6

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?

Dominique
  • 16,450
  • 15
  • 56
  • 112
jake wong
  • 4,909
  • 12
  • 42
  • 85
  • Where are you at in the setup process described in that tutorial? Have you followed the steps such as creating a channel, issuing a channel access token, and setting a the webhook url for your endpoint? – cody Nov 23 '18 at 15:05
  • @Cody Hello, thanks for your comment and answer! Seems like you were successful in implementing it in Python. It's quite late now and i'm extremely tired. I'll check out your answer tomorrow morning and write back? :) – jake wong Nov 23 '18 at 16:56

1 Answers1

0

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
    }
cody
  • 11,045
  • 3
  • 21
  • 36
  • Hi Cody, just taking a quick read first, I think in step 2, `webhook`, I did not perform this! Could you please share a little more about this AWS Lambda function? – jake wong Nov 23 '18 at 16:59
  • Basically, LINE needs an https endpoint to send your bot's events to for processing by your code. It does not need to be an AWS Lambda endpoint, I just chose that for the sake of convenience. It could be an endpoint on your own server. – cody Nov 23 '18 at 17:04
  • Hi Cody, i'm going to accept your answer because it solves the stated problem. However, Was wondering if you have the time, could you please share more about how you got AWS set up to receive the `webhook`? I have been trying for over a day now to understand more about AWS and set it up to receive the `webhook` request. But haven't been successful. Alternatively, if you don't mind, maybe we can take this offline and chat via email? – jake wong Nov 25 '18 at 08:44