How do I have my Bot respond with arguments?

旧街凉风 提交于 2020-01-02 01:17:07

问题


So I've built a Telegram bot, which can receive the following commands:

  • /list
  • /info 123

This works great, as I can catch /info and pass the additional arguments as ints. But, sadly, the Telegram clients don't see /info 123 as a complete command, but just the /info part. Is there a way to make it recognize the entirety of the command as the command?

I've tried Markdown-ing it: [/info 123](/info 123), but no joy. Is this possible?


回答1:


I've reached out to @BotSupport with the same question, and he/they/it responded swiftly with the following answer:

Hi, at the moment it is not possible to highlight parameters of a command. I any case, you may can find a workaround if you use correct custom keyboards ;) — @BotSupport

Custom keyboards may be an option for someone, but not for me. The solution I've gone for is to give the command as /info123. As the bot receives all / commands, I check if the received command starts with info, and if so, I remove the info part. I convert the remaining string/int to arguments, and pass that along to the relevant command.




回答2:


you can use RegexHandler() to do this.

Here is an example

def info(bot, update):
  id = update.message.text.replace('/info_', '')
  update.message.reply_text(id, parse_mode='Markdown')


def main():
  updater = Updater(TOKEN)
  updater.dispatcher.add_handler(RegexHandler('^(/info_[\d]+)$', info))
  updater.start_polling()

Usage

The command /info_120 will return 120
and /info_007 will return 007

UPDATE
for newer versions, you may use this method instead!

MessageHandler(Filters.regex(r'pattern'), callback)



回答3:


If you mean to pass the 123 as an argument for your command info and if you happen to use the python-telegram-bot, then here's how you do it:

dispatcher.add_handler(CommandHandler('hello', SayHello, pass_args=True))

According to the documentation: pass_args Determines whether the handler should be passed the arguments passed to the command as a keyword argument called args. It will contain a list of strings, which is the text following the command split on single or consecutive whitespace characters. Default is False.



来源:https://stackoverflow.com/questions/36059572/how-do-i-have-my-bot-respond-with-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!