From aedf80a4df2d192d318706df530c706b85abca73 Mon Sep 17 00:00:00 2001 From: Alexey Skobkin Date: Thu, 29 Jun 2023 00:39:05 +0300 Subject: [PATCH] Fix #49. Introducing Telegram message length limit and trimming descriptions which exceed it. --- telegram.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/telegram.py b/telegram.py index 63bce71..24b1b45 100644 --- a/telegram.py +++ b/telegram.py @@ -108,6 +108,8 @@ class Notifier: # https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this BATCH_LIMIT: int = 25 + # https://core.telegram.org/bots/api#sendmessage + MESSAGE_LENGTH_LIMIT: int = 4096 sent_counter: int = 0 @@ -167,12 +169,20 @@ class Notifier: if item.date is not None: date_string = item.date.strftime('%m.%d.%Y %H:%M') - return ( + header = ( f"{item.title}\n" f"{date_string}\n\n" - f"{self.__sanitize_html(item.description)}" ) + sanitized_description = self.__sanitize_html(item.description) + + if len(sanitized_description) > (self.MESSAGE_LENGTH_LIMIT - len(header)): + cut = '<...>' + trim_index = self.MESSAGE_LENGTH_LIMIT - len(header) - len(cut) - 1 + sanitized_description = sanitized_description[:trim_index] + cut + + return header + sanitized_description + def __sanitize_html(self, html: str) -> str: if not html: return ''