RPC stands for Remote Procedure Call, and when the library raises
a RPCError
, it’s because you have invoked some of the API
methods incorrectly (wrong parameters, wrong permissions, or even
something went wrong on Telegram’s server). All the errors are
available in API Errors, but some examples are:
-
FloodWaitError
(420), the same request was repeated many times.
Must wait.seconds
(you can access this attribute). For example:... from telethon import errors try: print(client.get_messages(chat)[0].text) except errors.FloodWaitError as e: print('Have to sleep', e.seconds, 'seconds') time.sleep(e.seconds)
-
SessionPasswordNeededError
, if you have setup two-steps
verification on Telegram. -
CdnFileTamperedError
, if the media you were trying to download
from a CDN has been altered. -
ChatAdminRequiredError
, you don’t have permissions to perform
said operation on a chat or channel. Try avoiding filters, i.e. when
searching messages.
The generic classes for different error codes are:
InvalidDCError
(303), the request must be repeated on another DC.BadRequestError
(400), the request contained errors.UnauthorizedError
(401), the user is not authorized yet.ForbiddenError
(403), privacy violation error.NotFoundError
(404), make sure you’re invokingRequest
’s!
If the error is not recognised, it will only be an RPCError
.
You can refer to all errors from Python through the telethon.errors
module. If you don’t know what attributes they have, try printing their
dir (like print(dir(e))
).
Avoiding Limits¶
Don’t spam. You won’t get FloodWaitError
or your account banned or
deleted if you use the library for legit use cases. Make cool tools.
Don’t spam! Nobody knows the exact limits for all requests since they
depend on a lot of factors, so don’t bother asking.
Still, if you do have a legit use case and still get those errors, the
library will automatically sleep when they are smaller than 60 seconds
by default. You can set different “auto-sleep” thresholds:
client.flood_sleep_threshold = 0 # Don't auto-sleep client.flood_sleep_threshold = 24 * 60 * 60 # Sleep always
You can also except it and act as you prefer:
from telethon.errors import FloodWaitError try: ... except FloodWaitError as e: print('Flood waited for', e.seconds) quit(1)
VoIP numbers are very limited, and some countries are more limited too.
Your export group python script was working fine but recently you tried to export members of one of your public group and it is showing following error.
telethon.errors.common.MultiError: ([None, FloodWaitError(‘A wait of 30 seconds is required (caused by GetParticipantsRequest)’)
Solution :
You need to make one change in your export script.
Remove
aggressive=True
from the line
all_participants = client.get_participants(target_group, aggressive=True)
Above line should be appeared like this
all_participants = client.get_participants(target_group)
and you will not get the following FloodWaitError anymore.
Traceback (most recent call last):
File «exportgroup.py», line 49, in <module>
all_participants = client.get_participants(target_group, aggressive=True)
File «virtualenvs/telegram/lib/python3.8/site-packages/telethon/sync.py», line 39, in syncified
return loop.run_until_complete(coro)
File «/usr/lib/python3.8/asyncio/base_events.py», line 616, in run_until_complete
return future.result()
File «virtualenvs/telegram/lib/python3.8/site-packages/telethon/client/chats.py», line 503, in get_participants
return await self.iter_participants(*args, **kwargs).collect()
File «virtualenvs/telegram/lib/python3.8/site-packages/telethon/requestiter.py», line 113, in collect
async for message in self:
File «virtualenvs/telegram/lib/python3.8/site-packages/telethon/requestiter.py», line 74, in __anext__
if await self._load_next_chunk():
File «virtualenvs/telegram/lib/python3.8/site-packages/telethon/client/chats.py», line 221, in _load_next_chunk
results = await self.client(self.requests)
File «virtualenvs/telegram/lib/python3.8/site-packages/telethon/client/users.py», line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File «virtualenvs/telegram/lib/python3.8/site-packages/telethon/client/users.py», line 75, in _call
raise MultiError(exceptions, results, requests)
telethon.errors.common.MultiError: ([None, FloodWaitError(‘A wait of 30 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 30 seconds is required (caused by GetParticipantsRequest)’)
To see the steps :
📷
Hi everyone,
I found a code that scrapes telegram group members from https://python.gotrained.com/scraping-telegram-group-members-python-telethon/
after I run it it gives error (the error comes after I chose the group).
Please help me solve this error.
Choose a group to scrape members from:
0- Zemedkun Bekele (ዘመዴ)
1- 🛒 SHEGER Marketplace 🎁
2- Safaricom Ethiopia PLC
3- ዮቶር። ከባሕሩ ዳር
4- Safaricom Ethiopia
5- ሺ ገበያ ባሕር ዳር/ Shi Gebeya Bahir Dar
6- 4ቱ ጉባኤያት በባሕር ዳር
7- timakis ጉዳይ አስፈፃሚ እና የተለያዩ አልባሳትን አቅራቢ
8- ዘኪ ዝጎራ የድለላ ስራ
9- M.E fashion
10- Women Mobility and Safety Charitable Organization (WMS)
11- Lomi Designs And Digital Advertizing
Enter a Number: 5
Fetching Members…
Traceback (most recent call last):
File «C:UsersAdministratorDesktopfrom telethon.sync import TelegramClient.sync import TelegramClient.py», line 49, in <module>
all_participants = client.get_participants(target_group, aggressive=True)
File «C:UsersAdministratorAppDataLocalProgramsPythonPython310libsite-packagestelethonsync.py», line 39, in syncified
return loop.run_until_complete(coro)
File «C:UsersAdministratorAppDataLocalProgramsPythonPython310libasynciobase_events.py», line 641, in run_until_complete
return future.result()
File «C:UsersAdministratorAppDataLocalProgramsPythonPython310libsite-packagestelethonclientchats.py», line 507, in get_participants
return await self.iter_participants(*args, **kwargs).collect()
File «C:UsersAdministratorAppDataLocalProgramsPythonPython310libsite-packagestelethonrequestiter.py», line 113, in collect
async for message in self:
File «C:UsersAdministratorAppDataLocalProgramsPythonPython310libsite-packagestelethonrequestiter.py», line 74, in __anext__
if await self._load_next_chunk():
File «C:UsersAdministratorAppDataLocalProgramsPythonPython310libsite-packagestelethonclientchats.py», line 222, in _load_next_chunk
results = await self.client(self.requests)
File «C:UsersAdministratorAppDataLocalProgramsPythonPython310libsite-packagestelethonclientusers.py», line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File «C:UsersAdministratorAppDataLocalProgramsPythonPython310libsite-packagestelethonclientusers.py», line 80, in _call
raise MultiError(exceptions, results, requests)
telethon.errors.common.MultiError: ([FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), None, FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), None, FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), None, FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’), FloodWaitError(‘A wait of 29 seconds is required (caused by GetParticipantsRequest)’)], [None, None, <telethon.tl.types.channels.ChannelParticipants object at 0x00000294EC712EC0>, None, <telethon.tl.types.channels.ChannelParticipants object at 0x00000294EC712620>, None, <telethon.tl.types.channels.ChannelParticipants object at 0x00000294ECD12B60>, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None], [<telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9E530>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9E5F0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9E6B0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9E770>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9E830>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9E8F0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9E9B0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9EA70>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9EB30>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9EBF0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9ECB0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9ED70>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9EE30>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9EEF0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9EFB0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F070>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F130>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F1F0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F2B0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F370>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F430>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F4F0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F5B0>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F670>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F730>, <telethon.tl.functions.channels.GetParticipantsRequest object at 0x00000294EBE9F7F0>])
***Repl Closed***
else:
# It doesn't make any sense to check if `photo` can be used
# as input location, because then this method would be able
# to "download the profile photo of a message", i.e. its
# media which should be done with `download_media` instead.
return None
file = self._get_proper_filename(
file, 'profile_photo', '.jpg',
possible_names=possible_names
)
try:
result = await self.download_file(loc, file, dc_id=dc_id)
return result if file is bytes else file
except errors.LocationInvalidError:
# See issue #500, Android app fails as of v4.6.0 (1155).
# The fix seems to be using the full channel chat photo.
ie = await self.get_input_entity(entity)
ty = helpers._entity_type(ie)
if ty == helpers._EntityType.CHANNEL:
full = await self(functions.channels.GetFullChannelRequest(ie))
return await self._download_photo(
full.full_chat.chat_photo, file,
date=None, progress_callback=None,
thumb=thumb
)
else:
# Until there's a report for chats, no need to.
return None
continue
self.session.process_entities(result)
self._entity_cache.add(result)
exceptions.append(None)
results.append(result)
request_index += 1
if any(x is not None for x in exceptions):
raise MultiError(exceptions, results, requests)
else:
return results
else:
result = await future
self.session.process_entities(result)
self._entity_cache.add(result)
return result
except (errors.ServerError, errors.RpcCallFailError,
errors.RpcMcgetFailError) as e:
self._log[__name__].warning(
'Telegram is having internal issues %s: %s',
e.__class__.__name__, e)
await asyncio.sleep(2)
except (errors.FloodWaitError, errors.SlowModeWaitError, errors.FloodTestPhoneWaitError) as e:
if utils.is_list_like(request):
request = request[request_index]
self._flood_waited_requests
[request.CONSTRUCTOR_ID] = time.time() + e.seconds
if e.seconds <= self.flood_sleep_threshold:
self._log[__name__].info(*_fmt_flood(e.seconds, request))
await asyncio.sleep(e.seconds, loop=self._loop)
return None
if "exc_info" in hint:
exc_type: Type[BaseException]
exc_value: BaseException
exc_type, exc_value = hint["exc_info"][:2]
# User-initiated interrupts, network errors, and I/O errors
if exc_type in (
KeyboardInterrupt,
ConnectionError,
IOError,
EOFError,
sqlite3.OperationalError,
plyvel.IOError,
tg.errors.FloodWaitError,
tg.errors.PhoneNumberInvalidError,
tg.errors.ApiIdInvalidError,
):
return None
exc_msg = str(exc_value)
# Pillow error for invalid user-submitted images
if exc_msg.startswith("cannot identify image file"):
return None
# Telegram connection errors
if (
exc_msg.startswith("Automatic reconnection failed")
or exc_msg.startswith("Request was unsuccessful")
or "Connection to Telegram failed" in exc_msg
Я не знаю, что не так, но я застрял на создании своей программы. Есть у кого-нибудь идеи по этому поводу?
Я получаю вот такую ошибку:
*Traceback (most recent call last):
File "C:UsersAdministratorDesktopTelegram Marketingadd members in channeladd members.py", line 50, in <module>
user_to_add = client.get_input_entity(user['username'])
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonsync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "c:usersadministratorappdatalocalprogramspythonpython38libasynciobase_events.py", line 616, in run_until_complete
return future.result()
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 404, in get_input_entity
await self._get_entity_from_string(peer))
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 516, in _get_entity_from_string
result = await self(
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 47, in __call__
raise errors.FloodWaitError(request=r, capture=diff)
telethon.errors.rpcerrorlist.FloodWaitError: A wait of 71180 seconds is required (caused by ResolveUsernameRequest)
Unexpected Error *
Мой код:
channel = client(GetFullChannelRequest(channel_username))
mode = 1
for user in users:
try:
print ("Adding {}".format(user['id']))
if mode == 1:
if user['username'] == "":
continue
user_to_add = client.get_input_entity(user['username'])
else:
sys.exit("Invalid Mode Selected. Please Try Again.")
client(InviteToChannelRequest(channel,[user_to_add]))
print("Waiting 60 Seconds...")
time.sleep(60)
except PeerFloodError:
print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
time.sleep(900)
except UserPrivacyRestrictedError:
print("The user's privacy settings do not allow you to do this. Skipping.")
except:
traceback.print_exc()
print("Unexpected Error")
continue
1 ответ
Лучший ответ
Попробуй это:
client(InviteToChannelRequest(channel_username,[user['username']]))
GetFullChannelRequest возвращает ChatFull, и использование его в качестве входных данных для InviteToChannelRequest вызовет ошибку типа. Все, что похоже на сущность , будет работать.
- Ссылка для приглашения канала
- Имя пользователя канала
- ID пользователя канала
Может использоваться как аргумент канала для InviteToChannelRequest. также,
- имя пользователя,
- ID пользователя,
- телефонный номер
Будет работать для аргумента пользователей.
0
Goodarzi
20 Апр 2020 в 07:57