【问题标题】:discord.py - send embed in custom exceptiondiscord.py - 发送嵌入自定义异常
【发布时间】:2021-09-14 10:29:56
【问题描述】:

如何发送嵌入自定义异常?

例外:

class CustomError(commands.CommandError):
    
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

    def __str__(self):
        return self.message

调用异常的代码:

if not ctx.voice_client or ctx.voice_client.queue.is_empty():
    raise CustomError(
        message="Your queue seems to be empty."
    )

return True

我希望机器人在聊天中发送嵌入的消息作为描述。

我该怎么做?

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    这是一个有效的解决方案,但一个丑陋的解决方案。我建议有一个帮助方法来创建和发送嵌入,并在您引发异常时使用它来发送消息。

    class CustomError(commands.CommandError):
        
        def __init__(self, message, ctx):
            self.message = message
            super().__init__(self.message)
            # create embed; customize as you like
            em = discord.Embed(title="Error in command", description=message)
            # non-async function cannot use aync functions so use create_task
            ctx.bot.loop.create_task(ctx.send(embed=em))
    
        def __str__(self):
            return self.message
    
    
    # Then inside a command, where ctx is context ie first argument to command(excluding self where relevant)
    # It is not valid in event handlers
    raise CustomError("Hello there", ctx)
        
    

    对于事件处理程序,ctx.bot 应替换为 discord.Clientdiscord.Bot 的实例,具体取决于您初始化机器人的方式。 ctx.send 应替换为 channel.send 其中 channel 是您要发送嵌入的 TextChannel 对象。您可以将两者都作为参数添加到 __init__。

    辅助方法示例。有多种方法可以做到这一点。

    # Title is optional
    async def send_embed(channel, message, title=''):
        em = discord.Embed(title=title, description=message)
        await channel.send(embed=em)
    

    示例用法: await send_embed(ctx, "You have an error")

    【讨论】:

    • 并且使用 .loop.create_task() 是在异常中发送内容的唯一方法?
    • @Alado 这是我所知道的最干净的方法,可以从同步函数中调用异步函数。还有其他诸如 run_in_executor 但它需要创建一个执行器。见docs。可能还有其他我不知道的问题,但这将是一个新问题。
    • 可能存在关于如何在同步函数中运行异步函数的问题。
    • 澄清 create_task 没有被使用,因为它是一个例外。之所以使用它,是因为消息是从 init 方法发送的,并且发送消息(ctx.send)是一个异步函数。通常你会将方法(命令处理程序是异步的)定义为异步并使用await ctx.send()。但是,您不能使 init 异步。因此,解决方法。
    • 是的,我知道。您的选择有效,谢谢:) 有什么方法可以让我在 cmd 行中也看不到错误?
    猜你喜欢
    • 2021-02-05
    • 2020-05-31
    • 2021-02-13
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2021-08-04
    • 1970-01-01
    相关资源
    最近更新 更多