Peers¶
An peer will refer to any Telegram entity that can be interacted with, such as a user, a chat, or a channel.
Note
Once you have encountered an ID, the library will (by default) have saved their access_hash for you, which is needed to invoke most methods.
What is an Peer?¶
A lot of methods in Pyrogram require a peer to work.
For example, if you want to send a message to a user or a chat, you need to specify the peer where the message will be sent.
Getting Peers¶
Through the use of the Session Files, the library will automatically remember the ID and hash pair, along with some extra information, so you’re able to just do this:
# This part is IMPORTANT, because it fills the peer cache.
async for _ in client.get_dialogs():
pass
# All of these work and do the same.
input_peer = await client.resolve_peer('username')
input_peer = await client.resolve_peer('t.me/username')
# Other kind of peers.
input_peer = await client.resolve_peer('telegram.me/joinchat/AAAAAEkk2WdoDrB4-Q8-gg')
input_peer = await client.resolve_peer('+34xxxxxxxxx')
input_peer = await client.resolve_peer(some_id)
Note
You don’t need to get the peer before using it! Just let the library do its job. Use a phone from your contacts, username or ID, whatever you already have.
All methods in the Client call resolve_peer() prior to sending the request to save you from the hassle of doing so manually. That way, convenience calls such as client.send_message('username', 'hi!') become possible.
Every peer the library encounters (in any response to any call) will by default be cached in the .session file (an SQLite database),
to avoid performing unnecessary API calls. If the peer cannot be found,
additonal calls like ResolveUsername or GetContacts may be made to obtain the required information.
Summary¶
If you’re here because of “The peer id being used is invalid or not known yet”, you must ask yourself “how did I find this peer through official applications”? Now do the same with the library. Use what applies:
# Does it have a username? Use it!
await client.send_message(username, 'Hi!')
# Do you have a conversation open with them? Get dialogs.
async for _ in client.get_dialogs()
pass
# Are they participant of some group? Get them.
async for _ in client.get_chat_members('username'):
pass
# Is the peer the original sender of a forwarded message? Get it.
await client.get_messages('username', 100)
# NOW you can use the ID, anywhere!
await client.send_message(123456, 'Hi!')