Reputation: 770
I'm playing a little bit with Python Telegram Bot, I want to pass to my handler an argument obtained with previous computation, e.g:
def my_handler(bot, update, param):
print(param)
def main():
res = some_function()
updater.dispatcher.add_handler(CommandHandler('cmd', my_handler))
How do I pass param to the handler?
Upvotes: 9
Views: 22102
Reputation: 1456
On version 12 of python-telegram-bot, the arguments are located as a list in the attribute CallbackContext.args
. Here is a generic example:
def my_handler(update, context):
print(context.args)
def main():
res = some_function()
updater.dispatcher.add_handler(CommandHandler('cmd', my_handler))
A simple example would be summing two integer numbers:
import logging
from config import tgtoken
from telegram.ext import Updater, CommandHandler
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def sum(update, context):
try:
number1 = int(context.args[0])
number2 = int(context.args[1])
result = number1+number2
update.message.reply_text('The sum is: '+str(result))
except (IndexError, ValueError):
update.message.reply_text('There are not enough numbers')
def main():
updater = Updater(tgtoken, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("sum", sum))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
If you send /sum 1 2
, your bot will answer The sum is: 3
Upvotes: 17
Reputation: 1690
If you mean you want to pass to the function called by the handler the argument that the user sends with the command you should add the pass_args=True
parameter and it will returns arguments the user sent as a list.
So your code should be:
def my_handler(bot, update, args):
for arg in args:
print(arg)
def main():
res = some_function()
updater.dispatcher.add_handler(CommandHandler('cmd', my_handler, pass_args=True))
I didn't check it tho
If you instead are looking for a way to pass something you took from another handler to that handler related to the same user, that library has a nice parameter called "chat_data" and "user_data".
Upvotes: 2