diff --git a/telegram/_message.py b/telegram/_message.py index 31425731e..f870e5077 100644 --- a/telegram/_message.py +++ b/telegram/_message.py @@ -826,11 +826,20 @@ class Message(TelegramObject): def link(self) -> Optional[str]: """:obj:`str`: Convenience property. If the chat of the message is not a private chat or normal group, returns a t.me link of the message. + + .. versionchanged:: NEXT.VERSION + For messages that are replies or part of a forum topic, the link now points + to the corresponding thread view. """ if self.chat.type not in [Chat.PRIVATE, Chat.GROUP]: # the else block gets rid of leading -100 for supergroups: to_link = self.chat.username if self.chat.username else f"c/{str(self.chat.id)[4:]}" - return f"https://t.me/{to_link}/{self.message_id}" + baselink = f"https://t.me/{to_link}/{self.message_id}" + + # adds the thread for topics and replies + if (self.is_topic_message and self.message_thread_id) or self.reply_to_message: + baselink = f"{baselink}?thread={self.message_thread_id}" + return baselink return None @classmethod diff --git a/tests/test_message.py b/tests/test_message.py index 741aeb291..38b347302 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -791,6 +791,20 @@ class TestMessageWithoutRequest(TestMessageBase): # The leading - for group ids/ -100 for supergroup ids isn't supposed to be in the link assert message.link == f"https://t.me/c/{3}/{message.message_id}" + def test_link_with_topics(self, message): + message.chat.username = None + message.chat.id = -1003 + message.is_topic_message = True + message.message_thread_id = 123 + assert message.link == f"https://t.me/c/3/{message.message_id}?thread=123" + + def test_link_with_reply(self, message): + message.chat.username = None + message.chat.id = -1003 + message.reply_to_message = Message(7, self.from_user, self.date, self.chat, text="Reply") + message.message_thread_id = 123 + assert message.link == f"https://t.me/c/3/{message.message_id}?thread=123" + @pytest.mark.parametrize(("id_", "username"), argvalues=[(None, "username"), (-3, None)]) def test_link_private_chats(self, message, id_, username): message.chat.type = Chat.PRIVATE