7
6

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 1 year has passed since last update.

【init】Google ColabでLINEおうむ返しBOTを爆速で動かす

Last updated at Posted at 2022-04-13

下準備

定数の定義

# LINEのチャネルシークレット
LINE_CHANNEL_SECRET = '下準備の値'
# LINEのチャネルアクセストークン
LINE_ACCESS_TOKEN = '下準備の値'
# ngrokのAuthtoken
NGROK_AUTHTOKEN = '下準備の値'

必要なライブラリのインストール&ngrokの初期化

!pip install flask
!pip install line-bot-sdk
!pip install pyngrok

!ngrok authtoken $NGROK_AUTHTOKEN

ngrokによるWebhook URL作成・設定

import os

from pyngrok import ngrok
from pyngrok.conf import PyngrokConfig

os.system('kill -9 $(pgrep ngrok)')
webhook_url = ngrok.connect(addr='127.0.0.1:5000', pyngrok_config=PyngrokConfig(start_new_session=True))
print (webhook_url)

出力された公開urlのhttpをhttpsに変更し、
https://developers.line.biz/console
[チャネル設定画面]>[Messaging API設定]内のWebhook URLに設定。

[Messaging API設定]>[LINE公式アカウント機能]>[あいさつメッセージ]の右側[編集]をクリック。
[応答メッセージ]をオフにし、[Webhook]をオンに変更。

おうむ返しBOTのプログラム入力

from flask import Flask, request, abort

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

app = Flask(__name__)

line_bot_api = LineBotApi(LINE_ACCESS_TOKEN)
handler = WebhookHandler(LINE_CHANNEL_SECRET)

@app.route("/test")
def test():
    return "TEST OK"

@app.route("/", 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友達登録

友達追加をして話しかけましょう。

7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?