问题
I'm using Telethon's send_message function to send messages to various chats.
Sometimes, the destination is another user (just a regular one on one chat), sometimes a group, sometimes a supergroup, and sometimes a channel (of which I'm admin).
If I understand correctly, the syntax is supposed to be:
client.send_message(entity,text)
But I can't figure out what the entity
parameter is supposed to be in different cases. What I find especially confusing is specifying an integer id seems to work fine for some groups, but not for others.
For example:
I have a normal 1-to-1 chat with someone who has user_id 11111
, and also with another person who has user_id 22222
.
Furthermore I'm in two groups (supergroups actually) which have channel_id 33333
and 44444
.
I can specify 11111
or 33333
as entity, and the message gets sent correctly (to the first person or the first group respectively). However if I specify 22222
or 44444
, I'm getting an error:
Cannot find any entity corresponding to "{}"'.format(string)
ValueError: Cannot find any entity corresponding to "22222"
I am also receiving mesasges from all 4 chats using this same Telethon instance, and that's working all fine.
So my question is: how do I get the correct entity data for send_message()?
回答1:
I suggest reading this section of the document (entities)
for example, I want to send the message to a user with the username: alix
client = TelegramClient('session_name',
api_id,
api_hash,
)
client.start()
destination_user_username='alix'
entity=client.get_entity(destination_user_username)
client.send_message(entity=entity,message="Hi")
or I want to send the message to a channel with username: test_ali3
client = TelegramClient('session_name',
api_id,
api_hash
)
client.start()
destination_channel_username='test_ali3'
entity=client.get_entity(destination_channel_username)
client.send_message(entity=entity,message="Hi")
or I want to send the message to a group with invite_link: https://t.me/joinchat/Bn4WIhMF1T_ZAF-yM6WbHw
client = TelegramClient('session_name',
api_id,
api_hash
)
client.start()
destination_group_invite_link='https://t.me/joinchat/Bn4WIhMF1T_ZAF-yM6WbHw'
entity=client.get_entity(destination_group_invite_link)
client.send_message(entity=entity,message="Hi")
I hope to be useful to you.
来源:https://stackoverflow.com/questions/52002524/sending-telegram-messages-with-telethon-some-entity-parameters-work-others-don