Trying to solve errors raised by users trying to look for an image in a restricted server or 18+ server, but can't seem to figure out how to do it properly. I'm using aPraw and 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))
This is the error handler.
@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}")
Whenever the user attempts to fetch from a banned or restricted subreddit, it returns an AttributeError, and when it can't find an image in a public subreddit, it returns and IndexError.
How can I use an errorhandler to resolve these issues?
You can include some except
in your code. For that you have to modify your code a bit:
@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]
= Insert your code with the correct indentation.except
arguments, these are suggested to youIf you have an IndexError
you however have to use the following: