【问题标题】:Errorhandling IndexError and Attribute error with DiscordPyDiscord Py 的错误处理 IndexError 和属性错误
【发布时间】: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


【解决方案1】:

您可以在代码中包含一些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,则必须使用以下内容:

【讨论】:

  • 谢谢!我认为你误解了 indexerror,那是因为 reddit 的事情,而不是 Discord!我只是将它更改为 IndexError 并且它有效。我希望能够通过@redditsearch_error 解决它,但这同样适用。
  • 我猜只是将我的消息编辑为正确的方法。您可以使用(ctx, error) 的错误处理程序,然后继续使用if isinstance(error, commands.YourError):,这对此类错误不起作用。
猜你喜欢
  • 2021-05-28
  • 2010-12-24
  • 2017-07-29
  • 2018-04-29
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
相关资源
最近更新 更多