1

我正在使用 Telepot(python) 构建一个电报机器人,发生了一件奇怪的事情:

因为机器人应该继续运行,所以我设置了一个

while 1:
    time.sleep(.3)

在我的机器人结束时,就在我定义如何处理 MessageLoop 之后。

机器人有一些print()断言机器人正在设置(或者更好的是,它正在设置消息处理程序)并且它正在阅读聊天,等待任何输入。

问题是,如果我在没有

while 1:
    time.sleep(.3)

它打印消息并停止执行(没有循环等待新输入),但是如果我添加while 1: (...)代码,则在能够打印任何内容之前停止。

这是代码:

"""Launch the bot."""
import json
import telepot
from telepot.loop import MessageLoop
import time
from base import splitter
from base import handler

messageHandler = handler.Handler()

with open('triggers.json') as f:
    triggers = json.load(f)
with open('config.json') as f:
    config = json.load(f)

botKey = config['BOT_KEY']

# define the bot and the botname
bot = telepot.Bot(botKey)
botName = bot.getMe()['username']

# split commands in arrays ordered by priority
configSplitter = splitter.Splitter()
triggers = configSplitter.splitByPriority(triggers)

# define the handler
messageHandler.setBotname(botName)
messageHandler.setMessages(triggers)

# handle the messageLoop
print("setting up the bot...")
MessageLoop(bot, messageHandler.handle).run_as_thread()
print("Multibot is listening!")

# loop to catch all the messages
while 1:
    time.sleep(.3)

Python 版本:3.6 32 位

4

1 回答 1

0

解决方案是sys.stdout.flush()在各种print()恢复功能之后添加print(),而为了使代码再次工作,我不得不更改 Telepot 功能

MessageLoop(bot, messageHandler.handle).run_as_thread()

这不能正常工作:

bot.message_loop(messageHandler.handle)
于 2018-05-15T09:52:27.570 回答