Skip to content

Commit

Permalink
commands setup & usage simplified
Browse files Browse the repository at this point in the history
  • Loading branch information
lavadk committed Apr 12, 2021
1 parent 472a99d commit b55899c
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 55 deletions.
24 changes: 9 additions & 15 deletions liker/command/handler_set_reactions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import inject
import logging
from tengine.command.command_handler import *
from tengine import TelegramBot, telegram_bot_utils
from tengine import Config
from tengine import telegram_bot_utils

from liker.state.enabled_channels import EnabledChannels
from liker.enabling_manager import EnablingManager
Expand All @@ -12,8 +11,6 @@

class CommandHandlerSetReactions(CommandHandler):
enabled_channels = inject.attr(EnabledChannels)
telegram_bot = inject.attr(TelegramBot)
config = inject.attr(Config)
enabling_manager = inject.attr(EnablingManager)

def get_cards(self) -> Iterable[CommandCard]:
Expand All @@ -23,38 +20,35 @@ def get_cards(self) -> Iterable[CommandCard]:
]

def handle(self,
config: Config,
chat_id,
message: Message,
args: Namespace,
telegram_bot: TelegramBot,
command_parser: CommandParser):
sender_chat_id,
sender_message: Message,
args: Namespace):
if args.command == '/set_reactions':
channel_id = args.channel_id
if channel_id is None:
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text='--channel_id required')
return

reactions = args.reactions
if (reactions is None) or (len(reactions) == 0):
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text='--reactions required')
return

if not telegram_bot_utils.is_proper_chat_id(channel_id):
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text='channel_id should be a number or start from @')
return

set_successfully = self.enabling_manager.try_set_reactions(channel_id=channel_id,
reactions=reactions,
reply_to_chat_id=chat_id)
reply_to_chat_id=sender_chat_id)
if not set_successfully:
return

logger.info(f'set_reactions {channel_id}, {reactions}')
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text=f'for {channel_id} reactions are {reactions}')
else:
raise ValueError(f'Unhandled command: {args.command}')
Expand Down
27 changes: 11 additions & 16 deletions liker/command/handler_take_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,15 @@
import time
from telebot.apihelper import ApiTelegramException
from tengine.command.command_handler import *
from tengine import TelegramBot, TelegramApi, telegram_api_utils, Config, telegram_error
from tengine import TelegramBot, TelegramApi, telegram_api_utils, telegram_error

from liker.setup import constants

logger = logging.getLogger(__file__)


class CommandHandlerTakeMessage(CommandHandler):
telegram_bot = inject.attr(TelegramBot)
telegram_api = inject.attr(TelegramApi)
config = inject.attr(Config)

def get_cards(self) -> Iterable[CommandCard]:
return [CommandCard(command_str='/take_messages',
Expand All @@ -22,28 +20,25 @@ def get_cards(self) -> Iterable[CommandCard]:
]

def handle(self,
config: Config,
chat_id,
message: Message,
args: Namespace,
telegram_bot: TelegramBot,
command_parser: CommandParser):
sender_chat_id,
sender_message: Message,
args: Namespace):
if args.command == '/take_messages':
channel_id = args.channel_id
if channel_id is None:
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text='--channel_id required')
return

prev_bot_token = args.bot_token
if prev_bot_token is None:
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text='--bot_id required')
return

from_message_id = args.message_id
if from_message_id is None:
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text='--message_id required')
return

Expand All @@ -59,7 +54,7 @@ def handle(self,
period = 60 / self.config['channel_rate_per_minute']
response_text = f'There are {n_messages:,} messages, will take approximately {n_messages * period:,.0f} ' \
f'seconds. Bot will not to respond to other commands and buttons clicks till finish'
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text=response_text)
n_processed = 0
for msg in arr_messages:
Expand All @@ -68,7 +63,7 @@ def handle(self,
# Verbose
if True:
if (n_processed > 0) and (n_processed % constants.TAKE_MESSAGE_VERBOSE_N == 0):
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text=f'Processed {n_processed:,} messages')
n_processed += 1

