【发布时间】:2021-06-14 05:49:53
【问题描述】:
尝试解决用户尝试在受限服务器或 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}")
当用户尝试从被禁止或受限的子版块中获取时,它会返回一个 AttributeError,当它在公共子版块中找不到图像时,它会返回 IndexError。
如何使用错误处理程序来解决这些问题?
【问题讨论】:
-
错误处理程序不工作还是什么?
-
这不是让我选择我想要的错误。在 Discord.py 的文档中找不到我确实得到了
Command raised an exception: AttributeError: 'Subreddit' object has no attribute 'over18'和Command raised an exception: IndexError: list index out of range
标签: python python-3.x discord praw