2018-06-09 22:22:54 +03:00
|
|
|
import asyncio
|
2019-07-17 13:04:53 +03:00
|
|
|
import datetime
|
2018-06-09 22:22:54 +03:00
|
|
|
import itertools
|
2018-06-18 14:22:25 +03:00
|
|
|
import time
|
2019-05-03 22:37:27 +03:00
|
|
|
import typing
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-12-23 15:52:07 +03:00
|
|
|
from .. import errors, helpers, utils, hints
|
2018-08-24 19:25:58 +03:00
|
|
|
from ..errors import MultiError, RPCError
|
2019-02-06 21:41:45 +03:00
|
|
|
from ..helpers import retry_range
|
2019-05-03 22:37:27 +03:00
|
|
|
from ..tl import TLRequest, types, functions
|
2018-06-12 21:05:05 +03:00
|
|
|
|
2019-02-06 21:41:45 +03:00
|
|
|
_NOT_A_REQUEST = lambda: TypeError('You can only invoke requests, not types!')
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
if typing.TYPE_CHECKING:
|
|
|
|
from .telegramclient import TelegramClient
|
|
|
|
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-07-17 13:04:53 +03:00
|
|
|
def _fmt_flood(delay, request, *, early=False, td=datetime.timedelta):
|
|
|
|
return (
|
|
|
|
'Sleeping%s for %ds (%s) on %s flood wait',
|
|
|
|
' early' if early else '',
|
|
|
|
delay,
|
|
|
|
td(seconds=delay),
|
|
|
|
request.__class__.__name__
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2019-06-24 18:48:46 +03:00
|
|
|
class UserMethods:
|
2019-05-03 22:37:27 +03:00
|
|
|
async def __call__(self: 'TelegramClient', request, ordered=False):
|
2020-04-28 21:49:57 +03:00
|
|
|
return await self._call(self._sender, request, ordered=ordered)
|
|
|
|
|
|
|
|
async def _call(self: 'TelegramClient', sender, request, ordered=False):
|
2018-08-24 19:25:58 +03:00
|
|
|
requests = (request if utils.is_list_like(request) else (request,))
|
|
|
|
for r in requests:
|
2018-06-12 21:05:05 +03:00
|
|
|
if not isinstance(r, TLRequest):
|
2019-02-06 21:41:45 +03:00
|
|
|
raise _NOT_A_REQUEST()
|
2018-06-09 22:22:54 +03:00
|
|
|
await r.resolve(self, utils)
|
|
|
|
|
2018-07-21 13:25:20 +03:00
|
|
|
# Avoid making the request if it's already in a flood wait
|
|
|
|
if r.CONSTRUCTOR_ID in self._flood_waited_requests:
|
|
|
|
due = self._flood_waited_requests[r.CONSTRUCTOR_ID]
|
|
|
|
diff = round(due - time.time())
|
|
|
|
if diff <= 3: # Flood waits below 3 seconds are "ignored"
|
|
|
|
self._flood_waited_requests.pop(r.CONSTRUCTOR_ID, None)
|
|
|
|
elif diff <= self.flood_sleep_threshold:
|
2019-07-17 13:04:53 +03:00
|
|
|
self._log[__name__].info(*_fmt_flood(diff, r, early=True))
|
2020-07-25 19:39:35 +03:00
|
|
|
await asyncio.sleep(diff)
|
2018-07-21 13:25:20 +03:00
|
|
|
self._flood_waited_requests.pop(r.CONSTRUCTOR_ID, None)
|
|
|
|
else:
|
2019-05-27 19:18:38 +03:00
|
|
|
raise errors.FloodWaitError(request=r, capture=diff)
|
2018-07-21 13:25:20 +03:00
|
|
|
|
|
|
|
request_index = 0
|
2020-10-01 12:53:17 +03:00
|
|
|
last_error = None
|
2018-06-18 14:22:25 +03:00
|
|
|
self._last_request = time.time()
|
2020-10-01 12:53:17 +03:00
|
|
|
|
2019-02-06 21:41:45 +03:00
|
|
|
for attempt in retry_range(self._request_retries):
|
2018-06-09 22:22:54 +03:00
|
|
|
try:
|
2020-04-28 21:49:57 +03:00
|
|
|
future = sender.send(request, ordered=ordered)
|
2018-06-09 22:22:54 +03:00
|
|
|
if isinstance(future, list):
|
|
|
|
results = []
|
2018-08-24 19:25:58 +03:00
|
|
|
exceptions = []
|
2018-06-09 22:22:54 +03:00
|
|
|
for f in future:
|
2018-08-24 19:25:58 +03:00
|
|
|
try:
|
|
|
|
result = await f
|
|
|
|
except RPCError as e:
|
|
|
|
exceptions.append(e)
|
|
|
|
results.append(None)
|
|
|
|
continue
|
2018-10-12 23:00:02 +03:00
|
|
|
self.session.process_entities(result)
|
2019-03-26 13:27:21 +03:00
|
|
|
self._entity_cache.add(result)
|
2018-08-24 19:25:58 +03:00
|
|
|
exceptions.append(None)
|
2018-06-18 21:44:20 +03:00
|
|
|
results.append(result)
|
2018-07-21 13:25:20 +03:00
|
|
|
request_index += 1
|
2018-08-24 20:50:55 +03:00
|
|
|
if any(x is not None for x in exceptions):
|
2018-08-24 19:25:58 +03:00
|
|
|
raise MultiError(exceptions, results, requests)
|
|
|
|
else:
|
|
|
|
return results
|
2018-06-09 22:22:54 +03:00
|
|
|
else:
|
2018-06-18 21:44:20 +03:00
|
|
|
result = await future
|
2018-10-12 23:00:02 +03:00
|
|
|
self.session.process_entities(result)
|
2019-03-26 13:27:21 +03:00
|
|
|
self._entity_cache.add(result)
|
2018-06-18 21:44:20 +03:00
|
|
|
return result
|
2019-02-14 12:58:48 +03:00
|
|
|
except (errors.ServerError, errors.RpcCallFailError,
|
2020-08-03 13:35:25 +03:00
|
|
|
errors.RpcMcgetFailError, errors.InterdcCallErrorError,
|
|
|
|
errors.InterdcCallRichErrorError) as e:
|
2020-10-01 12:53:17 +03:00
|
|
|
last_error = e
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].warning(
|
|
|
|
'Telegram is having internal issues %s: %s',
|
|
|
|
e.__class__.__name__, e)
|
2019-02-14 12:58:48 +03:00
|
|
|
|
|
|
|
await asyncio.sleep(2)
|
2019-09-24 12:37:41 +03:00
|
|
|
except (errors.FloodWaitError, errors.SlowModeWaitError, errors.FloodTestPhoneWaitError) as e:
|
2020-10-01 12:53:17 +03:00
|
|
|
last_error = e
|
2018-07-21 13:25:20 +03:00
|
|
|
if utils.is_list_like(request):
|
|
|
|
request = request[request_index]
|
|
|
|
|
2020-11-07 14:09:00 +03:00
|
|
|
# SLOW_MODE_WAIT is chat-specific, not request-specific
|
|
|
|
if not isinstance(e, errors.SlowModeWaitError):
|
|
|
|
self._flood_waited_requests\
|
|
|
|
[request.CONSTRUCTOR_ID] = time.time() + e.seconds
|
2018-07-21 13:25:20 +03:00
|
|
|
|
2020-05-13 19:50:56 +03:00
|
|
|
# In test servers, FLOOD_WAIT_0 has been observed, and sleeping for
|
|
|
|
# such a short amount will cause retries very fast leading to issues.
|
|
|
|
if e.seconds == 0:
|
|
|
|
e.seconds = 1
|
|
|
|
|
2018-06-26 17:09:16 +03:00
|
|
|
if e.seconds <= self.flood_sleep_threshold:
|
2019-07-17 13:04:53 +03:00
|
|
|
self._log[__name__].info(*_fmt_flood(e.seconds, request))
|
2020-07-25 19:39:35 +03:00
|
|
|
await asyncio.sleep(e.seconds)
|
2018-06-09 22:22:54 +03:00
|
|
|
else:
|
|
|
|
raise
|
|
|
|
except (errors.PhoneMigrateError, errors.NetworkMigrateError,
|
|
|
|
errors.UserMigrateError) as e:
|
2020-10-01 12:53:17 +03:00
|
|
|
last_error = e
|
2019-01-11 17:52:30 +03:00
|
|
|
self._log[__name__].info('Phone migrated to %d', e.new_dc)
|
2018-06-15 14:01:16 +03:00
|
|
|
should_raise = isinstance(e, (
|
2019-01-11 17:52:30 +03:00
|
|
|
errors.PhoneMigrateError, errors.NetworkMigrateError
|
2018-06-15 14:01:16 +03:00
|
|
|
))
|
2018-06-15 00:13:42 +03:00
|
|
|
if should_raise and await self.is_user_authorized():
|
|
|
|
raise
|
2018-06-09 22:22:54 +03:00
|
|
|
await self._switch_dc(e.new_dc)
|
|
|
|
|
2020-10-01 12:53:17 +03:00
|
|
|
if self._raise_last_call_error and last_error is not None:
|
|
|
|
raise last_error
|
2019-02-06 21:41:45 +03:00
|
|
|
raise ValueError('Request was unsuccessful {} time(s)'
|
|
|
|
.format(attempt))
|
2018-06-09 22:22:54 +03:00
|
|
|
|
|
|
|
# region Public methods
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def get_me(self: 'TelegramClient', input_peer: bool = False) \
|
2019-05-08 18:16:09 +03:00
|
|
|
-> 'typing.Union[types.User, types.InputPeerUser]':
|
2018-06-09 22:22:54 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Gets "me", the current :tl:`User` who is logged in.
|
|
|
|
|
2019-07-06 13:10:25 +03:00
|
|
|
If the user has not logged in yet, this method returns `None`.
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
2018-06-09 22:22:54 +03:00
|
|
|
input_peer (`bool`, optional):
|
|
|
|
Whether to return the :tl:`InputPeerUser` version or the normal
|
|
|
|
:tl:`User`. This can be useful if you just need to know the ID
|
|
|
|
of yourself.
|
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2018-06-09 22:22:54 +03:00
|
|
|
Your own :tl:`User`.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
2019-08-14 00:33:39 +03:00
|
|
|
me = await client.get_me()
|
|
|
|
print(me.username)
|
2018-06-09 22:22:54 +03:00
|
|
|
"""
|
|
|
|
if input_peer and self._self_input_peer:
|
|
|
|
return self._self_input_peer
|
|
|
|
|
|
|
|
try:
|
|
|
|
me = (await self(
|
|
|
|
functions.users.GetUsersRequest([types.InputUserSelf()])))[0]
|
|
|
|
|
2018-12-24 19:32:34 +03:00
|
|
|
self._bot = me.bot
|
2018-06-09 22:22:54 +03:00
|
|
|
if not self._self_input_peer:
|
|
|
|
self._self_input_peer = utils.get_input_peer(
|
|
|
|
me, allow_self=False
|
|
|
|
)
|
|
|
|
|
|
|
|
return self._self_input_peer if input_peer else me
|
|
|
|
except errors.UnauthorizedError:
|
|
|
|
return None
|
|
|
|
|
2020-10-02 11:23:04 +03:00
|
|
|
@property
|
|
|
|
def _self_id(self: 'TelegramClient') -> typing.Optional[int]:
|
|
|
|
"""
|
|
|
|
Returns the ID of the logged-in user, if known.
|
|
|
|
|
|
|
|
This property is used in every update, and some like `updateLoginToken`
|
|
|
|
occur prior to login, so it gracefully handles when no ID is known yet.
|
|
|
|
"""
|
|
|
|
return self._self_input_peer.user_id if self._self_input_peer else None
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def is_bot(self: 'TelegramClient') -> bool:
|
2018-12-24 19:32:34 +03:00
|
|
|
"""
|
2019-07-06 13:10:25 +03:00
|
|
|
Return `True` if the signed-in user is a bot, `False` otherwise.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
2019-08-14 00:33:39 +03:00
|
|
|
if await client.is_bot():
|
2019-05-20 12:38:26 +03:00
|
|
|
print('Beep')
|
|
|
|
else:
|
|
|
|
print('Hello')
|
2018-12-24 19:32:34 +03:00
|
|
|
"""
|
|
|
|
if self._bot is None:
|
|
|
|
self._bot = (await self.get_me()).bot
|
|
|
|
|
|
|
|
return self._bot
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def is_user_authorized(self: 'TelegramClient') -> bool:
|
2018-06-15 00:13:42 +03:00
|
|
|
"""
|
2019-07-17 13:37:16 +03:00
|
|
|
Returns `True` if the user is authorized (logged in).
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
2019-08-14 00:33:39 +03:00
|
|
|
if not await client.is_user_authorized():
|
|
|
|
await client.send_code_request(phone)
|
2019-05-20 12:38:26 +03:00
|
|
|
code = input('enter code: ')
|
2019-08-14 00:33:39 +03:00
|
|
|
await client.sign_in(phone, code)
|
2018-06-15 00:13:42 +03:00
|
|
|
"""
|
2018-12-06 18:07:11 +03:00
|
|
|
if self._authorized is None:
|
|
|
|
try:
|
2019-03-11 11:04:08 +03:00
|
|
|
# Any request that requires authorization will work
|
|
|
|
await self(functions.updates.GetStateRequest())
|
2018-12-06 18:07:11 +03:00
|
|
|
self._authorized = True
|
|
|
|
except errors.RPCError:
|
|
|
|
self._authorized = False
|
2018-06-15 14:01:16 +03:00
|
|
|
|
2018-12-06 18:07:11 +03:00
|
|
|
return self._authorized
|
2018-06-15 00:13:42 +03:00
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def get_entity(
|
|
|
|
self: 'TelegramClient',
|
2019-05-08 18:16:09 +03:00
|
|
|
entity: 'hints.EntitiesLike') -> 'hints.Entity':
|
2018-06-09 22:22:54 +03:00
|
|
|
"""
|
2018-06-21 12:08:14 +03:00
|
|
|
Turns the given entity into a valid Telegram :tl:`User`, :tl:`Chat`
|
|
|
|
or :tl:`Channel`. You can also pass a list or iterable of entities,
|
|
|
|
and they will be efficiently fetched from the network.
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
|
|
|
entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):
|
|
|
|
If a username is given, **the username will be resolved** making
|
|
|
|
an API call every time. Resolving usernames is an expensive
|
|
|
|
operation and will start hitting flood waits around 50 usernames
|
|
|
|
in a short period of time.
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If you want to get the entity for a *cached* username, you should
|
|
|
|
first `get_input_entity(username) <get_input_entity>` which will
|
|
|
|
use the cache), and then use `get_entity` with the result of the
|
|
|
|
previous call.
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Similar limits apply to invite links, and you should use their
|
|
|
|
ID instead.
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Using phone numbers (from people in your contact list), exact
|
|
|
|
names, integer IDs or :tl:`Peer` rely on a `get_input_entity`
|
|
|
|
first, which in turn needs the entity to be in cache, unless
|
|
|
|
a :tl:`InputPeer` was passed.
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Unsupported types will raise ``TypeError``.
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If the entity can't be found, ``ValueError`` will be raised.
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2018-06-09 22:22:54 +03:00
|
|
|
:tl:`User`, :tl:`Chat` or :tl:`Channel` corresponding to the
|
|
|
|
input entity. A list will be returned if more than one was given.
|
2019-05-09 13:24:37 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Example
|
2019-05-09 13:24:37 +03:00
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
from telethon import utils
|
|
|
|
|
2019-08-14 00:33:39 +03:00
|
|
|
me = await client.get_entity('me')
|
2019-05-09 13:24:37 +03:00
|
|
|
print(utils.get_display_name(me))
|
|
|
|
|
2019-08-14 00:33:39 +03:00
|
|
|
chat = await client.get_input_entity('username')
|
|
|
|
async for message in client.iter_messages(chat):
|
2019-05-09 13:24:37 +03:00
|
|
|
...
|
|
|
|
|
|
|
|
# Note that you could have used the username directly, but it's
|
|
|
|
# good to use get_input_entity if you will reuse it a lot.
|
2019-08-14 00:33:39 +03:00
|
|
|
async for message in client.iter_messages('username'):
|
2019-05-09 13:24:37 +03:00
|
|
|
...
|
|
|
|
|
|
|
|
# Note that for this to work the phone number must be in your contacts
|
2019-08-14 00:33:39 +03:00
|
|
|
some_id = await client.get_peer_id('+34123456789')
|
2018-06-09 22:22:54 +03:00
|
|
|
"""
|
|
|
|
single = not utils.is_list_like(entity)
|
|
|
|
if single:
|
|
|
|
entity = (entity,)
|
|
|
|
|
|
|
|
# Group input entities by string (resolve username),
|
|
|
|
# input users (get users), input chat (get chats) and
|
|
|
|
# input channels (get channels) to get the most entities
|
|
|
|
# in the less amount of calls possible.
|
2018-06-20 21:18:16 +03:00
|
|
|
inputs = []
|
|
|
|
for x in entity:
|
|
|
|
if isinstance(x, str):
|
|
|
|
inputs.append(x)
|
|
|
|
else:
|
|
|
|
inputs.append(await self.get_input_entity(x))
|
|
|
|
|
2019-12-23 15:52:07 +03:00
|
|
|
lists = {
|
|
|
|
helpers._EntityType.USER: [],
|
|
|
|
helpers._EntityType.CHAT: [],
|
|
|
|
helpers._EntityType.CHANNEL: [],
|
|
|
|
}
|
|
|
|
for x in inputs:
|
|
|
|
try:
|
|
|
|
lists[helpers._entity_type(x)].append(x)
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
users = lists[helpers._EntityType.USER]
|
|
|
|
chats = lists[helpers._EntityType.CHAT]
|
|
|
|
channels = lists[helpers._EntityType.CHANNEL]
|
2018-06-09 22:22:54 +03:00
|
|
|
if users:
|
|
|
|
# GetUsersRequest has a limit of 200 per call
|
|
|
|
tmp = []
|
|
|
|
while users:
|
|
|
|
curr, users = users[:200], users[200:]
|
|
|
|
tmp.extend(await self(functions.users.GetUsersRequest(curr)))
|
|
|
|
users = tmp
|
|
|
|
if chats: # TODO Handle chats slice?
|
|
|
|
chats = (await self(
|
2020-01-08 14:07:58 +03:00
|
|
|
functions.messages.GetChatsRequest([x.chat_id for x in chats]))).chats
|
2018-06-09 22:22:54 +03:00
|
|
|
if channels:
|
|
|
|
channels = (await self(
|
|
|
|
functions.channels.GetChannelsRequest(channels))).chats
|
|
|
|
|
|
|
|
# Merge users, chats and channels into a single dictionary
|
|
|
|
id_entity = {
|
|
|
|
utils.get_peer_id(x): x
|
|
|
|
for x in itertools.chain(users, chats, channels)
|
|
|
|
}
|
|
|
|
|
|
|
|
# We could check saved usernames and put them into the users,
|
|
|
|
# chats and channels list from before. While this would reduce
|
|
|
|
# the amount of ResolveUsername calls, it would fail to catch
|
|
|
|
# username changes.
|
2018-06-20 21:18:16 +03:00
|
|
|
result = []
|
|
|
|
for x in inputs:
|
|
|
|
if isinstance(x, str):
|
|
|
|
result.append(await self._get_entity_from_string(x))
|
|
|
|
elif not isinstance(x, types.InputPeerSelf):
|
|
|
|
result.append(id_entity[utils.get_peer_id(x)])
|
|
|
|
else:
|
|
|
|
result.append(next(
|
|
|
|
u for u in id_entity.values()
|
|
|
|
if isinstance(u, types.User) and u.is_self
|
|
|
|
))
|
|
|
|
|
2018-06-09 22:22:54 +03:00
|
|
|
return result[0] if single else result
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def get_input_entity(
|
|
|
|
self: 'TelegramClient',
|
2019-05-08 18:16:09 +03:00
|
|
|
peer: 'hints.EntityLike') -> 'types.TypeInputPeer':
|
2018-06-09 22:22:54 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Turns the given entity into its input entity version.
|
|
|
|
|
|
|
|
Most requests use this kind of :tl:`InputPeer`, so this is the most
|
|
|
|
suitable call to make for those cases. **Generally you should let the
|
|
|
|
library do its job** and don't worry about getting the input entity
|
|
|
|
first, but if you're going to use an entity often, consider making the
|
|
|
|
call:
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Arguments
|
|
|
|
entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):
|
|
|
|
If a username or invite link is given, **the library will
|
|
|
|
use the cache**. This means that it's possible to be using
|
|
|
|
a username that *changed* or an old invite link (this only
|
|
|
|
happens if an invite link for a small group chat is used
|
|
|
|
after it was upgraded to a mega-group).
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If the username or ID from the invite link is not found in
|
|
|
|
the cache, it will be fetched. The same rules apply to phone
|
|
|
|
numbers (``'+34 123456789'``) from people in your contact list.
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If an exact name is given, it must be in the cache too. This
|
|
|
|
is not reliable as different people can share the same name
|
|
|
|
and which entity is returned is arbitrary, and should be used
|
|
|
|
only for quick tests.
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If a positive integer ID is given, the entity will be searched
|
|
|
|
in cached users, chats or channels, without making any call.
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If a negative integer ID is given, the entity will be searched
|
|
|
|
exactly as either a chat (prefixed with ``-``) or as a channel
|
|
|
|
(prefixed with ``-100``).
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If a :tl:`Peer` is given, it will be searched exactly in the
|
|
|
|
cache as either a user, chat or channel.
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If the given object can be turned into an input entity directly,
|
|
|
|
said operation will be done.
|
2018-06-21 12:08:14 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Unsupported types will raise ``TypeError``.
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
If the entity can't be found, ``ValueError`` will be raised.
|
2018-06-09 22:22:54 +03:00
|
|
|
|
2019-05-20 12:38:26 +03:00
|
|
|
Returns
|
2018-06-09 22:22:54 +03:00
|
|
|
:tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`
|
|
|
|
or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.
|
|
|
|
|
|
|
|
If you need to get the ID of yourself, you should use
|
|
|
|
`get_me` with ``input_peer=True``) instead.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
# If you're going to use "username" often in your code
|
|
|
|
# (make a lot of calls), consider getting its input entity
|
|
|
|
# once, and then using the "user" everywhere instead.
|
2019-08-14 00:33:39 +03:00
|
|
|
user = await client.get_input_entity('username')
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
# The same applies to IDs, chats or channels.
|
2019-08-14 00:33:39 +03:00
|
|
|
chat = await client.get_input_entity(-123456789)
|
2018-06-09 22:22:54 +03:00
|
|
|
"""
|
2019-04-03 10:36:58 +03:00
|
|
|
# Short-circuit if the input parameter directly maps to an InputPeer
|
|
|
|
try:
|
|
|
|
return utils.get_input_peer(peer)
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
# Next in priority is having a peer (or its ID) cached in-memory
|
|
|
|
try:
|
|
|
|
# 0x2d45687 == crc32(b'Peer')
|
|
|
|
if isinstance(peer, int) or peer.SUBCLASS_OF_ID == 0x2d45687:
|
|
|
|
return self._entity_cache[peer]
|
|
|
|
except (AttributeError, KeyError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
# Then come known strings that take precedence
|
2018-06-09 22:22:54 +03:00
|
|
|
if peer in ('me', 'self'):
|
|
|
|
return types.InputPeerSelf()
|
|
|
|
|
2019-04-03 10:36:58 +03:00
|
|
|
# No InputPeer, cached peer, or known string. Fetch from disk cache
|
2018-06-09 22:22:54 +03:00
|
|
|
try:
|
2019-04-03 10:36:58 +03:00
|
|
|
return self.session.get_input_entity(peer)
|
|
|
|
except ValueError:
|
2018-06-09 22:22:54 +03:00
|
|
|
pass
|
|
|
|
|
2019-04-03 10:36:58 +03:00
|
|
|
# Only network left to try
|
2018-06-09 22:22:54 +03:00
|
|
|
if isinstance(peer, str):
|
|
|
|
return utils.get_input_peer(
|
|
|
|
await self._get_entity_from_string(peer))
|
|
|
|
|
2018-12-24 19:32:16 +03:00
|
|
|
# If we're a bot and the user has messaged us privately users.getUsers
|
|
|
|
# will work with access_hash = 0. Similar for channels.getChannels.
|
|
|
|
# If we're not a bot but the user is in our contacts, it seems to work
|
|
|
|
# regardless. These are the only two special-cased requests.
|
|
|
|
peer = utils.get_peer(peer)
|
|
|
|
if isinstance(peer, types.PeerUser):
|
|
|
|
users = await self(functions.users.GetUsersRequest([
|
|
|
|
types.InputUser(peer.user_id, access_hash=0)]))
|
2019-01-08 12:58:58 +03:00
|
|
|
if users and not isinstance(users[0], types.UserEmpty):
|
|
|
|
# If the user passed a valid ID they expect to work for
|
|
|
|
# channels but would be valid for users, we get UserEmpty.
|
|
|
|
# Avoid returning the invalid empty input peer for that.
|
|
|
|
#
|
|
|
|
# We *could* try to guess if it's a channel first, and if
|
|
|
|
# it's not, work as a chat and try to validate it through
|
|
|
|
# another request, but that becomes too much work.
|
2018-12-24 19:32:16 +03:00
|
|
|
return utils.get_input_peer(users[0])
|
|
|
|
elif isinstance(peer, types.PeerChat):
|
|
|
|
return types.InputPeerChat(peer.chat_id)
|
|
|
|
elif isinstance(peer, types.PeerChannel):
|
|
|
|
try:
|
|
|
|
channels = await self(functions.channels.GetChannelsRequest([
|
|
|
|
types.InputChannel(peer.channel_id, access_hash=0)]))
|
|
|
|
return utils.get_input_peer(channels.chats[0])
|
|
|
|
except errors.ChannelInvalidError:
|
|
|
|
pass
|
|
|
|
|
2018-06-09 22:22:54 +03:00
|
|
|
raise ValueError(
|
2021-03-14 03:32:01 +03:00
|
|
|
'Could not find the input entity for {} ({}). Please read https://'
|
2019-05-22 12:29:46 +03:00
|
|
|
'docs.telethon.dev/en/latest/concepts/entities.html to'
|
2018-06-09 22:22:54 +03:00
|
|
|
' find out more details.'
|
2021-03-14 03:32:01 +03:00
|
|
|
.format(peer, type(peer).__name__)
|
2018-06-09 22:22:54 +03:00
|
|
|
)
|
|
|
|
|
2020-10-23 20:02:43 +03:00
|
|
|
async def _get_peer(self: 'TelegramClient', peer: 'hints.EntityLike'):
|
|
|
|
i, cls = utils.resolve_id(await self.get_peer_id(peer))
|
|
|
|
return cls(i)
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def get_peer_id(
|
|
|
|
self: 'TelegramClient',
|
2019-05-08 18:16:09 +03:00
|
|
|
peer: 'hints.EntityLike',
|
2019-05-03 22:37:27 +03:00
|
|
|
add_mark: bool = True) -> int:
|
2018-07-07 13:45:50 +03:00
|
|
|
"""
|
2019-05-06 12:38:26 +03:00
|
|
|
Gets the ID for the given entity.
|
2018-07-07 13:45:50 +03:00
|
|
|
|
|
|
|
This method needs to be ``async`` because `peer` supports usernames,
|
2018-12-15 14:04:36 +03:00
|
|
|
invite-links, phone numbers (from people in your contact list), etc.
|
2018-07-07 13:45:50 +03:00
|
|
|
|
|
|
|
If ``add_mark is False``, then a positive ID will be returned
|
|
|
|
instead. By default, bot-API style IDs (signed) are returned.
|
2019-05-20 12:38:26 +03:00
|
|
|
|
|
|
|
Example
|
|
|
|
.. code-block:: python
|
|
|
|
|
2019-08-14 00:33:39 +03:00
|
|
|
print(await client.get_peer_id('me'))
|
2018-07-07 13:45:50 +03:00
|
|
|
"""
|
|
|
|
if isinstance(peer, int):
|
|
|
|
return utils.get_peer_id(peer, add_mark=add_mark)
|
|
|
|
|
|
|
|
try:
|
2019-02-11 12:40:35 +03:00
|
|
|
if peer.SUBCLASS_OF_ID not in (0x2d45687, 0xc91c90b6):
|
2018-07-07 13:45:50 +03:00
|
|
|
# 0x2d45687, 0xc91c90b6 == crc32(b'Peer') and b'InputPeer'
|
2019-02-11 12:40:35 +03:00
|
|
|
peer = await self.get_input_entity(peer)
|
2018-07-07 13:45:50 +03:00
|
|
|
except AttributeError:
|
2019-02-11 12:40:35 +03:00
|
|
|
peer = await self.get_input_entity(peer)
|
2018-07-07 13:45:50 +03:00
|
|
|
|
|
|
|
if isinstance(peer, types.InputPeerSelf):
|
|
|
|
peer = await self.get_me(input_peer=True)
|
|
|
|
|
|
|
|
return utils.get_peer_id(peer, add_mark=add_mark)
|
|
|
|
|
2018-06-09 22:22:54 +03:00
|
|
|
# endregion
|
|
|
|
|
|
|
|
# region Private methods
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _get_entity_from_string(self: 'TelegramClient', string):
|
2018-06-09 22:22:54 +03:00
|
|
|
"""
|
|
|
|
Gets a full entity from the given string, which may be a phone or
|
2018-09-22 20:18:42 +03:00
|
|
|
a username, and processes all the found entities on the session.
|
2018-06-09 22:22:54 +03:00
|
|
|
The string may also be a user link, or a channel/chat invite link.
|
|
|
|
|
|
|
|
This method has the side effect of adding the found users to the
|
|
|
|
session database, so it can be queried later without API calls,
|
|
|
|
if this option is enabled on the session.
|
|
|
|
|
|
|
|
Returns the found entity, or raises TypeError if not found.
|
|
|
|
"""
|
|
|
|
phone = utils.parse_phone(string)
|
|
|
|
if phone:
|
2018-10-15 19:42:35 +03:00
|
|
|
try:
|
|
|
|
for user in (await self(
|
|
|
|
functions.contacts.GetContactsRequest(0))).users:
|
|
|
|
if user.phone == phone:
|
|
|
|
return user
|
|
|
|
except errors.BotMethodInvalidError:
|
|
|
|
raise ValueError('Cannot get entity by phone number as a '
|
|
|
|
'bot (try using integer IDs, not strings)')
|
2018-10-19 17:57:46 +03:00
|
|
|
elif string.lower() in ('me', 'self'):
|
|
|
|
return await self.get_me()
|
2018-06-09 22:22:54 +03:00
|
|
|
else:
|
|
|
|
username, is_join_chat = utils.parse_username(string)
|
|
|
|
if is_join_chat:
|
|
|
|
invite = await self(
|
|
|
|
functions.messages.CheckChatInviteRequest(username))
|
|
|
|
|
|
|
|
if isinstance(invite, types.ChatInvite):
|
|
|
|
raise ValueError(
|
|
|
|
'Cannot get entity from a channel (or group) '
|
|
|
|
'that you are not part of. Join the group and retry'
|
|
|
|
)
|
|
|
|
elif isinstance(invite, types.ChatInviteAlready):
|
|
|
|
return invite.chat
|
|
|
|
elif username:
|
|
|
|
try:
|
|
|
|
result = await self(
|
|
|
|
functions.contacts.ResolveUsernameRequest(username))
|
|
|
|
except errors.UsernameNotOccupiedError as e:
|
|
|
|
raise ValueError('No user has "{}" as username'
|
|
|
|
.format(username)) from e
|
|
|
|
|
2018-08-26 13:00:17 +03:00
|
|
|
try:
|
|
|
|
pid = utils.get_peer_id(result.peer, add_mark=False)
|
|
|
|
if isinstance(result.peer, types.PeerUser):
|
|
|
|
return next(x for x in result.users if x.id == pid)
|
|
|
|
else:
|
|
|
|
return next(x for x in result.chats if x.id == pid)
|
|
|
|
except StopIteration:
|
|
|
|
pass
|
2018-06-09 22:22:54 +03:00
|
|
|
try:
|
|
|
|
# Nobody with this username, maybe it's an exact name/title
|
|
|
|
return await self.get_entity(
|
2018-10-12 23:00:02 +03:00
|
|
|
self.session.get_input_entity(string))
|
2018-06-09 22:22:54 +03:00
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
raise ValueError(
|
|
|
|
'Cannot find any entity corresponding to "{}"'.format(string)
|
|
|
|
)
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _get_input_dialog(self: 'TelegramClient', dialog):
|
2018-09-22 11:56:37 +03:00
|
|
|
"""
|
|
|
|
Returns a :tl:`InputDialogPeer`. This is a bit tricky because
|
|
|
|
it may or not need access to the client to convert what's given
|
|
|
|
into an input entity.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'InputDialogPeer')
|
|
|
|
dialog.peer = await self.get_input_entity(dialog.peer)
|
|
|
|
return dialog
|
|
|
|
elif dialog.SUBCLASS_OF_ID == 0xc91c90b6: # crc32(b'InputPeer')
|
|
|
|
return types.InputDialogPeer(dialog)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return types.InputDialogPeer(await self.get_input_entity(dialog))
|
|
|
|
|
2019-05-03 22:37:27 +03:00
|
|
|
async def _get_input_notify(self: 'TelegramClient', notify):
|
2018-07-07 13:14:03 +03:00
|
|
|
"""
|
|
|
|
Returns a :tl:`InputNotifyPeer`. This is a bit tricky because
|
|
|
|
it may or not need access to the client to convert what's given
|
|
|
|
into an input entity.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
if notify.SUBCLASS_OF_ID == 0x58981615:
|
|
|
|
if isinstance(notify, types.InputNotifyPeer):
|
|
|
|
notify.peer = await self.get_input_entity(notify.peer)
|
|
|
|
return notify
|
|
|
|
except AttributeError:
|
2021-03-13 21:06:19 +03:00
|
|
|
pass
|
|
|
|
|
|
|
|
return types.InputNotifyPeer(await self.get_input_entity(notify))
|
2018-07-07 13:14:03 +03:00
|
|
|
|
2018-06-09 22:22:54 +03:00
|
|
|
# endregion
|