【问题标题】:Trouble with handling exceptions for repeated errors (python)处理重复错误异常的问题(python)
【发布时间】:2020-12-11 12:59:16
【问题描述】:

我有一个 Discord 机器人,它通过在随机频道中回答来响应消息。有时它会随机选择一个它没有权限发送消息的频道,并引发错误。

这是我处理此错误的方式:

try:
    if message.content == "!xd":
        guild = client.guilds[0]
        random_xd = random.choice(random_list)
        await random.choice(guild.text_channels).send(random_xd)
except discord.errors.Forbidden:
    print("\nsomething went wrong\n")
    if message.content == "!xd":
        guild = client.guilds[0]
        random_xd = random.choice(random_list)
        await random.choice(guild.text_channels).send(random_xd)

有时,机器人会多次向它没有权限的频道发送消息。如何让它运行这段代码,直到它最终发送一条消息?

【问题讨论】:

  • 我无法理解你的问题,除了块效果好吗?
  • 它有效,但它只尝试再次发送消息一次。如果机器人尝试将消息发送到它没有权限的频道超过 2 次,则不会发送任何消息并引发错误。 (如果多次随机选择同一个频道则不发消息)

标签: python discord.py try-except


【解决方案1】:

我不能很好地理解你的问题,但我会尽量按照我的理解回答。起初,据我所知,错误处理不适用于try-except,因此您应该使用on_command_error 事件。像这样:

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, discord.errors.Forbidden):
        if message.content == "!xd":
            guild = client.guilds[0]
            random_xd = random.choice(random_list)
            await random.choice(guild.text_channels).send(random_xd)

这一定对你有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2016-06-27
    相关资源
    最近更新 更多