refactor(notification): add detailed logging and improve error handling

This commit is contained in:
2026-07-29 22:12:06 +05:00
parent e2e067894d
commit 183f0aa9bb
2 changed files with 57 additions and 19 deletions
+53 -18
View File
@@ -23,12 +23,17 @@ class NotificationBot:
link_preview_is_disabled=True,
),
)
logger.info(
"Бот для уведомлений инициализирован (admin_id=%s)", config.admin_id
)
except:
logger.exception("Не удалось инициализировать Бот для уведомлений")
raise
async def _notify(self, message: str, reply_to: int, link: str = None):
async def _notify(self, message: str, reply_to: int = None, link: str = None):
try:
logger.debug("Отправка уведомления (reply_to=%s, link=%s)", reply_to, link)
keyboard = None
if link:
keyboard = InlineKeyboardMarkup(
@@ -47,10 +52,13 @@ class NotificationBot:
reply_markup=keyboard,
)
logger.debug(
"Уведомление отправлено (message_id=%s)", sent_message.message_id
)
return sent_message.message_id
except Exception as e:
logger.error(f"Ошибка отправки уведомления: {e}")
logger.error("Ошибка отправки уведомления: %s", e)
async def new_post(self, post: Dict[str, Any], links: List[str]):
try:
@@ -65,52 +73,79 @@ class NotificationBot:
poster_link = f"https://lolz.team/members/{poster_user_id}"
user_link = f'<a href="{poster_link}">{poster_username}</a>'
links_msg = f"<blockquote>\n"
for link in links:
links_msg += f"{link}\n"
logger.info(
"Новый пост: пользователь=%s (id=%s), тема=%r, ссылок=%d",
poster_username,
poster_user_id,
thread_title,
len(links),
)
links_msg = f"<blockquote>"
for idx, link in enumerate(links):
links_msg += f'<a href="{link}">Ссылка №{idx + 1}</a>\n'
links_msg += "</blockquote>"
message = (
f"🚩 Новый ответ в теме {thread_link}:\n"
f"▪️ Пользователь: {user_link}\n"
f"▪️ Ссылки: {links_msg}"
f"🚩 Новый ответ в теме {thread_link}:\n\n"
f"▪️ <b>Пользователь</b>: {user_link}\n"
f"▪️ <b>Ссылки</b>: {links_msg}"
)
post_message_id = await self._notify(message=message, link=permalink)
logger.debug(
"Уведомление о новом посте отправлено (message_id=%s)", post_message_id
)
return post_message_id
except:
return None
logger.exception("Ошибка в new_post")
raise
async def success(self, link: str, post_message_id: int):
try:
logger.info(
"Звезда успешно отправлена: link=%s, stars=%s",
link,
self.config.stars_count,
)
message = (
f"🌟 Звезда отправлена:\n"
f"▪️ Количество: {self.config.stars_count} ⭐️\n"
f"▪️ Ссылка на сообщение: {link}"
f"🌟 Звезда отправлена:\n\n"
f"▪️ <b>Количество</b>: {self.config.stars_count}\n"
f'▪️ <b>Ссылка на сообщение</b>: <a href="{link}">тык</a>'
)
success_message_id = await self._notify(
message=message, reply_to=post_message_id, link=link
)
logger.debug(
"Уведомление об успехе отправлено (message_id=%s)", success_message_id
)
return success_message_id
except:
return None
logger.exception("Ошибка в success")
raise
async def failure(self, post: Dict[str, Any], reason: str, post_message_id: int):
try:
permalink = post.get("links").get("permalink")
logger.warning(
"Не удалось отправить звезду: reason=%r, link=%s", reason, permalink
)
message = (
f"❌ Не удалось отправить звезду:\n"
f"▪️ Причина: <code>{reason}</code>"
f"❌ Не удалось отправить звезду:\n\n"
f"▪️ <b>Причина</b>: <code>{reason}</code>"
)
success_message_id = await self._notify(
failure_message_id = await self._notify(
message=message, reply_to=post_message_id, link=permalink
)
return success_message_id
logger.debug(
"Уведомление об ошибке отправлено (message_id=%s)", failure_message_id
)
return failure_message_id
except:
return None
logger.exception("Ошибка в failure")
raise
+4 -1
View File
@@ -145,6 +145,8 @@ class TelegramStarsBot:
post_message_id = None
post_id = post.get("post_id")
post = await self.lolz_api.get_post(post_id=post_id)
poster_user_id = post.get("poster_user_id")
poster_username = post.get("poster_username", "Неизвестный пользователь")
@@ -235,7 +237,8 @@ class TelegramStarsBot:
if self.notification_bot:
await self.notification_bot.success(
link=parsed_link, post_message_id=post_message_id
link=f"https://t.me/{channel}/{message_id}",
post_message_id=post_message_id,
)
else: