Python HTTP 实现中的未知错误

问题描述 投票:0回答:2

我有一个简单的电报机器人,需要写一个小于 10 的数字,它会延迟一秒将你从这个数字数到零。

我想创建一个请求队列。 如果机器人已经在统计数字,则回复该人员他已被添加到队列中,并执行队列中的任务。

我做到了,但是当机器人尝试处理第二个或第三个请求时,它会写入一个错误。

代码:

import time, asyncio
from threading import Thread
from telegram import ForceReply, Update
from telegram.constants import ParseMode
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters

TOKEN = ""

queue = []

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_html("Send me a number and I'll count from it to zero")
 
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    msg = update.message.text
    if msg.isdigit():
        msg = int(msg)
        if msg > 0:
            data = {'update': update, 'number': msg}
            queue.append(data)
            pos = len(queue)
            await update.message.reply_text(f"Please wait. you're {pos} in queue")
 
async def count_to_zero(num, update):
    for i in range(num, -1, -1):
            await update.message.reply_text(i)
            time.sleep(2)

def queue_handler() -> None:
    while True:
        if len(queue) > 0:
            update = queue[0]['update']
            num = queue[0]['number']
            asyncio.run(count_to_zero(num, update))
            del queue[0]

thread = Thread(target=queue_handler)
thread.start()

def main() -> None:
    # Create the Application and pass it your bot's token.
    application = Application.builder().token(TOKEN).build()
 
    # on different commands - answer in Telegram
    application.add_handler(CommandHandler("start", start))
 
    # on non command i.e message - echo the message on Telegram
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
 
    # Run the bot until the user presses Ctrl-C
    application.run_polling()
 
if __name__ == "__main__":
    main()

错误:

HTTP 实现中的未知错误:运行时错误(' 绑定到不同的事件循环')

我试图通过 异步 io.new_event_loop() asyncio.set_event_loop(循环)

但是在这种情况下,机器人本身没有启动,或者queue_handler函数没有工作

python queue python-asyncio telegram python-telegram-bot
2个回答
0
投票

问题在于,您在不同的线程(因此不同的事件循环)中使用

update
对象的方法,而不是创建它们。我强烈建议不要混合线程和异步。我非常有信心您的用例可以通过本机
asyncio
方法解决,甚至可以使用内置的 PTB
JobQueue


免责声明:我目前是

python-telgeram-bot
的维护者。


0
投票

我也有类似的案例。

我有许多不同的线程处理数据(例如通过 COM 端口、通过不同套接字等的数据) 由此,生成通过 Telegram 发送的消息。 数据线程和 Telegram 线程之间的交换是通过队列实现的。 对于旧的 python-telegram-bot,这工作得很好。我现在想更新到 20.5(因为我还需要更新我的 Python 版本)。

我现在不明白如何解决这个问题。如果可能的话,我只想更改我的 Telegram 实现(如果它也必须在 asyncio 上),而不是整个其他线程。

© www.soinside.com 2019 - 2024. All rights reserved.