命令引发异常:AttributeError:'Command'对象没有属性'subreddit'Discord.PY

时间:2020-06-04 17:15:00

标签: python discord.py discord.py-rewrite praw

@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上运行它。

1 个答案:

答案 0 :(得分:2)

您的命名空间再次发生相同的问题-即使您已经在命令外部创建了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(...),因为它是最新的变量定义。