错误处理DiscordPy的IndexError和Attribute错误



试图解决用户在受限服务器或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. nn{inst}")

每当用户试图从禁止或限制的子reddit中提取时,它都会返回AttributeError,当在公共子reddit上找不到图像时,它会返回和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,则必须使用以下内容:

  • discord.HTTPException-检索消息时失败

相关内容

最新更新