4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

完成イメージ

7C9DFE3E-95C0-4172-B2D1-FDA25D8AE5D8.jpeg

前提条件

LINE BotとChatGPT APIが扱える環境

  • LINE Messaging API
  • GPT-3.5 Turbo API
  • Python3
  • ngrok

手順

1.OpenAI APIキーを取得する

2.各種インストール

$ pip3 install flask 
$ pip3 install line-bot-sdk==2.4.1
$ pip3 install openai

3.コードを記述する

app.py
import os, json
from flask import Flask, abort, request
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, FlexSendMessage
from openai import OpenAI

app = Flask(__name__)

access_token = os.environ["LINE_CHANNEL_ACCESS_TOKEN"]
channel_secret = os.environ["LINE_CHANNEL_SECRET"]
client = OpenAI()

line_bot_api = LineBotApi(access_token)
handler = WebhookHandler(channel_secret)

def generate_flex_message(theme):
    res = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "LINE Botで送信できるFlexメッセージをJSON形式で出力して。なお、JSON以外の文字列は含め
ないで。"},
            {"role": "user", "content": theme},
        ],
    )
    result = json.loads(res.choices[0].message.content)
    return result
    

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

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

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return "OK"


@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    try:
        msg = event.message.text
        if msg.startswith('!flex '):
            theme = msg.replace('!flex ', '')
            output_flex_message = generate_flex_message(theme)
            message = FlexSendMessage.new_from_json_dict(output_flex_message)
            line_bot_api.reply_message(
                reply_token=event.reply_token,
                messages=[message]
            )
    except Exception as e:
        print(e)
        
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=3000, debug=True)       

4.各種環境変数の設定

以下の3つの環境変数を設定します。
(OS等に応じて方法は異なります)

LINE_CHANNEL_ACCESS_TOKEN=LINEのチャネルアクセストークン
LINE_CHANNEL_SECRET=LINEのチャネルシークレット
OPENAI_API_KEY=OPENAIのAPIキー

5.サーバーを起動する

$ python3 app.py

6.ngrokを起動する

$ ngrok http 3000

Session Status                online                                                                                                  
Account                       user@example.com (Plan: Free)                                                                      
Update                        update available (version 3.5.0, Ctrl-U to update)                                                      
Version                       3.3.5                                                                                                   
Region                        Japan (jp)                                                                                              
Latency                       19ms                                                                                                    
Web Interface                 http://127.0.0.1:4040                                                                                   
Forwarding                    https://949b-2400-8500-2002-3178-160-251-212-25.ngrok-free.app -> http://localhost:3000     

7.LINEのWebHookにURLを登録する

LINE BotのWebHookに登録するURLは
表示されたURLのうち
Forwardingのhttpsの方 + /callback
という形にします。

今回の場合は

https://949b-2400-8500-2002-3178-160-251-212-25.ngrok-free.app/callback

です。

8.使い方

追加してトークを開き

「!flex 内容」
のようにメッセージを送信します。

AAA074F6-41A2-48E4-9342-42DB39649145.jpeg

参考文献

この記事は以下の情報を参考にして執筆しました。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?