Skip to content

Commit

Permalink
handle migrated chats
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Brugger committed Nov 19, 2023
1 parent ca394c1 commit b0089f9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/db/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ async def upsert_model(self, user: UserModel) -> None:
}
await self._upsert(update)

logging.info('added user: %s', user.__dict__)

async def get_by_id(self, user_id: int) -> UserModel:
user = await self._fetch_by_id(user_id)

Expand Down Expand Up @@ -211,3 +213,9 @@ async def get_by_user_id(self, user_id: int) -> list[NotificationModel]:

async def count_notifications_by_user_id(self, user_id: int) -> int:
return await self.count_rows_by_field(Tables.NOTIFICATIONS, NColumns.USER_ID, user_id)

async def copy_notifications_to_other_user(self, old_user_id: int, new_user_id: int) -> None:
all_notifications = await self.get_by_user_id(old_user_id)

for notification in all_notifications:
await self.save_notification(notification.query, new_user_id)
16 changes: 14 additions & 2 deletions src/telegram/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from aiogram.dispatcher import FSMContext
from aiogram.types import CallbackQuery, Message, ParseMode, Update
from aiogram.utils import executor
from aiogram.utils.exceptions import ChatNotFound, TelegramAPIError, Unauthorized
from aiogram.utils.exceptions import ChatNotFound, MigrateToChat, TelegramAPIError, Unauthorized

from src.config import Config
from src.db.constants import UColumns
Expand Down Expand Up @@ -80,7 +80,6 @@ async def start(
telegram_object.from_user.locale
)
user = UserModel().parse_telegram_object(telegram_object)
logging.info('added user: %s', user.__dict__)

await SQLiteUser().upsert_model(user)

Expand Down Expand Up @@ -427,6 +426,19 @@ async def send_deal(self, deal: DealModel, notification: NotificationModel) -> N
logging.info('User %s blocked the bot. Disable him', notification.user_id)
await SQLiteUser().set_user_state(notification.user_id, False)

except MigrateToChat as e:
try:
new_user = await SQLiteUser().get_by_id(e.migrate_to_chat_id)
except UserNotFoundError:
new_user = await SQLiteUser().get_by_id(notification.user_id)
new_user.id = e.migrate_to_chat_id
await SQLiteUser().upsert_model(new_user)
await SQLiteNotifications().copy_notifications_to_other_user(notification.user_id, new_user.id)

await SQLiteUser().delete_by_id(notification.user_id)

logging.info('Migrated user-id %s to %s', notification.user_id, new_user.id)

except Exception as error: # pylint: disable=broad-exception-caught
await self.send_error(error, message=message)

Expand Down

0 comments on commit b0089f9

Please sign in to comment.