0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【LINE Messaging API】Pythonでオウム返し BOTを作成

Last updated at Posted at 2019-12-02

##チュートリアル
image.png

####【メッセージを受信する場合】
WebhookHandlerを下記の様に設定
@handler.add(MessageEvent, message=TextMessage)

lineapi.py
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('YOUR_CHANNEL_ACCESS_TOKEN')
handler = WebhookHandler('YOUR_CHANNEL_SECRET')


@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:
        print("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'


@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__":
    app.run()

LINE Messaging API SDK for PythonSynopsis/Usageから引用

####【メッセージをリプライ】
reply message API( line_bot_api.reply_message)を呼ぶ
引数を、下記にすることで、オウム返しされる
・event.reply_token
TextSendMessage(event.message.text)

####<event>
handle_messageメソッドの引数(event)

event
{
  "message": {
    "id": "10951288714213",
    "text": "Hello",
    "type": "text"
  },
  "replyToken": "73fb2d4ab910457443a96c3483f478dc",
  "source": {
    "type": "user",
    "userId": "U0d47ada1d7ca738641228d4599c9d347"
  },
  "timestamp": 1574264703712,
  "type": "message"
}

##引用
LINE Messaging API SDK for Python

0
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?