imaginaryfriend/src/handler/command_handler.py

37 lines
1.2 KiB
Python
Raw Normal View History

2016-11-22 23:11:15 +01:00
from telegram import Update
2016-11-12 13:37:14 +01:00
from telegram.ext import Handler
2016-11-22 23:11:15 +01:00
from src.domain.command import Command
2016-12-04 14:13:04 +01:00
from .commands import commands
2016-11-12 13:37:14 +01:00
class CommandHandler(Handler):
2016-12-04 14:13:04 +01:00
def __init__(self):
2016-11-12 13:37:14 +01:00
super(CommandHandler, self).__init__(self.handle)
2016-12-04 14:13:04 +01:00
self.commands = commands
2016-11-16 20:42:00 +01:00
2016-11-12 13:37:14 +01:00
def check_update(self, update):
if isinstance(update, Update) and update.message:
message = update.message
2016-12-04 14:13:04 +01:00
return message.text \
and message.text.startswith('/') \
and Command.parse_name(message) in self.commands
2016-11-12 13:37:14 +01:00
else:
return False
2016-11-16 20:42:00 +01:00
2016-11-12 13:37:14 +01:00
def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
def handle(self, bot, update):
2016-12-01 22:01:04 +01:00
command = Command(update.message)
2016-11-12 13:37:14 +01:00
2016-11-12 23:55:48 +01:00
try:
2016-11-29 15:23:06 +01:00
self.commands[command.name](bot, command)
2016-11-12 13:37:14 +01:00
except (IndexError, ValueError):
2016-12-04 14:13:04 +01:00
bot.send_message(chat_id=command.chat_id,
reply_to_message_id=command.message.message_id,
text='Invalid command! Type /help')