skip to Main Content

I haven’t found ANYTHING about this online. I’ve read the documentation but understandably absolutely failed to understand it. I also haven’t found anything about (custom) commands in it directly.

I know that you can add a /start command for example by doing :

# Help command
def help_command(update, context):
    update.message.reply_text("This is the help")

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

After which you can use /help to display the help. But what if I want to add my own command? (which I know is possible since I saw bots that have them)

I wanted to make a command that would make all text that the user sent uppercase. It would work by writing /uppercase after which the user would send the message and the bot would reply with the text all uppercase. So I went ahead and create a new function :

# Custom commands
def uppercase_command(update, context):
    update.message.reply_text('Send any 📄 message to make it uppercase. ⬆')
    text = update.message.text
    update.message.reply_text(text).upper()

dispatcher.add_handler(CommandHandler("uppercase", uppercase_command))

Which doesn’t work and the bot responds with "Unknown command". How can I add a custom command?

2

Answers


  1. There is (almost) nothing wrong with the code that you showed. The only thing that comes to mind about uppercase_command is the wrong placement of upper that furas already pointed out in the comments.

    Which doesn’t work and the bot responds with "Unknown command". How can I add a custom command?

    If the bot actually sends Unknown command as a text message in the chat, this must be because you coded it to. That is, the update is already handled by another handler with probably prevents your CommandHandler("uppercase", uppercase_command) from handling the update. Please carefully read the documentation of Dispatcher.add_handler and double check that you add your handlers in the right order.

    If you want that your command shows up in the auto-completion in the app, you can either use Bot.set_my_commands for that or set it up with @BotFather.

    In order to show errors, please see here and here.


    Disclaimer: I’m currently the maintainer of python-telegram-bot.

    Login or Signup to reply.
  2. @dp.message_handler(text=['message'])
    async def command_1(message : types.Message):
        await bot.send_message(message.from_user.id, "answer?")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search