线程中的Python Telegrambot

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

我有一个相对复杂的程序,它处理来自不同接口的数据。为此,每个接口都在自己的线程中运行。线程通过队列交换数据。 当某些事件发生时,我会通过 Telegram 收到通知。 我现在需要更新 Python 版本 (v3.8 -> v3.11),因此也需要更新 Telegram 库 (v8 ->v20.5)。

我现在在使用异步函数的新实现时遇到问题。

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

class TelegramBotHandler():
    def __init__(self):
        self.application = Application.builder().token(TOKEN).build()
        self.application.add_handler(CommandHandler("help", self.help_command))


    def runPolling(self):
        self.application.run_polling(allowed_updates=Update.ALL_TYPES)

    async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
        await update.message.reply_text("Help!")

    def queuehandler(self):
        while True:
            time.sleep(60)
            # Here I regularly process other thread data from the queue 
            self.application.bot.send_message(MSG_ID, "Hello World")

if __name__ == "__main__":
    telebot = TelegramBotHandler()
    telebotthread = threading.Thread(target=telebot.runPolling, args=())
    telebotthread.start()
    queuehandlerthread = threading.Thread(target=telebot.queuehandler, args=())
    queuehandlerthread.start()

不幸的是,我尝试了各种选择但没有成功。我想了解如何在线程中运行异步函数(现在似乎是 Telegram 库所要求的)。

python multithreading python-asyncio python-multithreading python-telegram-bot
1个回答
0
投票

要在异步函数之外运行异步函数,您可以使用

asyncio.run(function())

要在异步函数中运行它,您只需在函数调用之前使用await关键字,就像您在这里所做的那样

await update.message.reply_text("Help!")

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