首页 > 解决方案 > 使用 Telethon 将消息转发到超级组

问题描述

最近我编写了代码,应该将来自某个用户的每条消息转发到我加入的所有组,但事实并非如此。这是我的代码:

        for message in client.iter_messages('aliakhtari78'):
        try:
            dialogs = client.get_dialogs()
            for dialog in dialogs:
                id_chat = dialog.message.to_id.channel_id
                entity = client.get_entity(id_chat)
                client.forward_messages(
                    entity,  # to which entity you are forwarding the messages
                    message.id,  # the IDs of the messages (or message) to forward
                    'somebody'  # who sent the messages?
                )

        except:
            pass

在这段代码中,我首先获取“aliakhtari78”发送给我的每条消息,然后获取我加入的组的实体,最后它应该将消息转发给所有组,但它没有,我检查了我的代码并用用户实体替换实体并且它有效,我知道问题是因为实体,但我无法找出我的问题。 另外,我很抱歉在我的问题中写错了。

标签: pythonpython-3.xtelegrampython-telegram-bottelethon

解决方案


为了向 Telegram 中的任何实体发送消息,您需要两条信息:

  1. 实体的常量唯一 ID(它是一个整数。它不是用户名字符串)
  2. 每个实体的access_hash每个用户都不同

您只能传递@usernameclient.get_entity,并且 Telethon 会自动将 解析@username为具有id和的实体access_hash。这就是为什么当您像这样更改代码时它会起作用的原因。但是,在您的代码中,您已将channel_id(实体的常量唯一 ID)传递给client.get_entity,而不是username

请注意,与 一起client.get_dialogs返回。您刚刚忽略了实体!这是获取所有实体数组的方法:entitiesdialogs

dialogs, entities = client.get_dialogs()

entities然后只需将数组中的相应实体传递给client.forward_messages.


推荐阅读