2
0
mirror of https://github.com/pyrogram/pyrogram synced 2025-08-29 05:18:10 +00:00

Add resolve_username method

This commit is contained in:
Dan 2018-01-25 16:41:59 +01:00
parent 894a0d0369
commit 16c5e63c8b

View File

@ -513,16 +513,49 @@ class Client:
peer_username = peer_username.lower() peer_username = peer_username.lower()
self.peers_by_username[peer_username] = input_peer self.peers_by_username[peer_username] = input_peer
def resolve_username(self, username: str):
username = username.lower().strip("@")
resolved_peer = self.send(
functions.contacts.ResolveUsername(
username=username
)
) # type: types.contacts.ResolvedPeer
if type(resolved_peer.peer) is PeerUser:
input_peer = InputPeerUser(
user_id=resolved_peer.users[0].id,
access_hash=resolved_peer.users[0].access_hash
)
chat_id = input_peer.user_id
elif type(resolved_peer.peer) is PeerChannel:
input_peer = InputPeerChannel(
channel_id=resolved_peer.chats[0].id,
access_hash=resolved_peer.chats[0].access_hash
)
chat_id = input_peer.channel_id
else:
raise PeerIdInvalid
self.peers_by_username[username] = input_peer
self.peers_by_id[chat_id] = input_peer
return input_peer
def resolve_peer(self, chat_id: int or str): def resolve_peer(self, chat_id: int or str):
if chat_id in ("self", "me"): if chat_id in ("self", "me"):
return InputPeerSelf() return InputPeerSelf()
else: else:
if type(chat_id) is str:
chat_id = chat_id.lower().strip("@")
try: try:
return ( return self.peers_by_username[chat_id]
self.peers_by_username[chat_id.lower().strip("@")] except KeyError:
if isinstance(chat_id, str) return self.resolve_username(chat_id)
else self.peers_by_id[chat_id] else:
) try:
return self.peers_by_id[chat_id]
except KeyError: except KeyError:
raise PeerIdInvalid raise PeerIdInvalid