Visitar URL original
Use the correct way to parse peer identifiers · hexa0code/pyrogram@ad0f828 · GitHub
Skip to content

Commit ad0f828

Browse files
committed
Use the correct way to parse peer identifiers
1 parent 9ad5e62 commit ad0f828

8 files changed

Lines changed: 80 additions & 71 deletions

File tree

‎pyrogram/client/client.py‎

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,7 +1015,7 @@ def fetch_peers(
10151015
access_hash = 0
10161016
peer_type = "group"
10171017
elif isinstance(peer, (types.Channel, types.ChannelForbidden)):
1018-
peer_id = int("-100" + str(peer.id))
1018+
peer_id = utils.get_channel_id(peer.id)
10191019
access_hash = peer.access_hash
10201020

10211021
username = getattr(peer, "username", None)
@@ -1131,7 +1131,7 @@ def updates_worker(self):
11311131
try:
11321132
diff = self.send(
11331133
functions.updates.GetChannelDifference(
1134-
channel=self.resolve_peer(int("-100" + str(channel_id))),
1134+
channel=self.resolve_peer(utils.get_channel_id(channel_id)),
11351135
filter=types.ChannelMessagesFilter(
11361136
ranges=[types.MessageRange(
11371137
min_id=update.message.id,
@@ -1519,33 +1519,38 @@ def resolve_peer(self, peer_id: Union[int, str]):
15191519
except KeyError:
15201520
raise PeerIdInvalid
15211521

1522-
if peer_id > 0:
1522+
peer_type = utils.get_type(peer_id)
1523+
1524+
if peer_type == "user":
15231525
self.fetch_peers(
15241526
self.send(
15251527
functions.users.GetUsers(
1526-
id=[types.InputUser(
1527-
user_id=peer_id,
1528-
access_hash=0
1529-
)]
1528+
id=[
1529+
types.InputUser(
1530+
user_id=peer_id,
1531+
access_hash=0
1532+
)
1533+
]
15301534
)
15311535
)
15321536
)
1537+
elif peer_type == "chat":
1538+
self.send(
1539+
functions.messages.GetChats(
1540+
id=[-peer_id]
1541+
)
1542+
)
15331543
else:
1534-
if str(peer_id).startswith("-100"):
1535-
self.send(
1536-
functions.channels.GetChannels(
1537-
id=[types.InputChannel(
1538-
channel_id=int(str(peer_id)[4:]),
1544+
self.send(
1545+
functions.channels.GetChannels(
1546+
id=[
1547+
types.InputChannel(
1548+
channel_id=utils.get_channel_id(peer_id),
15391549
access_hash=0
1540-
)]
1541-
)
1542-
)
1543-
else:
1544-
self.send(
1545-
functions.messages.GetChats(
1546-
id=[-peer_id]
1547-
)
1550+
)
1551+
]
15481552
)
1553+
)
15491554

15501555
try:
15511556
return self.storage.get_peer_by_id(peer_id)

‎pyrogram/client/ext/utils.py‎

Lines changed: 40 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@
1818

1919
import base64
2020
import struct
21-
from typing import Union, List
21+
from typing import List
22+
from typing import Union
2223

2324
import pyrogram
24-
25+
from pyrogram.api.types import PeerUser, PeerChat, PeerChannel
2526
from . import BaseClient
2627
from ...api import types
2728

@@ -62,23 +63,6 @@ def encode(s: bytes) -> str:
6263
return base64.urlsafe_b64encode(r).decode().rstrip("=")
6364

6465

65-
def get_peer_id(input_peer) -> int:
66-
return (
67-
input_peer.user_id if isinstance(input_peer, types.InputPeerUser)
68-
else -input_peer.chat_id if isinstance(input_peer, types.InputPeerChat)
69-
else int("-100" + str(input_peer.channel_id))
70-
)
71-
72-
73-
def get_input_peer(peer_id: int, access_hash: int):
74-
return (
75-
types.InputPeerUser(user_id=peer_id, access_hash=access_hash) if peer_id > 0
76-
else types.InputPeerChannel(channel_id=int(str(peer_id)[4:]), access_hash=access_hash)
77-
if (str(peer_id).startswith("-100") and access_hash)
78-
else types.InputPeerChat(chat_id=-peer_id)
79-
)
80-
81-
8266
def get_offset_date(dialogs):
8367
for m in reversed(dialogs.messages):
8468
if isinstance(m, types.MessageEmpty):
@@ -183,7 +167,7 @@ def parse_deleted_messages(client, update) -> List["pyrogram.Message"]:
183167
pyrogram.Message(
184168
message_id=message,
185169
chat=pyrogram.Chat(
186-
id=int("-100" + str(channel_id)),
170+
id=get_channel_id(channel_id),
187171
type="channel",
188172
client=client
189173
) if channel_id is not None else None,
@@ -203,3 +187,39 @@ def unpack_inline_message_id(inline_message_id: str) -> types.InputBotInlineMess
203187
id=r[1],
204188
access_hash=r[2]
205189
)
190+
191+
192+
MIN_CHANNEL_ID = -1002147483647
193+
MAX_CHANNEL_ID = -1000000000000
194+
MIN_CHAT_ID = -2147483647
195+
MAX_USER_ID = 2147483647
196+
197+
198+
def get_peer_id(peer: Union[PeerUser, PeerChat, PeerChannel]) -> int:
199+
if isinstance(peer, PeerUser):
200+
return peer.user_id
201+
202+
if isinstance(peer, PeerChat):
203+
return -peer.chat_id
204+
205+
if isinstance(peer, PeerChannel):
206+
return MAX_CHANNEL_ID - peer.channel_id
207+
208+
raise ValueError("Peer type invalid: {}".format(peer))
209+
210+
211+
def get_type(peer_id: int) -> str:
212+
if peer_id < 0:
213+
if MIN_CHAT_ID <= peer_id:
214+
return "chat"
215+
216+
if MIN_CHANNEL_ID <= peer_id < MAX_CHANNEL_ID:
217+
return "channel"
218+
elif 0 < peer_id <= MAX_USER_ID:
219+
return "user"
220+
221+
raise ValueError("Peer id invalid: {}".format(peer_id))
222+
223+
224+
def get_channel_id(peer_id: int) -> int:
225+
return MAX_CHANNEL_ID - peer_id

‎pyrogram/client/methods/chats/get_chat.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
import pyrogram
2222
from pyrogram.api import functions, types
23-
from ...ext import BaseClient
23+
from ...ext import BaseClient, utils
2424

2525

2626
class GetChat(BaseClient):
@@ -70,7 +70,7 @@ def get_chat(
7070
chat_id = -r.chat.id
7171

7272
if isinstance(r.chat, types.Channel):
73-
chat_id = int("-100" + str(r.chat.id))
73+
chat_id = utils.get_channel_id(r.chat.id)
7474

7575
peer = self.resolve_peer(chat_id)
7676

‎pyrogram/client/methods/chats/get_dialogs.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import pyrogram
2424
from pyrogram.api import functions, types
2525
from pyrogram.errors import FloodWait
26-
from ...ext import BaseClient
26+
from ...ext import BaseClient, utils
2727

2828
log = logging.getLogger(__name__)
2929

@@ -100,10 +100,8 @@ def get_dialogs(
100100
chat_id = to_id.user_id
101101
else:
102102
chat_id = message.from_id
103-
elif isinstance(to_id, types.PeerChat):
104-
chat_id = -to_id.chat_id
105103
else:
106-
chat_id = int("-100" + str(to_id.channel_id))
104+
chat_id = utils.get_peer_id(to_id)
107105

108106
messages[chat_id] = pyrogram.Message._parse(self, message, users, chats)
109107

‎pyrogram/client/types/bots_and_keyboards/callback_query.py‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from ..object import Object
2626
from ..update import Update
2727
from ..user_and_chats import User
28+
from ...ext import utils
2829

2930

3031
class CallbackQuery(Object, Update):
@@ -90,16 +91,7 @@ def _parse(client, callback_query, users) -> "CallbackQuery":
9091
inline_message_id = None
9192

9293
if isinstance(callback_query, types.UpdateBotCallbackQuery):
93-
peer = callback_query.peer
94-
95-
if isinstance(peer, types.PeerUser):
96-
peer_id = peer.user_id
97-
elif isinstance(peer, types.PeerChat):
98-
peer_id = -peer.chat_id
99-
else:
100-
peer_id = int("-100" + str(peer.channel_id))
101-
102-
message = client.get_messages(peer_id, callback_query.msg_id)
94+
message = client.get_messages(utils.get_peer_id(callback_query.peer), callback_query.msg_id)
10395
elif isinstance(callback_query, types.UpdateInlineBotCallbackQuery):
10496
inline_message_id = b64encode(
10597
pack(

‎pyrogram/client/types/messages_and_media/message.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@
3131
from ..update import Update
3232
from ..user_and_chats.chat import Chat
3333
from ..user_and_chats.user import User
34-
from ...parser import utils, Parser
34+
from ...ext import utils
35+
from ...parser import utils as parser_utils, Parser
3536

3637

3738
class Str(str):
@@ -54,7 +55,7 @@ def html(self):
5455
return Parser.unparse(self, self.entities, True)
5556

5657
def __getitem__(self, item):
57-
return utils.remove_surrogates(utils.add_surrogates(self)[item])
58+
return parser_utils.remove_surrogates(parser_utils.add_surrogates(self)[item])
5859

5960

6061
class Message(Object, Update):
@@ -446,7 +447,7 @@ def _parse(client, message: types.Message or types.MessageService or types.Messa
446447
new_chat_title=new_chat_title,
447448
new_chat_photo=new_chat_photo,
448449
delete_chat_photo=delete_chat_photo,
449-
migrate_to_chat_id=int("-100" + str(migrate_to_chat_id)) if migrate_to_chat_id else None,
450+
migrate_to_chat_id=utils.get_channel_id(migrate_to_chat_id) if migrate_to_chat_id else None,
450451
migrate_from_chat_id=-migrate_from_chat_id if migrate_from_chat_id else None,
451452
group_chat_created=group_chat_created,
452453
channel_chat_created=channel_chat_created,

‎pyrogram/client/types/user_and_chats/chat.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from .chat_permissions import ChatPermissions
2424
from .chat_photo import ChatPhoto
2525
from ..object import Object
26+
from ...ext import utils
2627

2728

2829
class Chat(Object):
@@ -180,7 +181,7 @@ def _parse_chat_chat(client, chat: types.Chat) -> "Chat":
180181

181182
@staticmethod
182183
def _parse_channel_chat(client, channel: types.Channel) -> "Chat":
183-
peer_id = int("-100" + str(channel.id))
184+
peer_id = utils.get_channel_id(channel.id)
184185

185186
return Chat(
186187
id=peer_id,
@@ -672,7 +673,7 @@ def promote_member(
672673
can_pin_messages=can_pin_messages,
673674
can_promote_members=can_promote_members
674675
)
675-
676+
676677
def join(self):
677678
"""Bound method *join* of :obj:`Chat`.
678679

‎pyrogram/client/types/user_and_chats/dialog.py‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from pyrogram.api import types
2222
from ..object import Object
2323
from ..user_and_chats import Chat
24+
from ...ext import utils
2425

2526

2627
class Dialog(Object):
@@ -70,18 +71,9 @@ def __init__(
7071

7172
@staticmethod
7273
def _parse(client, dialog: types.Dialog, messages, users, chats) -> "Dialog":
73-
chat_id = dialog.peer
74-
75-
if isinstance(chat_id, types.PeerUser):
76-
chat_id = chat_id.user_id
77-
elif isinstance(chat_id, types.PeerChat):
78-
chat_id = -chat_id.chat_id
79-
else:
80-
chat_id = int("-100" + str(chat_id.channel_id))
81-
8274
return Dialog(
8375
chat=Chat._parse_dialog(client, dialog.peer, users, chats),
84-
top_message=messages.get(chat_id),
76+
top_message=messages.get(utils.get_peer_id(dialog.peer)),
8577
unread_messages_count=dialog.unread_count,
8678
unread_mentions_count=dialog.unread_mentions_count,
8779
unread_mark=dialog.unread_mark,

0 commit comments

Comments
 (0)