Slashies helps to reduce the boiler plate code needed to create slashcommands for a Discord bot. It is built on top of Serenity. It focuses on providing traits that you can derive using the macros crate for most straightforward use cases, but gives you the escape hatch of implementing these traits yourself if you want to do something more complex.
Make sure to read the Discord documentation on slash commands to understand the general concepts like interactions.
With Slashies, you can create a slash command in four easy steps: ```
// 1. Create a struct representing the arguments for the command and derive/implement the // Command trait
/// Greet a user
struct HelloCommand { /// The user to greet user: UserInput, }
// 2. Implement the ApplicationCommandInteractionHandler trait to define what happens when you // call the command
impl ApplicationCommandInteractionHandler for HelloCommand { async fn invoke( &self, ctx: &Context, command: &ApplicationCommandInteraction, ) -> Result<(), InvocationError> { let nickname = self.user.member.asref().map(|pm| pm.nick.asref()).flatten(); let greeting = if let Some(nick) = nickname { format!("Hello {} aka {}", self.user.user.name, nick) } else { format!("Hello {}", self.user.user.name) }; command .createinteractionresponse(&ctx.http, |response| { response .kind(InteractionResponseType::ChannelMessageWithSource) .interactionresponsedata(|message| message.content(greeting)) }) .await .maperr(|| InvocationError) } }
// 3. Add the command to an enum that implements the Commands trait, representing all the // commands for the bot
enum BotCommands { Hello(HelloCommand), }
// 4. Add the basic code to register the command via a macro and handle interactions struct Handler;
impl EventHandler for Handler { async fn interactioncreate(&self, ctx: Context, interaction: Interaction) { match interaction { Interaction::ApplicationCommand(commandinteraction) => { BotCommands::parse(&ctx, &commandinteraction) .expect("Failed to parse command") .invoke(&ctx, &commandinteraction) .await .expect("Failed to invoke command"); } _ => (), } }
async fn ready(&self, ctx: Context, ready: Ready) {
register_commands!(&ctx, None, [HelloCommand])
.expect("Unable to register commands");
}
}
async fn main() {
let token = std::env::var("DISCORDTOKEN").expect("Expected a token in the environment");
let applicationid = std::env::var("DISCORDUSERID")
.expect("Expected a user id in the environment")
.parse::
if let Err(why) = client.start().await {
println!("Client error: {:?}", why);
}
} ```