I use this code to get random lines from the list “my_list” I created with a while loop underneath which is working if I type /start in telegram talking to my bot.
The only problem is that my pc is getting stuck because this infinite loop is propably taking my whole memory. And I don’t like this loop that is continiously working even when i’m not calling it.
The problem without the while loop is that it reads the code once and you get the same line every time you type /start in telegram.
I tried stuff like making a function, pass it to a for loop if “start” is beiing called from telegram, but without result because this is a little too advanced for me.
I hope somebody can show me the solution to get a new line from my_list if /start is typed in telegram without the while loop :’)
import time
import urllib.request as urllib
import json
import html
import random
from telegram.ext import Updater
from telegram.ext import CommandHandler
updater = Updater(token='<token>')
dispatcher = updater.dispatcher
while True:
my_list = ['"this is line1"',
'"this is line2"',
'"this is line3"',
'"this is line4"',
'"this is line5"'
]
my_random = random.choice(my_list)
def func1():
return my_random
def start(bot, update):
bot.send_message(chat_id=update.message.chat_id, text=func1())
my_handler = CommandHandler('start', start)
dispatcher.add_handler(my_handler)
updater.start_polling()
2
Answers
Thank you Arian, it works. I found another solution in the weekend by removing the func1 function and in the start function pointing directly towards my_list: text=random.choice(my_list). I also had code I couldn't iterate through, getting random text from an API. I had to put my code inside the start function. I could also do this for my_list.
Here's the code I ended up with:
if you no need to use while loop, you just need to code like this :