LoginSignup
2
8

More than 3 years have passed since last update.

LINE BOT(雑談)を作る

Last updated at Posted at 2020-03-20

A3RTを使って雑談LINEBOTを作る

前回作成したLINE BOT(オウム返し)を作るを改良して、リクルートが提供しているA3RTのTalk APIを使って雑談するBOTを作った。

(1)A3RTからAPIKEYを取得する

A3RTのサイトで、APIKEYを発行する。

(2)A3RTの構造を確認する

前回作成したmain.pyを修正する前にA3RTの構造を確認する。
A3RTの構造を確認するために以下のコードを実行して、"おはよう"に対する回答をAIがちゃんと返してくれるか確認する。
まず、仮想環境でpya3rtをインストールして、

pip install pya3rt

以下をターミナルのpythonモードで実行してみる。

import pya3rt

apikey = "*******************************"
client = pya3rt.TalkClient(apikey)
reply_message = client.talk("おはよう")

print(reply_message)
{'status': 0,'message': 'ok','results': [{'perplexity': 0.07743213382788067, 'reply': 'おはようございます'}]}

となる。
replyの"おはようございます"を取得したいので、以下のように修正

import pya3rt

apikey = "****************************"
client = pya3rt.TalkClient(apikey)
reply_message = client.talk("おはよう")

print(reply_message['results'][0]['reply'])

すると、

おはようございます

となり、ちゃんと"おはよう"→"おはようございます"と返してくれた。
これを前回作成したmain.pyに組み込む。

(3)前回作成したmain.pyを修正

まず、上記のpya3rtの記述を以下のように関数化する。

def talk_ai(word):
    apikey = "****************************"
    client = pya3rt.TalkClient(apikey)
    reply_message = client.talk(word)
    return reply_message['results'][0]['reply']

前回作成したmain.pyを修正する。

main.py
from flask import Flask, request, abort
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)
import os
#追加
import pya3rt

app = Flask(__name__)

YOUR_CHANNEL_ACCESS_TOKEN = os.environ["YOUR_CHANNEL_ACCESS_TOKEN"]
YOUR_CHANNEL_SECRET = os.environ["YOUR_CHANNEL_SECRET"]

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)

@app.route("/")
def hello_world():
    return "hello world!"


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



@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    #(追加)talk_aiメソッドに引数を渡して返り値をai_messageに代入
    ai_message = talk_ai(event.message.text)
    line_bot_api.reply_message(
        event.reply_token,
        #TextSendMessage(text=event.message.txt))
        #(修正)ai_messageを返すようにする
        TextSendMessage(text=ai_message))

#(追加)pya3rtでai会話を返信
def talk_ai(word):
    apikey = "****************************"
    client = pya3rt.TalkClient(apikey)
    reply_message = client.talk(word)
    return reply_message['results'][0]['reply']

if __name__ == "__main__":
    port = int(os.getenv("PORT", 5000))
    app.run(host="0.0.0.0", port=port)

修正できたらrequirements.txtを更新して、

pip freeze > requirements.txt

あとは、Herokuにデプロイすれば完成。

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