Skip to content

Commit

Permalink
/take_messages
Browse files Browse the repository at this point in the history
  • Loading branch information
lavadk committed Apr 10, 2021
1 parent 542f9d9 commit b859474
Show file tree
Hide file tree
Showing 13 changed files with 104 additions and 21 deletions.
1 change: 1 addition & 0 deletions data/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/state
/logs
/csv_logs
/*.session
4 changes: 2 additions & 2 deletions liker/command/handler_set_reactions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import inject
import logging
from tengine.command.command_handler import *
from tengine import TelegramBot, telegram_utils
from tengine import TelegramBot, telegram_bot_utils
from tengine import Config

from liker.state.enabled_channels import EnabledChannels
Expand Down Expand Up @@ -42,7 +42,7 @@ def handle(self,
text='--reactions required')
return

if not telegram_utils.is_proper_chat_id(channel_id):
if not telegram_bot_utils.is_proper_chat_id(channel_id):
self.telegram_bot.send_text(chat_id=chat_id,
text='channel_id should be a number or start from @')
return
Expand Down
61 changes: 61 additions & 0 deletions liker/command/handler_take_message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import inject
import logging
from tengine.command.command_handler import *
from tengine import TelegramBot, TelegramApi, telegram_api_utils

logger = logging.getLogger(__file__)


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

def get_cards(self) -> Iterable[CommandCard]:
return [CommandCard(command_str='/take_messages',
description='Take ownership over channel message(s)',
is_admin=True),
]

def handle(self,
config: Config,
chat_id,
message: Message,
args: Namespace,
telegram_bot: TelegramBot,
command_parser: CommandParser):
if args.command == '/take_messages':
channel_id = args.channel_id
if channel_id is None:
self.telegram_bot.send_text(chat_id=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,
text='--bot_id required')
return

message_id = args.message_id

if message_id is not None:
msg = self.telegram_api.get_chat_message(chat_id=channel_id,
message_id=message_id)
new_reply_markup = telegram_api_utils.api_to_bot_markup(msg.reply_markup)
prev_bot = TelegramBot(token=prev_bot_token)
# Reset reply markup, needed for another bot to be able to modify it
prev_bot.bot.edit_message_reply_markup(chat_id=channel_id,
message_id=message_id,
reply_markup=None)
# Modify reply markup by the new bot
self.telegram_bot.bot.edit_message_reply_markup(chat_id=channel_id,
message_id=message_id,
reply_markup=new_reply_markup)
else:
raise Exception(f'Not yet implemented')

logger.info(f'take_messages done {channel_id}, {message_id}')
self.telegram_bot.send_text(chat_id=chat_id,
text=f'for {channel_id} message(s) were taken')
else:
raise ValueError(f'Unhandled command: {args.command}')
6 changes: 6 additions & 0 deletions liker/command/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,10 @@
help_str='Channel id',
param_type=str,
nargs='*'),
CommandParam(name='--message_id',
help_str='Message id',
param_type=int),
CommandParam(name='--bot_token',
help_str='Bot token',
param_type=str),
]
6 changes: 3 additions & 3 deletions liker/custom_markup/channel_post_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import inject
from telebot.apihelper import ApiTelegramException
from telebot.types import InlineKeyboardMarkup
from tengine import Config, TelegramBot, telegram_utils, Hasher, AbuseDetector
from tengine import Config, TelegramBot, telegram_bot_utils, Hasher, AbuseDetector
from tengine.telegram.inbox_handler import *

from liker.state.space_state import SpaceState
Expand Down Expand Up @@ -54,9 +54,9 @@ def channel_post(self, channel_post: types.Message) -> bool:

def callback_query(self, callback_query: types.CallbackQuery) -> bool:
button_data = callback_query.data
if not telegram_utils.is_button_data_encoded(button_data):
if not telegram_bot_utils.is_button_data_encoded(button_data):
return False
handler, _case_id, reaction = telegram_utils.decode_button_data(button_data)
handler, _case_id, reaction = telegram_bot_utils.decode_button_data(button_data)
if handler != constants.CHANNEL_POST_HANDLER:
return False
if callback_query.message is None:
Expand Down
6 changes: 3 additions & 3 deletions liker/custom_markup/comment_handler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
import inject
from telebot.types import InlineKeyboardMarkup
from tengine import telegram_utils
from tengine import telegram_bot_utils
from tengine.telegram.inbox_handler import *
from tengine.telegram.constants import TELEGRAM_USER_ID

Expand All @@ -25,7 +25,7 @@ class CommentHandler(TelegramInboxHandler):
markup_synchronizer = inject.attr(MarkupSynchronizer)

def message(self, message: types.Message) -> bool:
if not telegram_utils.is_group_message(message):
if not telegram_bot_utils.is_group_message(message):
return False

if self._check_forward_from_channel(message):
Expand Down Expand Up @@ -126,7 +126,7 @@ def _ensure_comment_button(reply_markup: InlineKeyboardMarkup,
group_id: int,
thread_message_id: int) -> InlineKeyboardMarkup:
if not markup_utils.markup_has_button(reply_markup, constants.COMMENT_TEXT):
short_group_id = telegram_utils.get_short_chat_id(group_id)
short_group_id = telegram_bot_utils.get_short_chat_id(group_id)
comments_url = f'https://t.me/c/{short_group_id}/999999999?thread={thread_message_id}'
reply_markup = markup_utils.add_url_button_to_markup(reply_markup=reply_markup,
text=constants.COMMENT_TEXT,
Expand Down
13 changes: 7 additions & 6 deletions liker/custom_markup/markup_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
from telebot import types
from typing import Iterable, List, Optional
from tengine import telegram_utils
from tengine import telegram_bot_utils

from liker.setup import constants

Expand Down Expand Up @@ -45,9 +45,9 @@ def extend_reply_markup(current_markup: Optional[types.InlineKeyboardMarkup],
cur_btn = next((b for b in current_buttons if r in b.text), None)
if cur_btn is None:
text = f'{r}'
data = telegram_utils.encode_button_data(handler=handler,
case_id=case_id,
response=r)
data = telegram_bot_utils.encode_button_data(handler=handler,
case_id=case_id,
response=r)
cur_btn = types.InlineKeyboardButton(text=text,
callback_data=data)
buttons_obj.append(cur_btn)
Expand All @@ -57,7 +57,8 @@ def extend_reply_markup(current_markup: Optional[types.InlineKeyboardMarkup],
def change_reaction_counter(reply_markup: types.InlineKeyboardMarkup, reaction: str, delta: int):
for btn in iterate_markup_buttons(reply_markup):
if reaction in btn.text:
num_str = btn.text.replace(reaction, '').strip()
prefix = btn.text.rstrip('0123456789-')
num_str = btn.text.replace(prefix, '')

num = _num_str_to_number(num_str)
if num is None:
Expand All @@ -66,7 +67,7 @@ def change_reaction_counter(reply_markup: types.InlineKeyboardMarkup, reaction:
num += delta
num_str = '' if (num == 0) else f'{num}'

t_new = f'{reaction}{num_str}'
t_new = f'{prefix}{num_str}'
btn.text = t_new
return
raise Exception(f'Can not change reaction counter: {reply_markup.to_json()}')
Expand Down
4 changes: 2 additions & 2 deletions liker/enabling_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging
import inject
from telebot.apihelper import ApiTelegramException
from tengine import Config, telegram_utils, TelegramBot
from tengine import Config, telegram_bot_utils, TelegramBot

from liker.state.enabled_channels import EnabledChannels

Expand All @@ -19,7 +19,7 @@ def try_set_reactions(self,
reactions: list,
reply_to_chat_id: Optional[int]) -> bool:
enable_only_for = self.config['enable_only_for']
if enable_only_for and (telegram_utils.to_int_chat_id_if_possible(channel_id) not in enable_only_for):
if enable_only_for and (telegram_bot_utils.to_int_chat_id_if_possible(channel_id) not in enable_only_for):
self._try_reply(chat_id=reply_to_chat_id,
text=f'Cannot enable for channel {channel_id}')
return False
Expand Down
4 changes: 3 additions & 1 deletion liker/setup/daemons.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import inject
from tengine import MessagesLogger, AbuseJanitor
from tengine import MessagesLogger, AbuseJanitor, TelegramApi


def create_daemon_instances():
Expand All @@ -9,3 +9,5 @@ def create_daemon_instances():
:return:
"""
inject.instance(MessagesLogger)
inject.instance(AbuseJanitor)
inject.instance(TelegramApi)
10 changes: 9 additions & 1 deletion liker/setup/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from liker.command.handler_set_reactions import CommandHandlerSetReactions
from liker.enabling_manager import EnablingManager
from liker.command.handler_update_markup import CommandHandlerUpdateMarkup
from liker.command.handler_take_message import CommandHandlerTakeMessage


def bind_app_dependencies(binder: Binder):
Expand All @@ -25,6 +26,12 @@ def bind_app_dependencies(binder: Binder):
example_path=constants.config_example_path()))
binder.bind_to_constructor(Hasher, lambda: Hasher(config=inject.instance(Config)))
binder.bind_to_constructor(TelegramBot, lambda: TelegramBot(token=inject.instance(Config)['bot_token']))
binder.bind_to_constructor(TelegramApi,
lambda: TelegramApi(
api_session_name=str(constants.data_dir()
/ inject.instance(Config)['telegram_api_session']),
api_id=inject.instance(Config)['telegram_api_id'],
api_hash=inject.instance(Config)['telegram_api_hash']))
binder.bind_to_constructor(TelegramCursor,
lambda: TelegramCursor(bot=inject.instance(TelegramBot),
look_back_days=constants.BOT_LOOK_BACK_DAYS,
Expand All @@ -34,7 +41,8 @@ def bind_app_dependencies(binder: Binder):
CommandHandlerPassword,
CommandHandlerConfig,
CommandHandlerSetReactions,
CommandHandlerUpdateMarkup],
CommandHandlerUpdateMarkup,
CommandHandlerTakeMessage],
params=command_params,
telegram_bot=inject.instance(TelegramBot)))
binder.bind_to_constructor(MessagesLogger,
Expand Down
4 changes: 2 additions & 2 deletions liker/state/enabled_channels.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typeguard import typechecked
from typing import List, Optional
from tengine.state.preserver import *
from tengine import telegram_utils
from tengine import telegram_bot_utils


class EnabledChannels(Preserver):
Expand All @@ -19,7 +19,7 @@ def get_channel_dict(self, str_channel_id: str) -> dict:

@typechecked
def set_channel_dict(self, str_channel_id: str, channel_dict: dict):
if not telegram_utils.is_int_chat_id(str_channel_id):
if not telegram_bot_utils.is_int_chat_id(str_channel_id):
raise ValueError('str_channel_id should be a number')
self.state[str_channel_id] = channel_dict

Expand Down
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ certifi==2020.12.5
chardet==4.0.0
idna==2.10
Inject==4.3.1
pyaes==1.6.1
pyasn1==0.4.8
pymitter==0.3.0
pyTelegramBotAPI==3.7.6
python-jsonstore==1.3.0
requests==2.25.1
rsa==4.7.2
Telethon==1.21.1
typeguard==2.12.0
urllib3==1.26.4
2 changes: 1 addition & 1 deletion tengine

0 comments on commit b859474

Please sign in to comment.