What I did with 100% degree of success was:
1- Read the returning JSON when status code is 429. That should be something like:
{
"ok":false,
"error_code":429,
"description":"Too Many Requests: retry after 35",
"parameters":{
"retry_after":35
}
}
2- Add a sleep based on parameters.retry_after from that JSON
3- After sleep completes, send again the last message that gave error
4- Continue to send messages on queue until you get the next 429 error
5- Repeat steps 1 and on until all messages are delivered
My code:
def postNews(news: list[str]):
tries = 3
for link in news:
for i in range(tries):
result = requests.get(f'https://api.telegram.org/botXX:YY/sendMessage', params={'chat_id': '-999999999999999', 'text': link})
if result.status_code == 200:
#//sleep to avoid being blocked
time.sleep(2)
break
#//skip error sleep on last try
if i == tries - 1:
continue
#//there is some error, let us do some sleep
sleepTime = 3
if result.status_code == 429:
sleepTime = result.json()['parameters']['retry_after']
time.sleep(sleepTime)
else:
#//this else gets executed if the loop don't break
print(f'{link} - {result.status_code} {result.reason} {result.text}')