python - 即使在while循环期间,如何让机器人轮询用户消息
问题描述
我正在构建一个电报机器人,它接受货币对并回复其数据。每当有变化时,机器人都应该继续发送与该货币对相关的数据,直到用户要求它停止或输入一个新的价值/货币对。我在处理程序中使用了一个 while 循环,但这会使脚本很忙,因此更新程序无法在循环期间查找新消息。这是处理程序
def reply(update: Update, context: CallbackContext):
"""Echo the user message."""
chat_type = update.effective_chat.type
if chat_type == "channel":
msg = update.channel_post.text.lower()
else:
msg = update.message.text.lower()
msgs = msg.split(',')
while True:
if len(msgs) > 1 and len(msgs) < 4:
convert = msgs[1].upper()
if len(msgs[0]) > 3:
name = msgs[0].capitalize()
else:
name = msgs[0].upper()
data = coindata(name=name, convert=convert)
if len(msgs) == 2:
response = data
elif len(msgs) == 3:
data_val = msgs[2]
response = f"currency: {name}" + f" convert: {convert}" + f" {data_val}: {data[data_val]}"
context.bot.send_message(chat_id=update.effective_chat.id, text=response)
time.sleep(20)
else:
response = "Wrong input"
context.bot.send_message(chat_id=update.effective_chat.id, text=response)
time.sleep(20)
这是开始轮询的主要方法。
def main() -> None:
"""Start the bot."""
# Create the Updater and pass it bot's token.
updater = Updater(token=TOKEN)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help))
dispatcher.add_handler(MessageHandler(Filters.text, reply))
# Start the Bot
updater.start_polling()
updater.idle()
我知道问题所在。但是,不知道解决方案。在运行回复循环时,机器人应该仍然能够接收新消息。
怎么做到呢?
解决方案
推荐阅读
- reactjs - 在组件 onClick 中反应加载
- javascript - 窗口加载显示保存的 innerHTML 但不读取 innerHTML 的类名
- swift - 如何修改实体的核心数据属性,但修改数据库的所有元素
- jquery - 使用 jQuery 使用 clone() 插入行后删除行
- xpath - 如何使用 importxml 和 xPath 加载这个“标签”
- vba - 我可以使用宏在 Google Docs 中添加一个按部分统计项目符号的实时计数器吗?
- python-3.x - 尝试连接数据库 MongoDB 时,Docker 容器返回 Connection denied
- javascript - Next.js 中动态导入模块的单例对象
- android - 堆栈在列内不起作用 - 颤振
- reactjs - 在 hooks setState 之后执行下一行代码的后果是什么?