Command raised an exception: AttributeError: 'Command' object has no attribute 'subreddit' Discord.PY

Command raised an exception: AttributeError: 'Command' object has no attribute 'subreddit' Discord.PY

@client.command()
async def reddit(ctx):
    memes_submissions = reddit.subreddit('memes').hot()
    post_to_pick = random.randint(1, 10)
    for i in range(0, post_to_pick):
        submission = next(x for x in memes_submissions if not x.stickied)

    await ctx.send(submission.url)

这是我的代码。当我输入 .reddit 时,它应该会从 r/memes 中随机找到一个热门模因。它没有给我一些新鲜的模因,而是给我一个错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'subreddit'

据我了解,该程序不知道 subreddit 是什么。但我认为它应该从 PRAW 获取 subreddit 命令。这就是我定义 reddit:

的方式
reddit = praw.Reddit(client_id="id",
                 client_secret="secret",
                 user_agent="MASTERBOT")

我在想这可能是因为我编写或定义了 user_agent 错误,因为我不知道那是什么。我把所有东西都按原样导入了。在每个人身上,代码似乎都有效。可能是我的 Python 的问题?我是 运行 3.8.

您的命名空间再次发生同样的问题 - 您调用了命令 reddit,即使您已经在命令之外创建了 reddit 变量。

尝试重命名:

reddit = praw.Reddit(client_id="id", ....)

@client.command(name="reddit") # this is what the command will be in discord
async def _reddit(ctx):
    memes_submissions = reddit.subreddit('memes').hot()
    post_to_pick = random.randint(1, 10)
    for i in range(0, post_to_pick):
        submission = next(x for x in memes_submissions if not x.stickied)

    await ctx.send(submission.url)

您已经在此处定义了变量 reddit

reddit = praw.Reddit(...)

所以有一个函数定义如下:

async def reddit(...):

将隐藏您在外部定义的变量,如果您尝试在函数内引用 reddit,它实际上会查看 async def reddit(...): 而不是 reddit = praw.Reddit(...),因为这是变量的最新定义。