forward message to super group with telethon

Viewed 2456

Recently I wrote code that should forward every message from a certain user to all groups that I joined but it doesn't. Here my code:

        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

in this code first I take every message which send to me by 'aliakhtari78' and then get entity of the groups that I joined to and in the end it should forward the message to all groups but it doesn't, I check my code and replace the entity with a user entity and it worked and I know the problem is because of entity, but I cant find out what is my problem. In addition, I'm sorry for writing mistakes in my question.

1 Answers

In order to send messages to any entities in Telegram, you need two pieces of information:

  1. the constant unique ID of the entity (It's an integer. It's NOT username string)
  2. the access_hash which is different for each user for each entity

You can only pass @username to client.get_entity, and Telethon automatically resolves the @username to an entity with id and access_hash. That's why it works when you change your code like that. However, in your code, you have passed channel_id (which is the constant unique ID of the entity) to client.get_entity, not username.

Note that client.get_dialogs returns entities along with dialogs. You have just ignored the entities! This is how you can get an array of all entities:

dialogs, entities = client.get_dialogs()

Then simply pass the corresponding entity from the entities array to client.forward_messages.

Related