LINUX.ORG.RU

Как определить, в какой теме в группе телеграмма пришло сообщение

 ,


0

1

В телеграме есть группы, в группах есть темы, выглядят эти темы как отдельные группы(подгруппы, группы внутри групп), но message.chat.id у всех тем одинаковый, такой же как у главной группы.

Как можно идентифицировать темы в телеботе, нужно что бы бот в разных темах вёл себя по разному, ему надо как то понять что сообщение прилетело не просто в группу ххх, но еще и в тему ууу из этой группы.

Пробовал использовать message.message_thread_id но похоже что это не идентификатор тем а что то другое, это свойство есть у групп у которых нет тем, и может быть разным внутри одной темы, несколько разных в одной теме или группе без тем.

def get_topic_id(message: telebot.types.Message) -> str:
    thread_id = message.message_thread_id
    chat_id = message.chat.id
    return f'[{chat_id}] [{thread_id}]'

★★

Последнее исправление: hobbit (всего исправлений: 2)

Ответ на: комментарий от Anoxemian

https://pytba.readthedocs.io/en/latest/types.html#telebot.types.Message

в обработчик сообщений поступает этот объект

в нем есть поле message_thread_id (int) – Optional. Unique identifier of a message thread to which the message belongs; for supergroups only

и еще есть

is_topic_message (bool) – Optional. True, if the message is sent to a forum topic

forum_topic_created (telebot.types.ForumTopicCreated) – Optional. Service message: forum topic created

forum_topic_edited (telebot.types.ForumTopicEdited) – Optional. Service message: forum topic edited

forum_topic_closed (telebot.types.ForumTopicClosed) – Optional. Service message: forum topic closed

forum_topic_reopened (telebot.types.ForumTopicReopened) – Optional. Service message: forum topic reopened

general_forum_topic_hidden (telebot.types.GeneralForumTopicHidden) – Optional. Service message: the ‘General’ forum topic hidden

general_forum_topic_unhidden (telebot.types.GeneralForumTopicUnhidden) – Optional. Service message: the ‘General’ forum topic unhidden



Есть еще такое, из чего можно подумать что message_thread_id это всё таки то что надо, но у меня почему то нет

class telebot.types.ForumTopic(message_thread_id: int, name: str, icon_color: int, icon_custom_emoji_id: Optional[str] = None)

    Bases: JsonDeserializable

    This object represents a forum topic.

    Telegram documentation: https://core.telegram.org/bots/api#forumtopic

    Parameters:

            message_thread_id (int) – Unique identifier of the forum topic

            name (str) – Name of the topic

            icon_color (int) – Color of the topic icon in RGB format

            icon_custom_emoji_id (str) – Optional. Unique identifier of the custom emoji shown as the topic icon

    Returns:

        Instance of the class
    Return type:

        telebot.types.ForumTopic

theurs ★★
() автор топика
Ответ на: комментарий от Anoxemian

message_id - id сообщения а не группы или темы в группе

потыкал в отладчике и вроде понятнее стало

когда кто то что то пишет в тему в группе у объекта message почему то есть поле message.reply_to_message и message.is_topic_message == True
странно, ведь это сообщение не выглядит как ответ на чье то сообщение

и пара исключений

если пишут в главную тему группы то там этого поля нет (message.reply_to_message) и message.is_topic_message = None(False)

если пишут в ответ на сообщение в теме группы, тогда message.reply_to_message нету но есть message.is_topic_message == True

в итоге функция для идентификации получилась такая, но может это еще не все случаи и исключения Ж(

def get_topic_id(message: telebot.types.Message) -> str:
    """
    Get the topic ID from a Telegram message.

    Parameters:
        message (telebot.types.Message): The Telegram message object.

    Returns:
        str: '[chat.id] [topic.id]'
    """

    chat_id = message.chat.id
    # topic_id = 'not topic'
    topic_id = 0

    if message.reply_to_message and message.reply_to_message.is_topic_message:
    # if message.reply_to_message and message.reply_to_message.content_type == 'forum_topic_created':
        topic_id = message.reply_to_message.message_thread_id
    elif message.is_topic_message:
        topic_id = message.message_thread_id

    # bot.reply_to(message, f'DEBUG: [{chat_id}] [{topic_id}]')

    return f'[{chat_id}] [{topic_id}]'

theurs ★★
() автор топика
Последнее исправление: theurs (всего исправлений: 2)