Expand All @@ -92,7 +87,7 @@ def handle(self,
raise ex
except Exception as ex:
try:
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text=f'Error processing message {msg.id}: {str(ex)}')
except ApiTelegramException as ex:
logger.exception(ex)
Expand All @@ -102,7 +97,7 @@ def handle(self,
raise ex

logger.info(f'take_messages done {channel_id}')
self.telegram_bot.send_text(chat_id=chat_id,
self.telegram_bot.send_text(chat_id=sender_chat_id,
text=f'for {channel_id} message(s) were taken')
else:
raise ValueError(f'Unhandled command: {args.command}')
22 changes: 8 additions & 14 deletions liker/command/handler_update_markup.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import inject
import logging
from tengine.command.command_handler import *
from tengine import TelegramBot
from tengine import Config
from telebot.types import InlineKeyboardMarkup

from liker.state.enabled_channels import EnabledChannels
Expand All @@ -14,7 +12,6 @@


class CommandHandlerUpdateMarkup(CommandHandler):
telegram_bot = inject.attr(TelegramBot)
enabled_channels = inject.attr(EnabledChannels)
space_state = inject.attr(SpaceState)

Expand All @@ -25,23 +22,20 @@ def get_cards(self) -> Iterable[CommandCard]:
]

def handle(self,
config: Config,
chat_id,
message: Message,
args: Namespace,
telegram_bot: TelegramBot,
command_parser: CommandParser):
sender_chat_id,
sender_message: Message,
args: Namespace):
if args.command == '/update_markup':
ref_message: Message = message.reply_to_message
ref_message: Message = sender_message.reply_to_message
if (ref_message is None) or (ref_message.forward_from_chat is None):
telegram_bot.send_text(chat_id=chat_id,
text='Send /update_markup in comments to target channel post')
self.telegram_bot.send_text(chat_id=sender_chat_id,
text='Send /update_markup in comments to target channel post')
return

channel_id = ref_message.forward_from_chat.id
if not self.enabled_channels.is_enabled(str(channel_id)):
telegram_bot.send_text(chat_id=chat_id,
text='Liker is not enabled for the given channel')
self.telegram_bot.send_text(chat_id=sender_chat_id,
text='Liker is not enabled for the given channel')
return

channel_message_id = ref_message.forward_from_message_id
Expand Down
2 changes: 1 addition & 1 deletion liker/custom_markup/markup_synchronizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def update(self):
self.telegram_bot.bot.edit_message_reply_markup(chat_id=ch_id,
message_id=m_id,
reply_markup=reply_markup)
# We don't break loop for all exceptions except TOO_MANY_REQUESTS to avoid infitie error loop
# We don't break loop for all exceptions except TOO_MANY_REQUESTS to avoid infinite error loop
except ApiTelegramException as ex:
if ex.error_code == telegram_error.TOO_MANY_REQUESTS:
logger.error(f'Got TOO_MANY_REQUESTS error, will skip current channel update: {ex}')
Expand Down
28 changes: 20 additions & 8 deletions liker/setup/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,27 @@ def bind_app_dependencies(binder: Binder):
lambda: TelegramCursor(bot=inject.instance(TelegramBot),
look_back_days=constants.BOT_LOOK_BACK_DAYS,
long_polling_timeout=constants.LONG_POLLING_TIMEOUT))

def get_handler_params() -> dict:
return {
'config': inject.instance(Config),
'telegram_bot': inject.instance(TelegramBot),
}
binder.bind_to_constructor(CommandHandlerPool, lambda: CommandHandlerPool(handlers=[
CommandHandlerEssentials(get_parser=lambda: inject.instance(CommandParser),
**get_handler_params()),
CommandHandlerPassword(**get_handler_params()),
CommandHandlerConfig(**get_handler_params()),
CommandHandlerSetReactions(**get_handler_params()),
CommandHandlerUpdateMarkup(**get_handler_params()),
CommandHandlerTakeMessage(**get_handler_params()),
]))
binder.bind_to_constructor(CommandParser, lambda: CommandParser(handler_pool=inject.instance(CommandHandlerPool),
params=command_params))
binder.bind_to_constructor(CommandHub, lambda: CommandHub(config=inject.instance(Config),
handler_classes=[CommandHandlerEssentials,
CommandHandlerPassword,
CommandHandlerConfig,
CommandHandlerSetReactions,
CommandHandlerUpdateMarkup,
CommandHandlerTakeMessage],
params=command_params,
telegram_bot=inject.instance(TelegramBot)))
telegram_bot=inject.instance(TelegramBot),
parser=inject.instance(CommandParser),
handler_pool=inject.instance(CommandHandlerPool)))
binder.bind_to_constructor(MessagesLogger,
lambda: MessagesLogger(dir_path=constants.messages_log_dir(),
file_name_prefix=constants.MESSAGES_LOG_PREFIX,
Expand Down
2 changes: 1 addition & 1 deletion tengine

0 comments on commit b55899c

Please sign in to comment.