【问题标题】:using regular expressions in telegram commands在电报命令中使用正则表达式
【发布时间】:2017-09-19 13:33:04
【问题描述】:

好吧,下面的代码为/start 命令添加了一个命令处理程序:

dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start))

我想添加一个处理程序,它可以在一个处理程序中处理/download_video/download_music 等命令。

我想到的是这样的:

dp.add_handler(CommandHandler(r'^download', download))

但它没有按预期工作!相反,当我发送/^download 的非命令字符串时它会起作用

我应该怎么做?

【问题讨论】:

    标签: telegram telegram-bot python-telegram-bot


    【解决方案1】:

    迟到的答案。一种简单的方法是解析所有短信并检查它们是否以匹配的单词开头,即:

    from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
    import re
    
    def parse_msg(update, context):
        if re.search("^(/test|/something_else)$", update.message.text, re.IGNORECASE | re.DOTALL):
           update.message.reply_text("send your content")
    
    def main():
        updater = Updater("your_token", use_context=True)
        dp = updater.dispatcher
        dp.add_handler(MessageHandler(Filters.text, parse_msg)) # parses all text messages
        updater.start_polling()
        updater.idle()
    
    if __name__ == '__main__':
        main()
    

    • 通过发送以/test/something_else 开头的消息进行测试
    • 如果您打算在频道中使用此功能,请确保机器人有权阅读消息:
      • @Botfater > /setprivacy -> @bot_name -> Disable

    【讨论】:

      【解决方案2】:

      根据source code,只能将字符串作为CommandHandler参数传递。

      我建议你把所有命令都称为/download,这样对用户很友好。

      【讨论】:

        【解决方案3】:

        您可以使用正则表达式创建自定义处理程序。例如,创建名为 regexp_command handler.py 的新文件。然后把下面写的代码复制进去。现在您可以使用正则表达式作为处理程序参数。例如dispatcher.add_handler(RegexpCommandHandler(r'start_[\d]+', start))

        import re
        import warnings
        
        from telegram import Update
        from telegram.ext import Handler
        
        
        class RegexpCommandHandler(Handler):
            def __init__(self,
                         command_regexp,
                         callback,
                         filters=None,
                         allow_edited=False,
                         pass_args=False,
                         pass_update_queue=False,
                         pass_job_queue=False,
                         pass_user_data=False,
                         pass_chat_data=False):
                super(RegexpCommandHandler, self).__init__(
                    callback,
                    pass_update_queue=pass_update_queue,
                    pass_job_queue=pass_job_queue,
                    pass_user_data=pass_user_data,
                    pass_chat_data=pass_chat_data
                )
        
                self.command_regexp = command_regexp
        
                self.filters = filters
                self.allow_edited = allow_edited
                self.pass_args = pass_args
        
                # We put this up here instead of with the rest of checking code
                # in check_update since we don't wanna spam a ton
                if isinstance(self.filters, list):
                    warnings.warn('Using a list of filters in MessageHandler is getting '
                                  'deprecated, please use bitwise operators (& and |) '
                                  'instead. More info: https://git.io/vPTbc.')
        
            def check_update(self, update):
                if (isinstance(update, Update)
                    and (update.message or update.edited_message and self.allow_edited)):
                    message = update.message or update.edited_message
        
                    if message.text and message.text.startswith('/') and len(message.text) > 1:
                        command = message.text[1:].split(None, 1)[0].split('@')
                        command.append(
                            message.bot.username)  # in case the command was send without a username
                        print(command)
        
                        if self.filters is None:
                            res = True
                        elif isinstance(self.filters, list):
                            res = any(func(message) for func in self.filters)
                        else:
                            res = self.filters(message)
        
                        match = re.match(self.command_regexp, command[0])
        
                        return res and (bool(match) and command[1].lower() == message.bot.username.lower())
                    else:
                        return False
        
                else:
                    return False
        
            def handle_update(self, update, dispatcher):
                optional_args = self.collect_optional_args(dispatcher, update)
        
                message = update.message or update.edited_message
        
                if self.pass_args:
                    optional_args['args'] = message.text.split()[1:]
        
                return self.callback(dispatcher.bot, update, **optional_args)
        

        【讨论】:

          【解决方案4】:

          CommandHandler 接受元组/字符串列表作为输入,所以你可以这样做:

          dp.add_handler(CommandHandler(('download_video', 'download_music'), download))

          dp.add_handler(CommandHandler(['download_video', 'download_music'], download))

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-11-29
            • 1970-01-01
            • 2011-04-23
            • 2018-08-30
            • 2012-10-29
            • 2015-08-27
            相关资源
            最近更新 更多