I’m having an hard time figuring out how to implement a simple retry function in Python, where my code should have to try to send a message to telegram for a fixed amount of times, and if after tot times it will still fail, print an error. Instead, if it succeeds, break and go on.
So i have the following array:
Retries = [1, 2, 3]
Which means that, if it fails, wait one second, and if it fails again wait 2 seconds and then 3 seconds.
Then i have the following code:
for x in Retries:
try:
updater.bot.send_message(chat_id='myid', text='TEST')
except Exception as e:
time.sleep(x)
This code will try three times and wait 1, 2, 3, seconds between each try, but the problem is that:
- Even if the message will be sent, it will still keep trying, while it needs to break
- If it will fail for three times, it should print an error, i don’t know how to do that
I found this library, but i think it’s overkill for such a simple task. Can anyone help me out on this?
2
Answers
Use a break in the try block after sending the message like this –
I recommend using pythons arcane but useful
else
clause forfor
loops:If the function call succeeds, your code will
break
out of the loop and not trigger theelse
clause. Theelse
clause is only triggered if the loop completes without abreak
.