I keep running into flood protection errors when trying to send messages through Telegram’s API. I’ve tried everything I could find online, including setting wait times up to 3 minutes between messages, but I still get blocked after just 5 contacts.
import asyncio
from telethon import TelegramClient
from telethon.errors import FloodWaitError
import json
import time
WAIT_DELAY = 180 # 3 minutes
async def bulk_messenger():
# Load credentials
with open('settings.json', 'r') as config_file:
credentials = json.load(config_file)
app_id = credentials['app_id']
app_hash = credentials['app_hash']
phone_number = credentials['phone']
async with TelegramClient('session_name', app_id, app_hash) as client:
# Read contact list
contact_list = []
with open('contacts.json', 'r') as contacts_file:
contact_data = json.load(contacts_file)
message_text = input('Enter message to send: ')
for contact in contact_data:
try:
print(f'Messaging: {contact["display_name"]}')
await client.send_message(contact['user_id'], message_text)
print(f'Waiting {WAIT_DELAY} seconds...')
await asyncio.sleep(WAIT_DELAY)
except FloodWaitError as flood_err:
print(f'Hit rate limit. Need to wait {flood_err.seconds} seconds')
break
except Exception as error:
print(f'Error occurred: {error}')
continue
print('Bulk messaging completed')
if __name__ == '__main__':
asyncio.run(bulk_messenger())
Any ideas what I’m doing wrong? Are there better alternatives for sending individual messages to multiple Telegram users without getting rate limited so quickly?