[Python] PyQt5 Application with PythonTelegramBot (PTB) coroutine

Discussão em 'Python' iniciado por Stack, Janeiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I'm struggling with running python-telegram-bot-21.10 as a coroutine to a PyQt5 application using Python-3.12.7 (intended to run on a Raspberry Pi).

    I had this setting operating for some years now with Python-3.9 and python-telegram-bot-13.6 by running the telegram-bot on a separate thread by instantiating a class ("TelegramBot") inheriting from QThread. From the main (PyQt5)-app, I simply called the .start() function on the instance of "TelegramBot", which per default calls the virtual run() function, (re)-implemented in the class, once the thread is started.

    from PyQt5.QtCore import QThread
    from telegram.ext import Updater, CommandHandler

    class TelegramBot(QThread):
    def __init__(self, parent=None):
    super(TelegramBot, self).__init__(parent)

    def run(self):
    self.updater = Updater(API_KEY, use_context = True)
    dp = self.updater.dispatcher
    #dp.add_handler(CommandHandler("start", self.start_command))
    self.updater.start_polling(5)

    def stop(self):
    self.updater.stop()
    self.quit()
    self.wait()


    However, trying to update the whole application to Python-3.12 and python-telegram-bot-21.10, I failed to achieve the same behaviour. From reading PTB's documentation, I think it's implementation changed in the newer versions to use asynchronous routines. I tried to update my TelegramBot class to the new syntax (using async-await), but getting RuntimeWarning: Enable tracemalloc to get the object allocation traceback:

    def run(self):
    application = ApplicationBuilder().token(API_KEY).build()

    application.add_handler(CommandHandler("start", self.start_command))
    application.run_polling(allowed_updates=Update.ALL_TYPES)

    async def start_command(self, update, context):
    await context.bot.send_message(chat_id=update.effective_chat.id, text='You sent /start!')


    Under consideration of this entry to use non blocking polling functions, i tried to run it without a separate thread like this:

    async def run(self):
    application = ApplicationBuilder().token(API_KEY).build()
    application.add_handler(CommandHandler('start', self.start))
    await application.initialize()
    await application.start()
    await application.updater.start_polling()


    by calling the followint from the main app/thread:

    self.bot = TelegramBot()
    asyncio.run(self.bot.run())


    But the bot basically just didn't respond to any requests, even though it didn't show any errors.

    I am fairly new to asynchronous programming and can't wrap my head around this. I would appreciate any hints in the right directions or alternative suggestion to optionally run a telegram bot as coroutine by pressing a button in a PyQt5-app!

    Continue reading...

Compartilhe esta Página