1: posts
Reading ModeRO
$ cat 20191024_linebot-responder.md

#Building a LINE echo bot with Responder

Date:2019-10-24 (Thu)
>Creating a Python webhook with Responder and connecting it to the LINE Messaging API.

I built a LINE bot using Responder, a then-new Python web framework.
I ran into a couple of snags and found little about them in Japanese, so I wrote up the process.

##In this article

  • Build a Responder bot that echoes a LINE user’s message

##What is Responder?

Responder takes ideas from established Python web frameworks such as Django and Flask.
I have used Flask before, but it was difficult to implement asynchronous processing with Flask.
On the other hand, with Responder, you can easily implement asynchronous processing using async/await.
It is a very smart web framework that is expected to see more users in the future.

##Setting up Responder

Since Responder is registered on PyPI, it can be easily installed with pip.

Bash
pip install responder

I will not explain the detailed usage of Responder here.
There is a page that explains things in detail, so it would be good to refer to that.

For a hands-on introduction, I also recommend this article:
I also learned this way.

##Building an echo bot

The Flask example is a LINE bot that sends the user’s message back to them.
It makes a useful starting point for other bots.

The LINE Messaging API needs an HTTPS webhook endpoint.
A host such as Heroku was convenient if you wanted it to handle the certificate.

Here’s my Responder version of the echo bot:

Python
import responder
import json

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage
)

api = responder.API()

# LINE settings
line_bot_api = LineBotApi("LINE_ACCESS_TOKEN")   # ここにACCESS TOKENを入力
handler = WebhookHandler("LINE_CHANNEL_SECRET")  # ここにCHANNEL SECRETを入力

@api.route('/callback')
class LINEbot:
    async def on_post(self, req, resp):
        # get X-Line-Signature header value
        signature = req.headers['X-Line-Signature']

        # get request body as text
        body = await req.media()
        body = json.dumps(body, ensure_ascii=False).replace(' ', '')

        try:
            # handle webhook body
            handler.handle(body, signature)
            resp.status_code = 200
            resp.text = 'OK'
        except InvalidSignatureError as e:
            print(e)
            resp.status_code = 400
            resp.text = e

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=event.message.text)
    )

if __name__ == '__main__':
    api.run(address='0.0.0.0')

Most of the code is much the same as the Flask example.
One detail repeatedly caught me out:
verifying the request signature.

No matter how many times I tried, I kept getting InvalidSignatureError.
I looked up the verification code in the LINE Python SDK. Here’s what it does:
The example above already runs on its own. The rest of this section explains what caused the error for me.

Python
if hasattr(hmac, "compare_digest"):
    def compare_digest(val1, val2):
        """compare_digest function.
        If hmac module has compare_digest function, use it.
        Or not, use linebot.utils.safe_compare_digest.
        :param val1: string or bytes for compare
        :type val1: str | bytes
        :param val2: string or bytes for compare
        :type val2: str | bytes
        :rtype: bool
        :return: result
        """
        return hmac.compare_digest(val1, val2)
else:
    def compare_digest(val1, val2):
        """compare_digest function.
        If hmac module has compare_digest function, use it.
        Or not, use linebot.utils.safe_compare_digest.
        :param val1: string or bytes for compare
        :type val1: str | bytes
        :param val2: string or bytes for compare
        :type val2: str | bytes
        :rtype: bool
        :return: result
        """
        return safe_compare_digest(val1, val2)

class SignatureValidator(object):
    """Signature validator.
    https://developers.line.biz/en/reference/messaging-api/#signature-validation
    """

    def __init__(self, channel_secret):
        """__init__ method.
        :param str channel_secret: Channel secret (as text)
        """
        self.channel_secret = channel_secret.encode('utf-8')

    def validate(self, body, signature):
        """Check signature.
        :param str body: Request body (as text)
        :param str signature: X-Line-Signature value (as text)
        :rtype: bool
        """
        gen_signature = hmac.new(
            self.channel_secret,
            body.encode('utf-8'),
            hashlib.sha256
        ).digest()

        return compare_digest(
            signature.encode('utf-8'), base64.b64encode(gen_signature)
        )

In outline, the SDK verifies an incoming LINE request like this:

  1. Compute an HMAC-SHA256 of the request body using the channel secret as the key.
  2. Compare its Base64 encoding with the signature in the header. Raise InvalidSignatureError if they differ.

LINE signs the request using the same procedure, so using a different channel secret causes verification to fail.

While debugging I noticed that json.dumps() inserted spaces when converting the parsed dictionary back to a string.
The body LINE had signed in my test appeared to use compact JSON. Once I removed the extra spaces, the calculated value matched the signature in the header.
At this point the bot was echoing my messages back to me.

##Wrapping up

This gave me a working LINE echo bot built with Responder.
I liked how little work it took to write an asynchronous handler, and I’d like to use Responder again.

## Comments

"20191024_linebot-responder.md" [readonly]2L, 6257B
utf-8100%