使用 Discord Py 处理 IndexError 和 Attribute 错误

Errorhandling IndexError and Attribute error with DiscordPy

试图解决用户试图在受限服务器或 18+ 服务器中查找图像但似乎无法弄清楚如何正确执行此操作时提出的错误。我正在使用 aPraw 和 Discordpy

@bot.command()
async def redditsearch(ctx, sub):
    start_time = time.time()
    listing = []
    subreddit = await reddit.subreddit(sub)
    print(subreddit.subreddit_type)
    if sub.lower() in bannedsubs:
        await ctx.send("Banned subreddit.")
        return
    elif subreddit.over18 == True:
        await ctx.send("No NSFW subreddits.")
        return
    else:
        async for submission in subreddit.hot(limit=100):
            if submission.url.endswith(("jpg", "jpeg", "png", "gifv")) and not submission.spoiler and not submission.over_18:
                listing.append(submission)
            else:
                pass
    
        random.shuffle(listing)
        post = listing[0]
        if submission.link_flair_text == None:
            await ctx.send(f"{post.title}\n{post.url}")
        else:
            await ctx.send(f"[{submission.link_flair_text}] \n{post.title}\n{post.url}")
        end_time = time.time()
        await ctx.send(f"---- Took %s seconds to lookup ----" % (end_time - start_time))

这是错误处理程序。

@redditsearch.error
async def redditsearch_error(ctx, inst):
    if isinstance (inst, IndexError):
        await ctx.send(f"Exception raised. This probably means I failed to find an image.")
    else:
        await ctx.send(f"Exception raised. \n\n{inst}")

每当用户试图从被禁止或受限的 subreddit 中获取时,它 returns 一个 AttributeError,当它在 public subreddit 中找不到图像时,它 returns 和 IndexError.

如何使用错误处理程序来解决这些问题?

您可以在代码中包含一些 except。为此,您必须稍微修改一下代码:

@bot.command()
async def redditsearch(ctx, sub):
    try: # Must be included to use except 
    [Your code]
    except AttributeError: # except 
        await ctx.send(f"Exception raised. This probably means I failed to find an image.")
  • [Your code] = 使用正确的缩进插入代码。
  • 您还可以使用其他 except 参数,这些是推荐给您的

如果您有 IndexError,则必须使用以下内容: