0

Note: I have searched and read how to override a method defined in a module of a third party library.

The Python Telegram bot library utilizes callbacks/handlers. If we define this:

self.dispatcher.add_handler(CommandHandler("help", self.help))

Then self.help() will receive the args bot and update when a certain event occurs.

One of those args, bot, has a method called send_message. I want to prefix all of my bot's messages with a certain string. What I don't want:

  1. Do it manually each time in bot.send_message. like this: send_message(text= prefix + " Hello").

  2. Having to monkey patch the bot.send_message method, like suggested in the answer to the aforementioned question. I have several other methods besides self.help() and this doesn't seem to abide the DRY rule.

The challenge here seems to be that I'm receiving a new instance of bot each time the callback is fired.

What are my options, if any?

I'm calling bot.message() in a variety of ways (mixed args and kwargs). For example, parse_mode can be absent in some calls.

bot.send_message(
            chat_id=update.message.chat_id,
            text=txt,
            parse_mode=telegram.ParseMode.MARKDOWN,
        )
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
zerohedge
  • 3,185
  • 4
  • 28
  • 63

1 Answers1

1

If I understand correctly, you are calling bot.send_message() directly from your code. Presumably it's something like this:

bot = Bot(...)
bot.send_message("something")

You could make your own wrapper function that takes the bot instance and the message, and inserts the desired extra text:

def send_message_plus(bot, message):
    bot.send_message("This is extra " + message)

Then you would just call the wrapper function:

send_message_plus(bot, message)
John Gordon
  • 29,573
  • 7
  • 33
  • 58