Search code examples
pythontelegrampython-telegram-bot

`python-telegram-bot`: How do I pass additional arguments to callback functions?


I am tring to create a class that will manage my telegram bot and will handle interaction with other classes. However I can't find a way to pass self to the functions called in CommandHandler.

Here is a minimal example of the code I would like to be able to run; however it is not possible to pass the args argument to CommandHandler.

# minimal bot class

from telegram.ext import Application, CommandHandler

class Minimal_Example_Bot():
    def __init__(
            self,
            token,
            name:str,
            ):
        self.token=token
        self.name=name

    async def hi(self,update,context):
        await update.message.reply_text("{} says: 'Hi!!!'  ".format(args[0].name))
       
    def start(self):
        application = Application.builder().token(self.token).build()
        application.add_handler(CommandHandler("hi", self.hi, args=[self]))
        application.run_polling()
       
bot=Minimal_Example_Bot(token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", name="BestBot")
bot.start()

Do you know how I could achieve such a behavior? I would like to not have to add a bunch of global variables and functions.


Solution

  • I thought I would post the answer even if the solution is way simpler than expected.

    There is no need to pass anything extra. self.hi is a bound method of self, so you can readily use self in the method.

    Credits to the developers of python-telegram-bot