Receive the typed value from the user after the command in python telegram bot

Question:

For example, we have a command called a chart /chart Now I want to get the value that the user enters after this command

example: /chart 123456 now How should i get that 123456?
This is the code used to create the command:

def start(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /start is issued."""
    update.message.reply_text('Hi!')

I read the python telegram bot documents but did not find what I was looking for

Asked By: Mojtaba Delshad

||

Answers:

to get argument from command line we can use module sys

import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

$ python test.py arg1 arg2 arg3

Result:
Number of arguments: 4 arguments.
Argument List: [‘test.py’, ‘arg1’, ‘arg2’, ‘arg3’]

The code you provided is for when the user input the command /start.

Anyway, you can get the content of the input message directly from the Update and then split the message (because it returns everything that has been written, including the command itself) by the command and obtain the input arguments to the command, like this:

def chart(update: Update, context: CallbackContext) -> None:
    """Send a message with the arguments passed by the user, when the command /chart is issued."""
    input_mex = update.message.text
    input_args = input_mex.split('/chart ')[1]
    update.message.reply_text(input_args)

To make all working correctly, you will have to add a CommandHandler, like this:

updater = Updater(token=TOKEN, use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('chart', chart))

In this way the output for /chart 12345 will be just 12345, as shown in the picture:
command executed into the telegram chat

Answered By: marb

You can also do:

def chart(update: Update, context: CallbackContext) -> None:
    """Send a message with the arguments passed by the user, when the command /chart is issued."""
    input_args = context.args[0] # `context.args` is a list of all text sent after the command
    update.message.reply_text(input_args)
Answered By: HNipps
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.