在电报命令中使用正则表达式

时间:2017-09-19 13:33:05

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

以下代码为/start命令添加了命令处理程序:

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

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

我想到的是这个:

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

但它不能像预期的那样工作!相反,当我发送/^download

的非命令字符串时,它将起作用

我该怎么做?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

我建议您将所有命令称为/download,对用户友好。

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

您可以使用regexp创建自定义处理程序。例如,使用名称regexp_command handler.py创建新文件。然后在其中复制下面写的代码。现在您可以使用regexp作为处理程序参数。例如,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)