(Telegram bot/Pyrogram) 如何在 Python 上制作一个文本随机化器,它会在不需要重新启动代码的情况下选择随机文本?
(Telegram bot/Pyrogram) How to make a text randomizer on Python that will be picking random text without a need to restart the code?
我想制作一个电报机器人,它会从文本文件中向您发送随机单词(项目需要)我制作了这个:
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)
它有效,但是这个词只被随机化了一次,你需要重新启动机器人才能选择另一个。我该怎么办?
Python 从上到下逐行解释。
由于您首先存储 myline
,然后稍后重复调用您的 command1
函数,因此您将继续使用来自 myline
的相同内容。
如果你想每次都得到一个新单词,存储你的单词列表,并且只选择一个随机项目 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)
我想制作一个电报机器人,它会从文本文件中向您发送随机单词(项目需要)我制作了这个:
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)
它有效,但是这个词只被随机化了一次,你需要重新启动机器人才能选择另一个。我该怎么办?
Python 从上到下逐行解释。
由于您首先存储 myline
,然后稍后重复调用您的 command1
函数,因此您将继续使用来自 myline
的相同内容。
如果你想每次都得到一个新单词,存储你的单词列表,并且只选择一个随机项目 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)