我用Chatterbot库创建了我的第一个聊天机器人。现在我想通过Heroku部署它,但这是不可能的。
我的聊天机器人由一些文件(py,csv,yml,json,txt)组成。这是结构:
botusers(csv文件) Magghy(py文件) magghybot(py文件) Procfile 要求(txt文件) telegramtoken(txt文件) conversation.yml(在名为lang的文件夹中) math_words.json(在名为lang的文件夹中) nltk(txt文件) runtime(txt文件)
我创建了一个“Procfile”(worker:python magghybot.py)和“Requirements.txt”
然后我在Heroku上部署了我的项目,没有问题。但是当我试图与我的机器人开始对话时,它没有回答我。
当我在终端英雄日志上写字时,没有问题,只有这个字符串:
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
我的文件py似乎有问题。
我的magghybot.py有这段代码:
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
我的Magghy.py有这段代码:
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()
答案 0 :(得分:0)
我建议在Heroku上使用数据库而不是常规文件来存储数据。 Heroku是一个云托管,每次发布都可以在不同的机器上进行。这对磁盘使用量施加了一些限制。
这是我的实验项目 - 为Heroku部署准备的Django Telegram chatbot
https://github.com/lisitsky/dj-tg-alpha-bot
费尔可以自由地提出问题及其工作逻辑。