Part 8 - Command Checks#
For this section, we’ll be making a purge
command, which will delete messages in bulk.
You don’t want anyone to be able to use this command, only those who can delete messages themselves,
so we’re gonna need to add some command checks to ensure that!
So, create a new file named mod.py
in the extensions folder.
In it paste the following:
1import hikari
2import lightbulb
3
4mod_plugin = lightbulb.Plugin("Mod")
5
6
7@mod_plugin.command
8@lightbulb.option(
9 "messages", "The number of messages to purge.", type=int, required=True
10)
11@lightbulb.command("purge", "Purge messages.", aliases=["clear"])
12@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
13async def purge_messages(ctx: lightbulb.Context) -> None:
14 num_msgs = ctx.options.messages
15 channel = ctx.channel_id
16
17 # If the command was invoked using the PrefixCommand, it will create a message
18 # before we purge the messages, so we want to delete this message first
19 if isinstance(ctx, lightbulb.PrefixContext):
20 await ctx.event.message.delete()
21
22 msgs = await ctx.bot.rest.fetch_messages(channel).limit(num_msgs)
23 await ctx.bot.rest.delete_messages(channel, msgs)
24
25 await ctx.respond(f"{len(msgs)} messages deleted.", delete_after=5)
26
27
28def load(bot: lightbulb.BotApp) -> None:
29 bot.add_plugin(mod_plugin)
Line 14 - If we don’t use
pass_options=True
in the command decorator (like with theuserinfo
command), we can’t pass the options to the function, but their values can still be accessed fromctx.options
- Line 22 - Fetch the most recent messages in the channel, limiting it to
num_msgs
Line 23 - Delete the messages that we fetched
Now this command works fine, but now everyone can delete messages using the bot.
We only want people with the Manage Messages
permission to do this, so this is where
checks come in.
Just below line 7 (@mod_plugin.command
), add the following:
@lightbulb.add_checks(
lightbulb.has_guild_permissions(hikari.Permissions.MANAGE_MESSAGES),
lightbulb.bot_has_guild_permissions(hikari.Permissions.MANAGE_MESSAGES),
)
This checks if the both the user who ran the command and the bot has the manage messages
permission in the guild.
If the both the user and bot have permission to run the command, it will work. If they don’t, the command will raise CheckFailure.
But raising an error and the command failing isn’t that useful, we want to tell the user what happened.
So, onto error handling!