From 0566ff5aeef834877f0c0dd568b8472f561b7489 Mon Sep 17 00:00:00 2001 From: soruh Date: Mon, 4 Dec 2023 13:16:53 +0100 Subject: [PATCH] remove bloat --- src/main.rs | 126 +--------------------------------------------------- 1 file changed, 1 insertion(+), 125 deletions(-) diff --git a/src/main.rs b/src/main.rs index daa74df..3c1369f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,7 +9,6 @@ //! ``` use std::collections::{HashMap, HashSet}; use std::env; -use std::fmt::Write; use std::sync::Arc; use rand::seq::SliceRandom; @@ -23,26 +22,12 @@ use serenity::framework::standard::{ help_commands, Args, BucketBuilder, CommandGroup, CommandResult, Configuration, DispatchError, HelpOptions, StandardFramework, }; -use serenity::gateway::ShardManager; use serenity::http::Http; use serenity::model::channel::Message; use serenity::model::gateway::{GatewayIntents, Ready}; use serenity::model::id::UserId; use serenity::prelude::*; -// A container type is created for inserting into the Client's `data`, which allows for data to be -// accessible across all events and framework commands, or anywhere else that has a copy of the -// `data` Arc. -struct ShardManagerContainer; -impl TypeMapKey for ShardManagerContainer { - type Value = Arc; -} - -struct CommandCounter; -impl TypeMapKey for CommandCounter { - type Value = HashMap; -} - struct HttpCache(Arc, Http); impl HttpCache { fn as_ref(&self) -> (&Arc, &Http) { @@ -74,7 +59,7 @@ impl EventHandler for Handler { } #[group] -#[commands(commands, champions)] +#[commands(champions)] struct General; // The framework provides two built-in help commands for you to use. But you can also make your own @@ -116,43 +101,6 @@ async fn my_help( Ok(()) } -#[hook] -async fn before(ctx: &Context, msg: &Message, command_name: &str) -> bool { - println!( - "Got command '{}' by user '{}'", - command_name, msg.author.name - ); - - // Increment the number of times this command has been run once. If the command's name does not - // exist in the counter, add a default value of 0. - let mut data = ctx.data.write().await; - let counter = data - .get_mut::() - .expect("Expected CommandCounter in TypeMap."); - let entry = counter.entry(command_name.to_string()).or_insert(0); - *entry += 1; - - true // if `before` returns false, command processing doesn't happen. -} - -#[hook] -async fn after(_ctx: &Context, _msg: &Message, command_name: &str, command_result: CommandResult) { - match command_result { - Ok(()) => println!("Processed command '{command_name}'"), - Err(why) => println!("Command '{command_name}' returned error {why:?}"), - } -} - -#[hook] -async fn unknown_command(_ctx: &Context, _msg: &Message, unknown_command_name: &str) { - println!("Could not find command named '{unknown_command_name}'"); -} - -#[hook] -async fn normal_message(_ctx: &Context, msg: &Message) { - println!("Message is not a command '{}'", msg.content); -} - #[hook] async fn delay_action(ctx: &Context, msg: &Message) { // You may want to handle a Discord rate limit if this fails. @@ -175,32 +123,6 @@ async fn dispatch_error(ctx: &Context, msg: &Message, error: DispatchError, _com } } -// You can construct a hook without the use of a macro, too. -// This requires some boilerplate though and the following additional import. -use serenity::futures::future::BoxFuture; -use serenity::FutureExt; -fn _dispatch_error_no_macro<'fut>( - ctx: &'fut mut Context, - msg: &'fut Message, - error: DispatchError, - _command_name: &str, -) -> BoxFuture<'fut, ()> { - async move { - if let DispatchError::Ratelimited(info) = error { - if info.is_first_try { - let _ = msg - .channel_id - .say( - &ctx.http, - &format!("Try this again in {} seconds.", info.as_secs()), - ) - .await; - } - }; - } - .boxed() -} - #[tokio::main] async fn main() { let _ = dotenv::from_filename(".env"); @@ -235,24 +157,6 @@ async fn main() { }; let framework = StandardFramework::new() - // Set a function to be called prior to each command execution. This provides the context - // of the command, the message that was received, and the full name of the command that - // will be called. - // - // Avoid using this to determine whether a specific command should be executed. Instead, - // prefer using the `#[check]` macro which gives you this functionality. - // - // **Note**: Async closures are unstable, you may use them in your application if you are - // fine using nightly Rust. If not, we need to provide the function identifiers to the - // hook-functions (before, after, normal, ...). - .before(before) - // Similar to `before`, except will be called directly _after_ command execution. - .after(after) - // Set a function that's called whenever an attempted command-call's command could not be - // found. - .unrecognised_command(unknown_command) - // Set a function that's called whenever a message is not a command. - .normal_message(normal_message) // Set a function that's called whenever a command's execution didn't complete for one // reason or another. For example, when a user has exceeded a rate-limit or a command can // only be performed by the bot owner. @@ -304,44 +208,16 @@ async fn main() { let mut client = Client::builder(&token, intents) .event_handler(Handler) .framework(framework) - .type_map_insert::(HashMap::default()) .type_map_insert::(HttpCache(Arc::new(Cache::new()), Http::new(&token))) .type_map_insert::(champions) .await .expect("Failed to create client"); - { - let mut data = client.data.write().await; - data.insert::(Arc::clone(&client.shard_manager)); - } - if let Err(why) = client.start().await { println!("Client error: {why:?}"); } } -// Commands can be created via the attribute `#[command]` macro. -#[command] -// Options are passed via subsequent attributes. -// Make this command use the "complicated" bucket. -#[bucket = "complicated"] -async fn commands(ctx: &Context, msg: &Message) -> CommandResult { - let mut contents = "Commands used:\n".to_string(); - - let data = ctx.data.read().await; - let counter = data - .get::() - .expect("Expected CommandCounter in TypeMap."); - - for (name, amount) in counter { - writeln!(contents, "- {name}: {amount}")?; - } - - msg.channel_id.say(&ctx.http, &contents).await?; - - Ok(()) -} - // Repeats what the user passed as argument but ensures that user and role mentions are replaced // with a safe textual alternative. // In this example channel mentions are excluded via the `ContentSafeOptions`.