I wanted to make a telegram bot which sends you a random word from text file (need that for a project) I made this:
import random
lines = open('C:\\Users\\User\\Desktop\\singnplur.txt').read().splitlines()
myline =random.choice(lines)
@bot.on_message(filters.command('rng') & filters.private)
def command1(bot, message):
bot.send_message(message.chat.id, myline)
And it works, but the word is being randomized only once and you need to restart the bot to pick another. What should i do?
>Solution :
Python interprets top to bottom, line per line.
Since you’re storing myline first, and then call your command1 function repeatedly later, you’ll keep using the same content from myline.
If you want to get a new word every time, store your list of words, and only choose a random item with command1:
with open("words.txt") as f: # automatically closes file afterwards
lines = f.read().splitlines()
@bot.on_message(...)
def command(bot, message):
word = random.choice(lines) # Choose random item every time
bot.send_message(message.chat.id, word)