Image

(마지막 변경: 19.09.2024)

Python 채팅 봇의 성능을 테스트하기 위해 우리는 미리 구성된 질문과 답변을 사용했습니다. 텔레그램 봇 서버. 이 봇은 미리 준비된 질문에 답할 수 있습니다. 즉, 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: hello
Welcome to the chatbot
u: what is your name
Bro Bot!
u: how old are you
relatively few
u: what can you do
You can add to my database in the answers.txt file

데모 봇을 기존 로봇으로 교체해 보겠습니다:

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

import telebot
import os
from fuzzywuzzy import fuzz

# Create a bot, write your own token
bot = telebot.TeleBot('Key received from @BotFather')

# Loading a list of phrases and answers into an array
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()

# Using fuzzywuzzy, we calculate the most similar phrase and give the next element of the list as an answer
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):

# Using fuzzywuzzy we get how similar two strings are
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 'Error'
except:
return 'Error'

# /Start Command
@bot.message_handler(commands=["start"])
def start(m, res=False):
bot.send_message(m.chat.id, 'I am in touch. Write me hello )')

# Receiving messages from a user
@bot.message_handler(content_types=["text"])
def handle_text(message):

# Logging
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()

# Sending a response
bot.send_message(message.chat.id, s)

# Launching the bot
bot.polling(none_stop=True, interval=0)

완료되었습니다. 스크립트에 키 토큰을 지정하고 서비스를 다시 시작하는 것을 잊지 마세요:

service my-tel-bot restart



No Comments Yet