Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PythonBot - pass argument to command hanlder

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?

like image 399
Alessandro Gaballo Avatar asked Aug 07 '17 00:08

Alessandro Gaballo


2 Answers

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

like image 149
SergioR Avatar answered Nov 18 '22 08:11

SergioR


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".

like image 3
91DarioDev Avatar answered Nov 18 '22 07:11

91DarioDev