【问题标题】:(Telegram bot/Pyrogram) How to make a text randomizer on Python that will be picking random text without a need to restart the code?(Telegram bot/Pyrogram) 如何在 Python 上制作一个文本随机化器,无需重新启动代码即可选择随机文本?
【发布时间】:2022-01-19 17:21:09
【问题描述】:

我想制作一个电报机器人,它会从文本文件中向您发送一个随机单词(项目需要)我做了这个:

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 random telegram telegram-bot


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-03-12
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2017-01-25
      相关资源
      最近更新 更多