J'ai créé mon premier chatbot avec la bibliothèque Chatterbot. Maintenant, je veux le déployer à travers Heroku, mais c'est impossible.Bibliothèque Chatterbot et déploiement Heroku
Mon chatbot est composé de quelques fichiers (py, csv, yml, json, txt). Voici la structure:
botusers (fichier csv) Magghy (fichier py) magghybot (fichier py) Procfile Exigences (fichier txt) telegramtoken (fichier txt) conversation.yml (dans le dossier nommé lang) math_words.json (dans le dossier nommé lang) NLTK (fichier txt) exécution (fichier txt)
I a créé un "Procfile" (travailleur: magghybot.py python) et "Requirements.txt"
Puis j'ai déployé mon projet sur Heroku et il n'y a pas de problème. Mais quand j'ai essayé de démarrer une conversation avec mon bot, ça ne me répond pas.
Quand j'écris sur les journaux Terminal héroïques, il n'y a pas de problème, mais seulement ce cordes:
2017-10-18T10:16:08.079891+00:00 heroku[worker.1]: Starting process with command python magghybot.py
2017-10-18T10:16:08.745016+00:00 heroku[worker.1]: State changed from starting to up
2017-10-18T10:16:10.087633+00:00 heroku[worker.1]: Process exited with status 0
2017-10-18T10:16:10.098959+00:00 heroku[worker.1]: State changed from up to crashed
2017-10-18T10:16:10.100468+00:00 heroku[worker.1]: State changed from crashed to starting
2017-10-18T10:16:14.445838+00:00 heroku[worker.1]: Starting process with command python magghybot.py
2017-10-18T10:16:14.982759+00:00 heroku[worker.1]: State changed from starting to up
2017-10-18T10:16:15.767656+00:00 heroku[worker.1]: Process exited with status 0
2017-10-18T10:16:15.782460+00:00 heroku[worker.1]: State changed from up to crashed
Il semble qu'il y ait un problème avec mes fichiers py.
Mon magghybot.py a ce code:
import sys
from inspect import getsourcefile
from os.path import abspath
from chatterbot import ChatBot
class MagghyBot(object):
def __init__(self, lang = "english"):
self.language = lang
self.chatbot = ChatBot(
'MagghyBot',
logic_adapters=[
"chatterbot.logic.MathematicalEvaluation",
"chatterbot.logic.TimeLogicAdapter",
"chatterbot.logic.BestMatch"
],
#input_adapter="chatterbot.input.VariableInputTypeAdapter",
#output_adapter="chatterbot.output.OutputAdapter"
trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
)
self.instdir = "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/chatterbot_corpus/data" + self.language + "/"
self.localdir = os.path.abspath(os.path.dirname(sys.argv[0])) + "/lang/" + self.language + "/chatcorpus/"
def train(self):
if self.checkdirnotempty(self.localdir):
print(self.localdir)
self.chatbot.train(
self.localdir
)
elif self.checkdirnotempty(self.instdir):
print(self.instdir)
self.chatbot.train(
self.instdir
)
else:
print("Using standard english corpus")
self.chatbot.train("chatterbot.corpus.english.greetings")
def reply(self, phrase = ""):
# Get a response to an input statement
response = self.chatbot.get_response(phrase)
return response
def checkdirnotempty(self, folder = ""):
check = False
if os.path.isdir(folder):
entities = os.listdir(folder)
for entity in entities:
if os.path.isfile(folder + entity):
check = True
break
return check
Mon Magghy.py a ce code:
import time
import random
import datetime
import telepot
import os
import sys
import subprocess
from magghybot import MagghyBot
telegramtoken = '' #telegram bot token from BotFather
checkuserid = 394287240 #enable users whitelist, so only certain people can talk with this bot
usersfile = 'botusers' #the file where we store the list of users who can talk with bot
attemptsfile = '/tmp/attempts.log' #the file where we log denied accesses
active = 1 #if set to 0 the bot will stop
language = "italiano"
chatter = MagghyBot(language)
chatter.train()
if telegramtoken == '' and os.path.isfile("telegramtoken.txt"):
text_file = open("telegramtoken.txt", "r")
telegramtoken = text_file.read().replace("\n", "")
text_file.close()
print("Connecting to Telegram...")
bot = telepot.Bot(telegramtoken)
print(bot.getMe())
def listusers():
if not os.path.isfile(usersfile):
return ''
text_file = open(usersfile, "r")
lines = text_file.read().split(',')
text_file.close()
del lines[-1] #remove last element since it is blank
return lines
def adduser(name):
csv = ""
users = listusers()
if users != "":
for usr in users:
csv = csv+usr+","
csv = csv+name+","
text_file = open(usersfile, "w")
text_file.write(csv)
text_file.close()
def deluser(name):
csv = ""
users = listusers()
if users != "":
for usr in users:
if usr != name:
csv = csv+usr+","
text_file = open(usersfile, "w")
text_file.write(csv)
text_file.close()
def handle(msg):
global bot
global chatter
global language
chat_id = msg['chat']['id']
sender = msg['from']['id']
users = listusers()
if checkuserid == 1:
verified = 0
if users != "":
for usr in users:
if str(sender) == usr:
verified = 1
if verified == 0:
bot.sendMessage(chat_id, "I don't talk with strangers, dear "+str(sender))
#write this user in the list of attempted accesses
if attemptsfile != '':
lines = ''
if os.path.isfile(attemptsfile):
text_file = open(attemptsfile, "r")
lines = text_file.read()
text_file.close()
lines = lines + str(datetime.datetime.now()) + " --- UserdID: " + str(sender) + " DENIED \n"
text_file = open(attemptsfile, "w")
text_file.write(lines)
text_file.close()
return
command = ''
try:
if msg['text'] != '':
command = msg['text']
print('Got command: ' + command)
except:
print("No text in this message")
if command == '/time':
bot.sendMessage(chat_id, str(datetime.datetime.now()))
elif '/adduser' in command:
if len(command.split(' ')) > 1:
usrname = command.split(' ')[1]
adduser(usrname)
bot.sendMessage(chat_id, "User "+usrname+" added")
elif '/deluser' in command:
if len(command.split(' ')) > 1:
usrname = command.split(' ')[1]
deluser(usrname)
bot.sendMessage(chat_id, "User "+usrname+" deleted")
elif command == '/help':
bot.sendMessage(chat_id, "/adduser /deluser /time /exit")
elif command == '/exit':
global active
active = False
bot.sendMessage(chat_id, "The bot will shutdown in 10 seconds")
elif command != '':
answer = chatter.reply(command)
bot.sendMessage(chat_id, str(answer))
bot.message_loop(handle)
print('I am listening ...')
while active:
time.sleep(10)
print("Exiting")
sys.exit()
Merci beaucoup, donc mon problème causé par les chemins locaux (self.instdir et self.localdir)? Dans le cas positif, je dois changer toute la structure, en utilisant Django. :( – Adryr83
Django n'est pas la seule façon de construire un Bot, je l'ai utilisé car il donne des choses utiles comme le panneau d'administration –
Essayez de conserver les données dans la base de données .Python a de jolies bibliothèques comme 'psycopg2' –