Part 9 - Error Handling#

We’re going to add a command-specific error handler to make sure that if the command fails due to insufficient permissions, we can send a little error message to whoever ran the command.

In mod.py after our purge_messages command, add the following:

1@purge_messages.set_error_handler
2async def on_purge_error(event: lightbulb.CommandErrorEvent) -> bool:
3    exception = event.exception.__cause__ or event.exception
4
5    if isinstance(exception, lightbulb.BotMissingRequiredPermission):
6        await event.context.respond("I do not have permission to delete messages.")
7        return True
8
9    return False
  • Line 1 - Set the decorated function as purge_messages’s error handler

  • Line 2 - The error handler takes one parameter: lightbulb.CommandErrorEvent, and must return a boolean

  • Line 3 - Unwrap the original cause of the error

  • Line 5-6 - If the exception is that the bot does not have permission to delete messages, we let the user know with a small message.

  • Line 7 - We must return True if the error has been handled, this way lightbulb knows not to raise the error

  • Line 9 - If the error hasn’t been handled (it may have been cause by something other than missing permissions), we return False, so lightbulb will raise the error

Read the docs - Error Handling