Image

(最終更新日: 19.09.2024)

Python チャットボットの動作をテストするために、あらかじめ用意された質問と回答を使用しました。事前設定済みの Telegram ボットサーバーを使用しました。このボットは、ファイル answers.txt に含まれるあらかじめ用意された質問と回答に基づいて応答し、ログを記録します。

インストールを始めましょう:

source my-tel-bot/bin/activate
pip install fuzzywuzzy
pip install python-Levenshtein

mkdir /root/my-tel-bot/data
chmod 775 /root/my-tel-bot/data

質問と回答を含むファイルを作成します:

nano /root/my-tel-bot/data/answers.txt

u: こんにちは
チャットボットがご挨拶します
u: 名前は何ですか
ボットの名前はバティニャです!
u: 何歳ですか
そんなに古くないですよ
u: 何ができますか
answers.txt ファイルにデータベースを追加できます

デモボットを既存のものに置き換えます:

/root/my-tel-bot/bot.py

import telebot
import os
from fuzzywuzzy import fuzz

# ボットを作成し、トークンを記入
bot = telebot.TeleBot('BotFatherから取得したトークン')

# フレーズと回答のリストを配列にロード
mas=[]
if os.path.exists('data/answers.txt'):
f=open('data/answers.txt', 'r', encoding='UTF-8')
for x in f:
if(len(x.strip()) > 2):
mas.append(x.strip().lower())
f.close()

# fuzzywuzzy を使って最も似ているフレーズを計算し、次の要素を回答として返す
def answer(text):
try:
text=text.lower().strip()
if os.path.exists('data/answers.txt'):
a = 0
n = 0
nn = 0
for q in mas:
if('u: ' in q):

# fuzzywuzzy を使って 2 つの文字列の類似度を取得
aa=(fuzz.token_sort_ratio(q.replace('u: ',''), text))
if(aa > a and aa!= a):
a = aa
nn = n
n = n + 1
s = mas[nn + 1]
return s
else:
return 'エラー'
except:
return 'エラー'

# 「スタート」コマンド
@bot.message_handler(commands=["start"])
def start(m, res=False):
bot.send_message(m.chat.id, 'オンラインです。こんにちはと書いてみてください )')

# ユーザーからのメッセージを取得
@bot.message_handler(content_types=["text"])
def handle_text(message):

# ログを記録
f=open('data/' + str(message.chat.id) + '_log.txt', 'a', encoding='UTF-8')
s=answer(message.text)
f.write('u: ' + message.text + '\n' + s +'\n')
f.close()

# 回答を送信
bot.send_message(message.chat.id, s)

# ボットを起動
bot.polling(none_stop=True, interval=0)

完了です。スクリプトにトークンを入力し、サービスを再起動するのを忘れないでください:

service my-tel-bot restart



No Comments Yet