我想制作一个电报机器人,它从文本文件中向你发送一个随机单词(项目需要它(我制作了这个:
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)