首页 > 解决方案 > 我的不和谐机器人在 Python 上的命令代码由于某种原因无法执行

问题描述

这是我的一个代码,它使我的机器人通过使用用户的参数来访问 Reddit 帖子:

@bot.command()
async def reddit(ctx, *, args):
    global block, embed
    keywords = ""
    sub = ['memes', 'showerthoughts', 'jokes', 'antijokes']
    if args:
        for i in range(0, len(sub)):
            if sub[i] in args:
                keywords = sub[i]
                break
            else:
                await ctx.send("The sub-reddit is invalid, dear dummy.")
                return
        block = await ctx.send(f"Fetching {keywords}...")
        for count in range(1, 5):
            await asyncio.sleep(0.05)
            await block.edit(content=f"Fetching {keywords}...`{str(count)}/5`")
            count += 1
        subreddit = reddit.subreddit(keywords)
        all_subs = []

        top = subreddit.top(limit=50)

        for submission in top:
            all_subs.append(submission)

        random_sub = random.choice(all_subs)

        name = random_sub.title
        url = random_sub.url
        text = random_sub.selftext
        embed = discord.Embed(title=name, color=discord.Color.green(), description=text)
        embed.set_image(url = url)
        embed.set_footer(text=f"Asked by {ctx.message.author.display_name}")
        await block.edit(embed=embed)

问题是它似乎导致错误:

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\admin\PycharmProjects\pythonProject\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:/Users/admin/PycharmProjects/pythonProject/main.py", line 23, in on_command_error
    timeleft = round(error.retry_after, 2);
AttributeError: 'CommandInvokeError' object has no attribute 'retry_after'

这是它引用的代码:

@bot.event
async def on_command_error(ctx, error):
    timeleft = round(error.retry_after, 2);
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f'Wah, spicy. Stop spamming. Try it again after `{timeleft}` seconds')

代码工作得很好,但是,只有当我尝试执行 reddit 命令时,它才开始抛出上述错误。我不知道为什么会这样。

标签: discord.py

解决方案


原来是因为存在 reddit 变量的重复名称。初学者的错误,正如我这样的初学者所期望的。问题已经解决了。


推荐阅读