Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(Telegram bot/Pyrogram) How to make a text randomizer on Python that will be picking random text without a need to restart the code?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading