LoginSignup
12
14

More than 1 year has passed since last update.

Python、Lambda、API GatewayでLINEチャットBotを作る

Last updated at Posted at 2021-04-13

今回はline-bot-sdk-pythonを使わずにAWSのLambdaとAPI Gatewayでオウム返しLINEチャットボットを作ったので投稿します。AWS初心者が初めてのLambdaとAPI Gatewayに挑みました。

LINE Developersへのチャネル登録

を開いて「今すぐはじめよう」を押してチャンネルを作成してください。

AWS Lambdaの関数の作成

Lambdaの画面に遷移して関数を一から作成しましょう。
スクリーンショット 2021-04-13 16.28.13.png
関数名はLINEBot、ランタイムはPython 3.8 にします。そして関数の作成を押しましょう。

あとLambdaの環境設定を編集しましょう

スクリーンショット 2021-04-13 16.40.34.png

値のところにMessaging APIのChannel access token(めちゃくちゃ長いやつ)をコピペして保存してください。

ここから「lambda_function.py」を編集して実際にコードを書いていきます。

lambda_function.py の編集

lambda_function.py
import logging

import os
import urllib.request
import json

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    
    logger.info(event)
    
    # JSON文字列をPythonオブジェクトに変換してをeventsをループで回す
    for message_event in json.loads(event['body'])['events']:
        
        logger.info(json.dumps(message_event))
        
        url = 'https://api.line.me/v2/bot/message/reply'

        # リクエストヘッダー
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + os.environ['ACCESSTOKEN']
        }
        # リクエストボディ
        data = {
            'replyToken': message_event['replyToken'],
            'messages': [
                {
                    "type": "text",
                    "text": message_event['message']['text'],
                }
            ]
        }
        req = urllib.request.Request(url=url, data=json.dumps(data).encode('utf-8'), method='POST', headers=headers)
        
        with urllib.request.urlopen(req) as res:
            
            logger.info(res.read().decode("utf-8"))

loggerはCloud Watchでlogを出力しているのでなくてもいいです!

https://developers.line.biz/ja/reference/messaging-api/#send-reply-message
公式に下記のような方法でPOSTリクエストすれば良いと書いてありました。

HTTPリクエスト POST 
https://api.line.me/v2/bot/message/reply

リクエストヘッダー
Content-Type application/json
Authorization Bearer {channel access token}

リクエストボディ
replyToken Webhookで受信する応答トークン
messages 送信するメッセージ

そしてオウム返しするには下記のような構造になっていたので

"events":[{
"replyToken":"xxxxxxxxxxxxxxxxxxx",
"message":{"type":"text","id":"xxxxxxxxxxxxxxx","text":"こんにちは"}
}]

"text": message_event['message']['text']でオウム返しできる。

API Gatewayの設定

image.png

Lambdaの先ほど作成したLINEBotの「関数の概要」より、「トリガーを追加」ボタンを押します。「トリガーを選択」では「API GateWay」、「APIを作成する」をそれぞれ選択し、APIタイプは「HTTP」を選択します。セキュリティは今回は「オープン」を選択します。ここまでできたら「追加」ボタンを押します。

LINE.jpg

そして作成したトリガーのAPIエンドポイントをコピーしてMessaging APIのWebhookのURLに貼り付けます。

完成

IMG_6552.jpg

そうするとこのようにオウム返しチャットbotの完成です !!

参考文献

12
14
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
12
14