Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions src/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,6 @@ def init_handlers(self):
def asyncify(func):
async def wrapper(*args, **kwargs):
results = func(*args, **kwargs)
if asyncio.iscoroutine(results):
return await results
return results

return wrapper
Expand Down
2 changes: 1 addition & 1 deletion src/db/db_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ def _get_now_msk_naive() -> datetime:
@staticmethod
def _make_next_reminder_ts(weekday_num: int, time: str):
hour, minute = map(int, time.split(":"))
today = DBClient._get_now_msk_naive()
today = datetime.today()

next_reminder = today + timedelta(days=(weekday_num - today.weekday()))
next_reminder = next_reminder.replace(
Expand Down
8 changes: 4 additions & 4 deletions src/jobs/backfill_telegram_user_ids_job.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
import logging
import time
from typing import Callable

from ..app_context import AppContext
Expand All @@ -10,7 +10,7 @@

class BackfillTelegramUserIdsJob(BaseJob):
@staticmethod
async def _execute(
def _execute(
app_context: AppContext, send: Callable[[str], None], called_from_handler=False
):
"""
Expand Down Expand Up @@ -75,9 +75,9 @@ async def _execute(

# Try to resolve username to user_id
# Add delay to avoid rate limiting (telethon has limits)
await asyncio.sleep(0.2) # 200ms delay between requests
time.sleep(0.2) # 200ms delay between requests

result = await tg_client.resolve_telegram_username(telegram_username)
result = tg_client.resolve_telegram_username(telegram_username)

if not result:
# Result is None if:
Expand Down
35 changes: 1 addition & 34 deletions src/jobs/base_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,46 +28,13 @@ def execute(

try:
logging_func(f"Job {module} started...")
import inspect
import asyncio

# This returns either a result (sync) or coroutine (async)
res = cls._execute(
cls._execute(
app_context,
send,
called_from_handler,
*args if args else [],
**kwargs if kwargs else {},
)

if inspect.isawaitable(res):
try:
# Check if we are running in the main event loop (e.g. called from Handler)
loop = asyncio.get_running_loop()
if loop.is_running():
# We are in an async context (Handler).
# Return the coroutine so the caller (asyncify) can await it.
return res
except RuntimeError:
# No running loop. We are likely in a Scheduler thread.
pass

# If we are here, we need to run the coroutine synchronously/threadsafe
# The coroutine likely uses TgClient which is bound to the Main Loop.
# So we must schedule it on the Main Loop and wait for result.

# Check if app_context has tg_client and valid loop
if hasattr(app_context, "tg_client") and hasattr(
app_context.tg_client, "api_client"
):
main_loop = app_context.tg_client.api_client.loop
if main_loop and main_loop.is_running():
future = asyncio.run_coroutine_threadsafe(res, main_loop)
return future.result()

# Fallback (e.g. testing or no loop running): run locally
return asyncio.run(res)

logging_func(f"Job {module} finished")
except Exception as e:
# should not raise exception, so that schedule module won't go mad retrying
Expand Down
4 changes: 2 additions & 2 deletions src/jobs/hr_check_chat_consistency_frozen_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@

class HRCheckChatConsistencyFrozenJob(BaseJob):
@staticmethod
async def _execute(
def _execute(
app_context: AppContext, send: Callable[[str], None], called_from_handler=False
):
# get users that are in the main chat
chat_users = await app_context.tg_client.get_main_chat_users()
chat_users = app_context.tg_client.get_main_chat_users()
# get Frozen users
frozen_members = app_context.role_manager.get_members_for_role(
Roles.FROZEN_MEMBER
Expand Down
4 changes: 2 additions & 2 deletions src/jobs/hr_check_chat_consistency_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@

class HRCheckChatConsistencyJob(BaseJob):
@staticmethod
async def _execute(
def _execute(
app_context: AppContext, send: Callable[[str], None], called_from_handler=False
):
# get users that are in the main chat
chat_users = await app_context.tg_client.get_main_chat_users()
chat_users = app_context.tg_client.get_main_chat_users()
# get users that _should_ be in the main chat <==> roles include Active or Frozen
active_members = app_context.role_manager.get_members_for_role(
Roles.ACTIVE_MEMBER
Expand Down
33 changes: 11 additions & 22 deletions src/jobs/tg_analytics_report_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,19 @@

class TgAnalyticsReportJob(BaseJob):
@staticmethod
async def _execute(
def _execute(
app_context: AppContext, send: Callable[[str], None], called_from_handler=False
):
# We use the raw api_client here, so we must manage connection manually
if not app_context.tg_client.api_client.is_connected():
await app_context.tg_client.api_client.connect()

try:
stats = await app_context.tg_client.api_client.get_stats(
app_context.tg_client.channel
)
entity = await app_context.tg_client.api_client.get_entity(
app_context.tg_client.channel
)
finally:
# Do not disconnect as other jobs might be using the client locally?
# But TgClient generally keeps it disconnected?
# Based on previous code, it disconnected. Let's keep it safe.
# Wait, TgClient.resolve_telegram_username connects and disconnects.
# So we should probably disconnect to avoid state accumulation if it's meant to be ephemeral.
# BUT if we are running the bot (TelegramSender), isn't the client connected?
# No, TelegramSender uses `bot` instance. TgClient uses `TelegramClient` (Userbot/MTProto).
# So they are separate.
await app_context.tg_client.api_client.disconnect()
app_context.tg_client.api_client.loop.run_until_complete(
app_context.tg_client.api_client.connect()
)
stats = app_context.tg_client.api_client.loop.run_until_complete(
app_context.tg_client.api_client.get_stats(app_context.tg_client.channel)
)
entity = app_context.tg_client.api_client.loop.run_until_complete(
app_context.tg_client.api_client.get_entity(app_context.tg_client.channel)
)
app_context.tg_client.api_client.disconnect()
new_posts_count = len(stats.recent_message_interactions)
followers_stats = TgAnalyticsReportJob._get_followers_stats(stats)
message = load(
Expand Down
2 changes: 1 addition & 1 deletion src/tg/handler_registry.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from typing import Callable, Optional, Literal

from ..consts import CommandCategories
from ...consts import CommandCategories
from . import handlers


Expand Down
2 changes: 1 addition & 1 deletion src/tg/handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@
# Plain text message handler
from .user_message_handler import (
handle_callback_query,
handle_new_members,
handle_user_message,
)
from .flow_handlers import handle_new_members
21 changes: 1 addition & 20 deletions src/tg/handlers/flow_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,16 +806,6 @@ def _handle_edit_action(self, chat_title, chat_id):
return None

def handle(self) -> Optional[PlainTextUserAction]:
# If user clicked a button (like "Create New" again) instead of typing
if not self.user_input:
if self.button:
# If valid known button from previous step, maybe we should just ignore or re-ask
# For now, let's just ask to enter ID again to avoid crash
reply(load("manager_reminders_handler__enter_chat_id"), self.update)
return PlainTextUserAction.MANAGE_REMINDERS__ENTER_CHAT_ID
# If no input and no button (shouldn't happen?), return same state
return PlainTextUserAction.MANAGE_REMINDERS__ENTER_CHAT_ID

try:
chat_id = int(self.user_input)
chat_title = DBClient().get_chat_name(chat_id)
Expand Down Expand Up @@ -914,15 +904,6 @@ def handle(self) -> Optional[PlainTextUserAction]:
self.command_data[consts.ManageRemindersData.CHOSEN_REMINDER_ID]
)
DBClient().update_reminder(reminder_id, weekday=weekday_num, time=time)
weekday_name = self.command_data[consts.ManageRemindersData.WEEKDAY_NAME]
reply(
load(
"manage_reminders_handler__success_time",
weekday_name=weekday_name,
time=time,
),
self.update,
)
return None

button_yes = telegram.InlineKeyboardButton(
Expand Down Expand Up @@ -951,7 +932,7 @@ def handle(self) -> Optional[PlainTextUserAction]:
weekday_name = self.command_data[consts.ManageRemindersData.WEEKDAY_NAME]
time = self.command_data[consts.ManageRemindersData.TIME]

if self.button == consts.ButtonValues.MANAGE_REMINDERS__POLL__YES:
if self.button == consts.ButtonValues.MANAGE_REMINDERS__TOGGLE_POLL__YES:
if text is None:
reminder_id = int(
self.command_data[consts.ManageRemindersData.CHOSEN_REMINDER_ID]
Expand Down
4 changes: 2 additions & 2 deletions src/tg/handlers/user_message_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
logger = logging.getLogger(__name__)


async def handle_callback_query(
def handle_callback_query(
update: telegram.Update, tg_context: telegram.ext.CallbackContext
):
"""
Handler for handling button callbacks. Redirects to handle_user_message
"""
await update.callback_query.answer()
update.callback_query.answer()
handle_user_message(update, tg_context, ButtonValues(update.callback_query.data))


Expand Down
24 changes: 13 additions & 11 deletions src/tg/tg_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,17 @@ def _update_from_config(self):
self.sysblok_chats = self._tg_config["sysblok_chats"]
self.channel = self._tg_config["channel"]

async def _get_chat_users(self, chat_id: str) -> List[User]:
async with self.api_client:
users = await self.api_client.get_participants(chat_id)
def _get_chat_users(self, chat_id: str) -> List[User]:
with self.api_client:
users = self.api_client.loop.run_until_complete(
self.api_client.get_participants(chat_id)
)
return users

async def get_main_chat_users(self) -> List[User]:
return await self._get_chat_users(self.sysblok_chats["main_chat"])
def get_main_chat_users(self) -> List[User]:
return self._get_chat_users(self.sysblok_chats["main_chat"])

async def resolve_telegram_username(
self, username: str
) -> Optional[Tuple[int, str]]:
def resolve_telegram_username(self, username: str) -> Optional[Tuple[int, str]]:
"""
Resolve Telegram username to user ID using telethon.

Expand All @@ -67,10 +67,12 @@ async def resolve_telegram_username(

if not was_connected:
# Connect if not already connected
await self.api_client.connect()
self.api_client.loop.run_until_complete(self.api_client.connect())

try:
entity = await self.api_client.get_entity(normalized)
entity = self.api_client.loop.run_until_complete(
self.api_client.get_entity(normalized)
)

# Only process User entities, skip channels, groups, bots, etc.
if entity and isinstance(entity, User):
Expand All @@ -86,7 +88,7 @@ async def resolve_telegram_username(
finally:
# Only disconnect if we connected it
if not was_connected:
await self.api_client.disconnect()
self.api_client.disconnect()
except Exception as e:
logger.warning(f"Failed to resolve username {username}: {e}", exc_info=True)
return None
Expand Down