Reputation: 41
How can I send an embed on a custom exception?
Exception:
class CustomError(commands.CommandError):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def __str__(self):
return self.message
Code where the exception gets called:
if not ctx.voice_client or ctx.voice_client.queue.is_empty():
raise CustomError(
message="Your queue seems to be empty."
)
return True
I want the bot to send an embed with the message as description in the chat.
How would I do that?
Upvotes: 0
Views: 165
Reputation: 1417
This is a valid solution but a ugly one. I would suggest having a helper method to create and send embed and using that to send message whenever you raise an Exception.
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)
For event handlers, ctx.bot
should be replaced by an instance of discord.Client
or discord.Bot
depending on how you are initializing your bot. ctx.send
should be replaced by channel.send
where channel is the TextChannel object where you want to send the embed. You can add both as arguments to __init__.
Example of a helper method. There are multiple methods of doing this.
# Title is optional
async def send_embed(channel, message, title=''):
em = discord.Embed(title=title, description=message)
await channel.send(embed=em)
Example usage:
await send_embed(ctx, "You have an error")
Upvotes: 1