首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Chatterbot库和Heroku部署

Chatterbot库和Heroku部署
EN

Stack Overflow用户
提问于 2017-10-19 01:36:04
回答 1查看 529关注 0票数 0

我用聊天机器人库创建了我的第一个聊天机器人。现在我想通过Heroku部署它,但这是不可能的。

我的聊天机器人由一些文件(py、csv、yml、json、txt)组成。结构是这样的:

僵尸用户(csv文件) Magghy (py文件) magghybot (py文件)过程文件要求(txt文件) telegramtoken (txt文件) conversation.yml (在名为lang的文件夹中) math_words.json (在名为lang的文件夹中) nltk (txt文件)运行时(txt文件)

我创建了一个"Procfile“(worker: python magghybot.py)和"Requirements.txt”

然后我在Heroku上部署了我的项目,没有问题。但当我试图与我的机器人开始对话时,它没有回答我。

当我在终端英雄日志上写的时候,没有问题,只有这个字符串:

代码语言:javascript
复制
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代码是这样的:

代码语言:javascript
复制
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代码是这样的:

代码语言:javascript
复制
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()

EN

回答 1

Stack Overflow用户

发布于 2017-10-19 02:00:02

我建议使用Heroku上的数据库而不是常规文件来存储数据。Heroku是一个云主机,每次发布都可以在不同的机器上进行。这对磁盘使用施加了一些限制。

这是我的实验项目- Django Telegram聊天机器人为Heroku部署准备的

https://github.com/lisitsky/dj-tg-alpha-bot

你可以自由地对它和它的工作逻辑提出问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46816044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档