diff --git a/.env.example b/.env.example index 31a87f9..beb5ada 100644 --- a/.env.example +++ b/.env.example @@ -74,3 +74,6 @@ MACVENDOR_API_URL="" # ============================================================================= TG_BOT_TOKEN="" TG_CHAT_ID="" +# Optional forum topic id. If empty/unset, message_thread_id is omitted and +# messages post to the group's General topic. +TG_TOPIC_ID="" diff --git a/api/bot.py b/api/bot.py index 9559f6d..2507977 100644 --- a/api/bot.py +++ b/api/bot.py @@ -12,6 +12,8 @@ telegram_loop = None BOT_TOKEN = config("TG_BOT_TOKEN", default="killme", cast=str) CHAT_ID = config("TG_CHAT_ID", default="drake", cast=str) +# Optional forum topic to post into. If empty, messages go to the group's General topic. +TOPIC_ID = config("TG_TOPIC_ID", default="", cast=str) if not BOT_TOKEN or not isinstance(BOT_TOKEN, str): raise ValueError( @@ -57,10 +59,14 @@ else: async def send_telegram_alert(markdown_message: str): logger.info("[TELEGRAM] Preparing to send alert...") + kwargs = {} + if TOPIC_ID: + kwargs["message_thread_id"] = int(TOPIC_ID) await bot.send_message( chat_id=str(CHAT_ID), text=markdown_message, parse_mode=ParseMode.MARKDOWN_V2, + **kwargs, ) diff --git a/api/notifications.py b/api/notifications.py index 0cc5a74..d7d4cd9 100644 --- a/api/notifications.py +++ b/api/notifications.py @@ -8,6 +8,8 @@ api_url = str(config("SMS_API_URL", cast=str, default="")) api_key = str(config("SMS_API_KEY", cast=str, default="")) bot_token = str(config("TG_BOT_TOKEN", cast=str, default="")) chat_id = str(config("TG_CHAT_ID", cast=str, default="")) +# Optional forum topic to post into. If empty, messages go to the group's General topic. +topic_id = str(config("TG_TOPIC_ID", cast=str, default="")) def format_mobile(mobile: str) -> str: @@ -88,6 +90,8 @@ def send_telegram_markdown(message: str): try: url = f"https://api.telegram.org/bot{bot_token}/sendMessage" payload = {"chat_id": chat_id, "text": message, "parse_mode": "MarkdownV2"} + if topic_id: + payload["message_thread_id"] = topic_id response = requests.post(url, data=payload) response.raise_for_status()