From 0d0dcaaca6f16217819ea76df3cd74e5a724979f Mon Sep 17 00:00:00 2001 From: Rahul P S Date: Sun, 28 Jul 2024 18:33:05 +0530 Subject: [PATCH] Added support to send logs to specific topic in supergroups --- README.md | 3 +++ tglogging/tglogger.py | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/README.md b/README.md index 68bbb44..e453c10 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ logging.basicConfig( log_chat_id=-10225533666, update_interval=2, minimum_lines=1, + topic_id=5, pending_logs=200000), logging.StreamHandler() ] @@ -49,6 +50,8 @@ logger.info("live log streaming to telegram.") ```log_chat_id``` : Chat id of chat to which logs are to be send. +```topic_id``` : Topic id of topic to which logs are to be send. + ```update_interval```: Interval between two posting in seconds. Lower intervals will lead to floodwaits. Default to 5 seconds. ```minimum_lines```: Minimum number of new lines required to post / edit a message. diff --git a/tglogging/tglogger.py b/tglogging/tglogger.py index 81ae7ca..52c1738 100644 --- a/tglogging/tglogger.py +++ b/tglogging/tglogger.py @@ -31,6 +31,7 @@ def __init__( self, token: str, log_chat_id: int, + topic_id: int = None, update_interval: int = 5, minimum_lines: int = 1, pending_logs: int = 200000, @@ -39,6 +40,7 @@ def __init__( self.loop = asyncio.get_event_loop() self.token = token self.log_chat_id = log_chat_id + self.topic_id = topic_id self.wait_time = update_interval self.minimum = minimum_lines self.pending = pending_logs @@ -51,6 +53,7 @@ def __init__( self.base_url = f"https://api.telegram.org/bot{token}" DEFAULT_PAYLOAD.update({"chat_id": log_chat_id}) + def emit(self, record): msg = self.format(record) self.lines += 1 @@ -131,6 +134,8 @@ async def send_message(self, message): payload = DEFAULT_PAYLOAD.copy() payload["text"] = f"```{message}```" url = f"{self.base_url}/sendMessage" + if self.topic_id: + payload["message_thread_id"] = self.topic_id res = await self.send_request(url, payload) if res.get("ok"): result = res.get("result") @@ -153,6 +158,8 @@ async def send_as_file(self, logs): url = f"{self.base_url}/sendDocument" payload = DEFAULT_PAYLOAD.copy() payload["caption"] = "Too much logs to send and hence sending as file." + if self.topic_id: + payload["message_thread_id"] = self.topic_id files = {"document": file} with contextlib.suppress(BaseException): del payload["disable_web_page_preview"]