1

我是 python 新手,想通过使用谷歌应用引擎创建电报机器人来学习。我正在使用这个存储库项目https://github.com/yukuku/telebot作为我的机器人基础。在这个项目 main.py 中,我们可以找到这段代码:

if text.startswith('/'):
            if text == '/start':
                reply('Bot enabled')
                setEnabled(chat_id, True)
            elif text == '/stop':
                reply('Bot disabled')
                setEnabled(chat_id, False)
            elif text == '/image':
                img = Image.new('RGB', (512, 512))
                base = random.randint(0, 16777216)
                pixels = [base+i*j for i in range(512) for j in range(512)]  # generate sample image
                img.putdata(pixels)
                output = StringIO.StringIO()
                img.save(output, 'JPEG')
                reply(img=output.getvalue())
            else:
                reply("What command")

        # CUSTOMIZE FROM HERE
        elif 'who are you' in text:
            reply('telebot starter kit, created by yukuku: https://github.com/yukuku/telebot')
        elif 'what time' in text:
            reply('look at the top-right corner of your screen!')
        else:
            if getEnabled(chat_id):
                try:
                    resp1 = json.load(urllib2.urlopen('http://www.simsimi.com/requestChat?lc=en&ft=1.0&req=' + urllib.quote_plus(text.encode('utf-8'))))
                    back = resp1.get('res').get('msg')
                except urllib2.HTTPError, err:
                    logging.error(err)
                    back = str(err)
                if not back:
                    reply('okay...')
                elif 'I HAVE NO RESPONSE' in back:
                    reply('you said something with no meaning')
                else:
                    reply(back)
            else:
                logging.info('not enabled for chat_id {}'.format(chat_id))

但是,我想使用文本文件来丰富我的机器人知识而不是硬编码。文本文件将如下所示:

/fact1#I'm a robot
/fact2#I'm not human
/fact3#Stop talking to me

...ETC

我试过使用这样的代码:

d = {}
with open("data.txt") as f:
    for line in f:
        (key, val) = line.split("#")
        d[key] = val

for x in d.keys():
    if text==x:
        reply(d[x])

但是有些事情发生了,机器人停止回复。请帮我解决这个问题。提前致谢

4

0 回答 0