LoginSignup
2
6

More than 1 year has passed since last update.

iPadでChatGPT APIを用いたLINE botを作ってみた。

Last updated at Posted at 2023-03-15

ChatGPTにハマっており、ほぼ知識のない状態でChatGPT APIを用いたLINE botを作ってみた。

pythonista3では、openaiのインストールが出来ない!などの作成までのトラブルは全て割愛して、下記に手順を記載する。

工程としては、⒈Google Colabでノートブックを作成→⒉LINE公式とDeveloperのアカウントを作成→⒊LINEの設定と必要な情報を取得する。→⒋webhook用にngrokのアカウントを作成→⒌openaiのAPIキーを取得する→⒍コードを書く→完成!

⒈Google Colabで新規ノートブックを作成する

Google Colabにアクセスする。
ノートブックを新規作成を押す。AB93618A-0566-475D-9D9D-9F4736A2D45C.jpeg

コードを書くノートブックが出来る。83767E4A-7BED-439E-8148-0A5507DA240F.jpeg

⒉ LINE公式とDeveloperのアカウントを作成する

LINE公式のHPからは何故かアカウントを作成出来ないので、こちらの公式LINEアプリをダウンロードして、指示に従いアカウントを作成する。

公式LINEアカウントが作成出来たらDeveloperのサイトにアクセスして、先程作成した LINE公式のアカウントでログインして、Developerのアカウントを作成する。

※この手順で上手くいかない場合、公式の説明がわかりやすいので、参照してみて下さい。

⒊ LINEの設定と必要な情報を取得する

まず、こちらからLINE Developersコンソールを開き、こちらの手順でチャネルを作成する。

チャネルを作成したら、作成したチャネルを開き「チャネル基本設定」から「チャネルシークレット」と、「Messaging API設定」から「チャネルアクセストークン」を取得して、すぐ使えるところにメモする。

ウェブ版のLINE公式のアカウントページにアクセスして、メッセージを全てオフにする。
上手くいくとコンソールのMessaging API設定のLINE公式アカウント機能が以下のようになる。6DBBFEA3-8107-47C6-9FC4-9DEEAD3B3A12.jpeg

⒋webhook用にngrokのアカウントを作成する

LINEのwebhookにhttpsが必要なので、ngrokにアクセスしてアカウントを作成する。

アカウントを作成したらログインして、左のメニューからYour Authtokenを選択してYour Authtokenを取得してすぐ使えるところにメモする。

⒌openaiのAPIキーを取得する

こちらのサイトを参考にopenaiのAPIキーを取得する。

⒍コードを書く

まず、⒈で作成したGoogle Colabのノートブックを開く。この際にブラウザをPCモードにしておくと使いやすい。

⒈これまでに集めたトークンなどを書く。

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

⒉openaiをインストールする。私は普通に!pipでインストール出来なかったので、以下のようにしています。

!pip install --upgrade pip
!pip install setuptools wheel
!pip install openai

⒊ngrokやLINE等をインストールする

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

!ngrok authtoken $NGROK_AUTHTOKEN

⒋webhook用のhttpsを作成する

import os

from pyngrok import ngrok
from pyngrok.conf import PyngrokConfig


os.system('kill -9 $(pgrep ngrok)')

https_tunnel = ngrok.connect(addr='127.0.0.1:5000',bind_tls=True)
print(https_tunnel)

⒍ChatGPT付きLINE botを作成する

import openai

openai.api_key = ''
# openaiの APIキー


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):
 text = event.message.text
 response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "任意の設定を書く。例:占い師になって下さい。"},  {"role": "user", "content": text},
    ]
)
 line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=response["choices"][0]["message"]["content"]),
    )

if __name__ == '__main__':
    app.run()

⒎⒍だと記憶がなくコミュニケーションにならないので、⒍のコードを下記に変更する。

import openai

openai.api_key = ''
# openaiの APIキー

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'


assist1 = ""  # 初期化

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    global assist1  # assist1をグローバル変数にする

    text = event.message.text
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "任意の設定を書く。例:占い師になって下さい。"},
            {"role": "assistant", "content": assist1},
            {"role": "user", "content": text},
        ]
    )
    assist1 = response["choices"][0]["message"]["content"]  # assist1を更新
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=response["choices"][0]["message"]["content"]),
    )


if __name__ == '__main__':
    app.run()

⒏ランタイムの項目から全てのセルを実行する。

⒐⒌のコード実行後に現れる数字が多い方のURLをコピーして、 LINE DevelopersのチャネルのMessaging API設定のWebhook設定にコピーしたURLを入れて、Webhookの利用をオンにする。
※検証を押してエラーの場合、どこかで失敗しています。
※実行するたびにURLが更新される為、実行するたびに再設定が必要です。

10.自分とLINE botを友達にして自分から話しかけてみる。以下のように返答が返ってきたら成功!!061EA3E6-7EA1-4048-B5EF-DD7E5EE0EBB0.jpeg

最後に

以上のようにして、ほぼ知識のない私でもChatGPTを用いたLINE botを作成出来ました。
わからないことはbingに聞いて、足りないコードはChatGPTに書いてもらうと誰でも簡単な開発は出来るのだなと思いました。
また何か作ってみます。

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