0

I need this part of script work infinitely(send messages), but it works only one time and then stops

f = open('text.txt')
t = 1
with app:
    while True:
        for line in f.readlines():
            try:
                app.send_message(chat_id=line[13:].rstrip(), text=txt)
                print(f"Успешно написал в чат по ссылке {line}")
                time.sleep(0.5)
            except:
                print(f"Что-то пошло не так... Возможно в чате {line} включен медленный режим")```
            
1
  • 1
    You need to reopen the file each time through the while loop, or seek back to the beginning.
    – Barmar
    Dec 10, 2021 at 18:22

1 Answer 1

1

The for loop stops when it gets to the end of the file. When the while loop repeats, there's nothing for the for loop to read because you're already at the end of the file.

You can seek to the beginning each time.

f = open('text.txt')
t = 1
with app:
    while True:
        f.seek(0)
        for line in f.readlines():
            try:
                app.send_message(chat_id=line[13:].rstrip(), text=txt)
                print(f"Успешно написал в чат по ссылке {line}")
                time.sleep(0.5)
            except:
                print(f"Что-то пошло не так... Возможно в чате {line} включен медленный режим")     

Or you could save the contents to a list and loop through that.

with open('text.txt') as f:
    lines = f.readlines()
t = 1
with app:
    while True:
        for line in lines:
            try:
                app.send_message(chat_id=line[13:].rstrip(), text=txt)
                print(f"Успешно написал в чат по ссылке {line}")
                time.sleep(0.5)
            except:
                print(f"Что-то пошло не так... Возможно в чате {line} включен медленный режим")
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.