【问题标题】:How do i make my discord.py bot pick an random line in a .txt file and reply to a message如何让我的 discord.py 机器人在 .txt 文件中随机选择一行并回复消息
【发布时间】:2022-11-18 06:35:00
【问题描述】:

好的,所以我正在为我和我的朋友制作一个 gen bot,我想知道如何让我的 bot 使用我放在 bot 文件夹中的 .txt 文件中的帐户回复消息,请帮助我,谢谢

我试过`

import random

@client.command()
async def color(ctx):
    responses = ['red',
                 'blue',
                 'green',
                 'purple',
                 'Add more',]
    await ctx.send(f'Color: {random.choice(responses)}')

` 但我不想在回复中将所有内容都放在一行中

【问题讨论】:

  • 请阐明您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 这回答了你的问题了吗? How to read a file line-by-line into a list?

标签: python discord discord.py bots


【解决方案1】:

您可以在代码中添加类似这样的内容:

import random


def readTxtLines(filename):
    with open(filename, "r") as f:
        lines = f.readlines()
    return lines


def getRandomLine(lines):
    return random.choice(lines).strip()


print(getRandomLine(readTxtLines("test.txt")))

【讨论】:

    【解决方案2】:

    这是一个 cog 形式的方法:

    @commands.command()
        async def color(self,ctx):
        
            file1=open('color.txt','r')
            wordList1=[line.rstrip('
    ') for line in file1]
            file1.close()
            out1 = random.choice(wordList1)
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2020-05-27
      • 2023-03-21
      • 2019-11-23
      • 2021-07-12
      • 1970-01-01
      • 2021-05-11
      • 2021-07-19
      • 2021-11-28
      相关资源
      最近更新 更多