随机未定义不和谐

Random Not Defined for discord

我一直在尝试编写一个 Discord 机器人并制作一个 8ball,但它告诉我未定义随机数。

@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
        responses = [ "It is certain.",
                    "It is decidedly so.",
                    "Without a doubt.",
                    "Yes - definitely.",
                    "You may rely on it.",
                    "As I see it, yes.",
                    "Most likely.",
                    "Outlook good.",
                    "Yes.",
                    "Signs point to yes.",
                    "Reply hazy, try again.",
                    "Ask again later.",
                    "Better not tell you now.",
                    "Cannot predict now.",
                    "Concentrate and ask again.",
                    "Don't count on it.",
                    "My reply is no.",
                    "My sources say no.",
                    "Outlook not so good.",
                    "Very doubtful."]
        await ctx.send(f'Question: {question}\nAnswer: {random.choices(responses)}')

我遇到了错误

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'random' is not defined

我的代码有问题吗?这是我第一次编码。

在您的代码中某处有一个名为 random 的变量。我看到它应该有一个名为 choices 的函数。您在 f 字符串的行中使用它:

await ctx.send(f'Question: {question}\nAnswer: {random.choices(responses)}')

确保您在此行之前定义了它。

或者,如果这是 Python 核心中的标准 random,那么就像 jasonharper 建议的那样,确保你导入了它。

您可能需要 import random 转到代码的顶部 import discord 并输入 down 和 import random 然后尝试 参考:https://docs.python.org/3/library/random.html