-1

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:

  1. Even if the message will be sent, it will still keep trying, while it needs to break
  2. 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?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
JayK23
  • 287
  • 1
  • 15
  • 49
  • 1
    Your for loop will continues for all values in Retries, so if it sends on value one, it will still try on value 2 ect. You can end this with a break in the loop. After the 3 fails, you can simply add another condition to the loop – Joseph Lane Jul 24 '20 at 15:36
  • 2
    for 2, add an `else` block to your for loop – vlovero Jul 24 '20 at 15:37

2 Answers2

1

Use a break in the try block after sending the message like this -

for x in Retries:
    try:
        print('Hi there')
        break #Add a break here
    except Exception as e:
        time.sleep(x)
Hi there
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
1

I recommend using pythons arcane but useful else clause for for loops:

for x in Retries:
    try:
        updater.bot.send_message(chat_id='myid', text='TEST')
    except Exception as e:
        time.sleep(x)
    else:
        break
else:
    # raise the real error here

If the function call succeeds, your code will break out of the loop and not trigger the else clause. The else clause is only triggered if the loop completes without a break.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264