From 1863ac85714e020c2a8677a2cb99bd50187fbfa3 Mon Sep 17 00:00:00 2001 From: uburuntu Date: Sun, 10 Nov 2019 00:34:20 +0300 Subject: [PATCH 1/2] enh: private chat links --- aiogram/types/chat.py | 10 ++++++++++ aiogram/types/message.py | 15 +++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/aiogram/types/chat.py b/aiogram/types/chat.py index 66b8fe4d..a05ad47e 100644 --- a/aiogram/types/chat.py +++ b/aiogram/types/chat.py @@ -63,6 +63,16 @@ class Chat(base.TelegramObject): return f"tg://user?id={self.id}" + @property + def shifted_id(self) -> int: + """ + Get shifted id of chat, e.g. for private links + + For example: -1001122334455 -> 1122334455 + """ + shift = -1000000000000 + return shift - self.id + def get_mention(self, name=None, as_html=False): if name is None: name = self.mention diff --git a/aiogram/types/message.py b/aiogram/types/message.py index 8fdece2b..5fb012f1 100644 --- a/aiogram/types/message.py +++ b/aiogram/types/message.py @@ -258,12 +258,19 @@ class Message(base.TelegramObject): :return: str """ - if self.chat.type not in [ChatType.SUPER_GROUP, ChatType.CHANNEL]: + if ChatType.is_private(self.chat): raise TypeError('Invalid chat type!') - elif not self.chat.username: - raise TypeError('This chat does not have @username') - return f"https://t.me/{self.chat.username}/{self.message_id}" + url = 'https://t.me/' + if self.chat.username: + # Generates public link + url += f'{self.chat.username}/' + else: + # Generates private link available for chat members + url += f'c/{self.chat.shifted_id}/' + url += f'{self.message_id}' + + return url def link(self, text, as_html=True) -> str: """ From deddcf540eba16244a264583c000d5f9018342cb Mon Sep 17 00:00:00 2001 From: uburuntu Date: Tue, 19 Nov 2019 20:40:18 +0300 Subject: [PATCH 2/2] enh: add check for private chat --- aiogram/types/chat.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/aiogram/types/chat.py b/aiogram/types/chat.py index 1792613c..3f0c4e10 100644 --- a/aiogram/types/chat.py +++ b/aiogram/types/chat.py @@ -70,6 +70,8 @@ class Chat(base.TelegramObject): For example: -1001122334455 -> 1122334455 """ + if self.type == ChatType.PRIVATE: + raise TypeError('`shifted_id` property is not available for private chats') shift = -1000000000000 return shift - self.id