Search code examples
pythondirect-line-botframework

line bot - how to get started


i've just started working with line-bot and followed the tutorial here: https://developers.line.biz/en/docs/messaging-api/building-bot/

However, I still don't understand how I can connect with my line app account, to send messages, and have these messages appear back in python.

The below is the script I copied from line tutorial.

from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage


app = Flask(__name__)

line_bot_api = LineBotApi('foo', timeout=20)
handler = WebhookHandler('bar')
user_profile = 'far'


@app.route("/", methods=['GET'])
def home():
    profile = line_bot_api.get_profile(user_profile)

    print(profile.display_name)
    print(profile.user_id)
    print(profile.picture_url)
    print(profile.status_message)
    return '<div><h1>ok</h1></div>'


@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'


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


if __name__ == "__main__":
    app.run(debug=True)

What am I missing, or how can I connect with the line app to send and receive messages?


Solution

  • I followed that tutorial and was able to successfully create a bot that just echoes messages in uppercase:

    example of interaction with bot

    Your question is how to "connect" your bot's code with the LINE app. The three most important parts of the tutorial are probably:

    1. Adding the bot as a friend, you do this by scanning its QR code with the LINE app
    2. When you create a channel for your bot, you need to enable "Webhooks" and provide an https endpoint which is where LINE will send the interaction events your bot receives. To keep this simple for the purposes of this answer, I created an AWS Lambda function and exposed it via API Gateway as an endpoint that looked something like: https://asdfasdf.execute-api.us-east-1.amazonaws.com/default/MyLineBotFunction. This is what I entered as the Webhook URL for my bot.
    3. Once you are successfully receiving message events, responding simply requires posting to the LINE API with the unique replyToken that came with the message.

    Here is the Lambda function code for my simple yell-back-in-caps bot:

    import json
    
    from botocore.vendored import requests
    
    def lambda_handler(event, context):
    
        if 'body' in event:
            message_event = json.loads(event['body'])['events'][0]    
            reply_token = message_event['replyToken']
            message_text = message_event['message']['text']
    
            requests.post('https://api.line.me/v2/bot/message/reply',
                data=json.dumps({
                    'replyToken': reply_token,
                    'messages': [{'type': 'text', 'text': message_text.upper()}]
                }),
                headers={
                    # TODO: Put your channel access token in the Authorization header
                    'Authorization': 'Bearer YOUR_CHANNEL_ACCESS_TOKEN_HERE',
                    'Content-Type': 'application/json'
                }
            )
    
        return {
            'statusCode': 200
        }