|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +import re |
| 3 | + |
| 4 | +from telebot import util |
| 5 | + |
| 6 | + |
| 7 | +class MessageHandler: |
| 8 | + |
| 9 | + def __init__(self, handler, commands=None, regexp=None, func=None, content_types=None): |
| 10 | + self.handler = handler |
| 11 | + self.tests = [] |
| 12 | + if content_types is not None: |
| 13 | + self.tests.append(lambda m: m.content_type in content_types) |
| 14 | + |
| 15 | + if commands is not None: |
| 16 | + self.tests.append(lambda m: m.content_type == 'text' and util.extract_command(m.text) in commands) |
| 17 | + |
| 18 | + if regexp is not None: |
| 19 | + self.tests.append(lambda m: m.content_type == 'text' and re.search(regexp, m.text)) |
| 20 | + |
| 21 | + if func is not None: |
| 22 | + self.tests.append(func) |
| 23 | + |
| 24 | + def test_message(self, message): |
| 25 | + return all([test(message) for test in self.tests]) |
| 26 | + |
| 27 | + def __call__(self, update): |
| 28 | + if update.message is None: |
| 29 | + return |
| 30 | + |
| 31 | + if self.test_message(update.message): |
| 32 | + self.handler(update.message) |
| 33 | + |
| 34 | + |
| 35 | +class NextStepHandler: |
| 36 | + |
| 37 | + def __init__(self, handler, message): |
| 38 | + self.chat_id = message.chat.id |
| 39 | + self.handler = handler |
| 40 | + |
| 41 | + def __call__(self, update): |
| 42 | + if update.message is None: |
| 43 | + return |
| 44 | + |
| 45 | + if update.message.chat.id == self.chat_id: |
| 46 | + self.handler(update.message) |
| 47 | + |
| 48 | + |
| 49 | +class InlineHandler: |
| 50 | + |
| 51 | + def __init__(self, handler, func): |
| 52 | + self.handler = handler |
| 53 | + self.func = func |
| 54 | + |
| 55 | + def __call__(self, update): |
| 56 | + if update.inline_query is None: |
| 57 | + return |
| 58 | + |
| 59 | + if self.func(update.inline_query): |
| 60 | + self.handler(update.inline_query) |
| 61 | + |
| 62 | + |
| 63 | +class ChosenInlineResultHandler: |
| 64 | + |
| 65 | + def __init__(self, handler, func): |
| 66 | + self.handler = handler |
| 67 | + self.func = func |
| 68 | + |
| 69 | + def __call__(self, update): |
| 70 | + if update.chosen_inline_result is None: |
| 71 | + return |
| 72 | + |
| 73 | + if self.func(update.chosen_inline_result): |
| 74 | + self.handler(update.chosen_inline_result) |
| 75 | + |
| 76 | + |
| 77 | +class CallbackQueryHandler: |
| 78 | + |
| 79 | + def __init__(self, handler, func): |
| 80 | + self.handler = handler |
| 81 | + self.func = func |
| 82 | + |
| 83 | + def __call__(self, update): |
| 84 | + if update.callback_query is None: |
| 85 | + return |
| 86 | + |
| 87 | + if self.func(update.callback_query): |
| 88 | + self.handler(update.callback_query) |
0 commit comments