Как предотвратить исключение Flood control в aiogram3.x?
Есть телеграмм бот, который достаЁт данные группы в телеграмме nickname и id пользователя. КОД:
@router.message(Form.waiting_for_group_link)
async def get_group_link(message: Message, state: FSMContext):
global collecting_ids
collecting_ids = True
link = message.text.split(maxsplit=1)[-1]
counter = 0
try:
await client.start()
async with client:
formatted_text = (
f"╔════════════════════════╗\n"
f"║ <b>? Собираем участников:</b> <i>0</i> ?\n"
f"╚════════════════════════╝"
)
status_message = await message.answer(formatted_text, parse_mode='html')
entity = await client.get_entity(link)
async for msg in client.iter_messages(entity):
if not collecting_ids:
break
if msg.sender_id and msg.sender_id not in [user['id'] for user in collected_user_ids]:
username = msg.sender.username if msg.sender.username else "Unknow"
collected_user_ids.append({'id': msg.sender_id, 'username': username})
counter += 1
formatted_text = (
f"╔════════════════════════╗\n"
f"║ <b>? Собираем участников:</b> <i>{counter}</i> ?\n"
f"╚════════════════════════╝"
)
await status_message.edit_text(formatted_text, parse_mode='html')
if counter % 28 == 0:
await asyncio.sleep(2)
await status_message.edit_text("<b>Парсинг успешно завершен ✅</b>\n\n<i>? Отправляю файл...</i>",
parse_mode='html')
sleep(3)
await status_message.delete()
with open("RESULTS.txt", "w") as file:
file.write(f"{'ID':<20} {'NICKNAME':<20}\n")
file.write("=====================================\n")
for index, user in enumerate(collected_user_ids, start=1):
file.write(f"{index}{'.':<3} {user['id']:<15} @{user['username']:<20}\n")
if collected_user_ids:
document = FSInputFile(path='RESULTS.txt')
await message.answer_document(document=document, caption=f"<b>?️ Парсинг готов!</b>", parse_mode='html')
else:
await message.answer("Не удалось собрать ID участников.")
except FloodWaitError as e:
await message.answer(f"<b><i>⚠️ Слишком много запросов. Пожалуйста, подождите {e.seconds} секунд.</i></b>",
parse_mode='html')
await state.clear()
await message.answer("? Вы вернулись в главное меню.", reply_markup=main_menu)
В телеграмм документации было написано что бот может отправлять 30 запросов в секунду, поэтому я добавил это:
if counter % 28 == 0:
await asyncio.sleep(2)
Думая что это предотвратить исключение Flood control, но он все ровно выпадает. Что можно сделать чтобы это самое исключение не возникало.
ЛОГИ:
INFO:aiogram.dispatcher:Start polling
INFO:aiogram.dispatcher:Run polling for bot @chat_hunterbot id=7815606139 - 'ChatHunter'
INFO:aiogram.event:Update id=478623879 is handled. Duration 383 ms by bot id=7815606139
INFO:aiogram.event:Update id=478623880 is handled. Duration 110 ms by bot id=7815606139
INFO:telethon.network.mtprotosender:Connecting to 149.154.167.51:443/TcpFull...
INFO:telethon.network.mtprotosender:Connection to 149.154.167.51:443/TcpFull complete!
INFO:telethon.network.mtprotosender:Disconnecting from 149.154.167.51:443/TcpFull...
INFO:telethon.network.mtprotosender:Disconnection from 149.154.167.51:443/TcpFull complete!
INFO:aiogram.event:Update id=478623881 is not handled. Duration 23757 ms by bot id=7815606139
ERROR:aiogram.event:Cause exception while process update id=478623881 by bot id=7815606139
TelegramRetryAfter: Telegram server says - Flood control exceeded on method 'EditMessageText' in chat 6523126372. Retry in 224 seconds.
Original description: Too Many Requests: retry after 224