Skip to content

Commit

Permalink
Overhaul usage of the builder pattern (serenity-rs#2024)
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrasnitski authored and arqunis committed Oct 24, 2023
1 parent fe31763 commit f9cb040
Show file tree
Hide file tree
Showing 75 changed files with 4,203 additions and 4,266 deletions.
4 changes: 3 additions & 1 deletion examples/e03_struct_utilities/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::env;

use serenity::async_trait;
use serenity::builder::CreateMessage;
use serenity::model::channel::Message;
use serenity::model::gateway::Ready;
use serenity::prelude::*;
Expand All @@ -19,7 +20,8 @@ impl EventHandler for Handler {
// In this case, you can direct message a User directly by simply
// calling a method on its instance, with the content of the
// message.
let dm = msg.author.dm(&context, |m| m.content("Hello!")).await;
let builder = CreateMessage::default().content("Hello!");
let dm = msg.author.dm(&context, builder).await;

if let Err(why) = dm {
println!("Error when direct messaging user: {:?}", why);
Expand Down
6 changes: 3 additions & 3 deletions examples/e05_command_framework/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use std::fmt::Write;
use std::sync::Arc;

use serenity::async_trait;
use serenity::builder::EditChannel;
use serenity::client::bridge::gateway::{ShardId, ShardManager};
use serenity::framework::standard::buckets::{LimitedFor, RevertBucket};
use serenity::framework::standard::macros::{check, command, group, help, hook};
Expand Down Expand Up @@ -564,9 +565,8 @@ async fn am_i_admin(ctx: &Context, msg: &Message, _args: Args) -> CommandResult
#[command]
async fn slow_mode(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let say_content = if let Ok(slow_mode_rate_seconds) = args.single::<u64>() {
if let Err(why) =
msg.channel_id.edit(&ctx.http, |c| c.rate_limit_per_user(slow_mode_rate_seconds)).await
{
let builder = EditChannel::default().rate_limit_per_user(slow_mode_rate_seconds);
if let Err(why) = msg.channel_id.edit(&ctx.http, builder).await {
println!("Error setting channel's slow mode rate: {:?}", why);

format!("Failed to set slow mode to `{}` seconds.", slow_mode_rate_seconds)
Expand Down
41 changes: 20 additions & 21 deletions examples/e09_create_message_builder/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::env;

use serenity::async_trait;
use serenity::builder::{CreateEmbed, CreateEmbedFooter, CreateMessage};
use serenity::model::channel::Message;
use serenity::model::gateway::Ready;
use serenity::model::Timestamp;
Expand All @@ -16,27 +17,25 @@ impl EventHandler for Handler {
// using a builder syntax.
// This example will create a message that says "Hello, World!", with an embed that has
// a title, description, an image, three fields, and a footer.
let msg = msg
.channel_id
.send_message(&ctx.http, |m| {
m.content("Hello, World!")
.embed(|e| {
e.title("This is a title")
.description("This is a description")
.image("attachment://ferris_eyes.png")
.fields(vec![
("This is the first field", "This is a field body", true),
("This is the second field", "Both fields are inline", true),
])
.field("This is the third field", "This is not an inline field", false)
.footer(|f| f.text("This is a footer"))
// Add a timestamp for the current time
// This also accepts a rfc3339 Timestamp
.timestamp(Timestamp::now())
})
.add_file("./ferris_eyes.png")
})
.await;
let footer = CreateEmbedFooter::default().text("This is a footer");
let embed = CreateEmbed::default()
.title("This is a title")
.description("This is a description")
.image("attachment://ferris_eyes.png")
.fields(vec![
("This is the first field", "This is a field body", true),
("This is the second field", "Both fields are inline", true),
])
.field("This is the third field", "This is not an inline field", false)
.footer(footer)
// Add a timestamp for the current time
// This also accepts a rfc3339 Timestamp
.timestamp(Timestamp::now());
let builder = CreateMessage::default()
.content("Hello, World!")
.embed(embed)
.add_file("./ferris_eyes.png");
let msg = msg.channel_id.send_message(&ctx.http, builder).await;

if let Err(why) = msg {
println!("Error sending message: {:?}", why);
Expand Down
32 changes: 15 additions & 17 deletions examples/e13_parallel_loops/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::time::Duration;

use chrono::offset::Utc;
use serenity::async_trait;
use serenity::builder::{CreateEmbed, CreateMessage};
use serenity::gateway::ActivityData;
use serenity::model::channel::Message;
use serenity::model::gateway::Ready;
Expand Down Expand Up @@ -79,23 +80,20 @@ async fn log_system_load(ctx: Arc<Context>) {

// We can use ChannelId directly to send a message to a specific channel; in this case, the
// message would be sent to the #testing channel on the discord server.
let message = ChannelId::new(381926291785383946)
.send_message(&ctx, |m| {
m.embed(|e| {
e.title("System Resource Load")
.field("CPU Load Average", &format!("{:.2}%", cpu_load.one * 10.0), false)
.field(
"Memory Usage",
&format!(
"{:.2} MB Free out of {:.2} MB",
mem_use.free as f32 / 1000.0,
mem_use.total as f32 / 1000.0
),
false,
)
})
})
.await;
let embed = CreateEmbed::default()
.title("System Resource Load")
.field("CPU Load Average", &format!("{:.2}%", cpu_load.one * 10.0), false)
.field(
"Memory Usage",
&format!(
"{:.2} MB Free out of {:.2} MB",
mem_use.free as f32 / 1000.0,
mem_use.total as f32 / 1000.0
),
false,
);
let builder = CreateMessage::default().embed(embed);
let message = ChannelId::new(381926291785383946).send_message(&ctx, builder).await;
if let Err(why) = message {
eprintln!("Error sending message: {:?}", why);
};
Expand Down
17 changes: 9 additions & 8 deletions examples/e14_slash_commands/src/commands/attachmentinput.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use serenity::builder::CreateApplicationCommand;
use serenity::builder::{CreateApplicationCommand, CreateApplicationCommandOption};
use serenity::model::prelude::command::CommandOptionType;
use serenity::model::prelude::interaction::application_command::{ResolvedOption, ResolvedValue};

Expand All @@ -13,14 +13,15 @@ pub fn run(options: &[ResolvedOption]) -> String {
}
}

pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("attachmentinput").description("Test command for attachment input").create_option(
|option| {
option
pub fn register() -> CreateApplicationCommand {
CreateApplicationCommand::default()
.name("attachmentinput")
.description("Test command for attachment input")
.add_option(
CreateApplicationCommandOption::default()
.name("attachment")
.description("A file")
.kind(CommandOptionType::Attachment)
.required(true)
},
)
.required(true),
)
}
12 changes: 6 additions & 6 deletions examples/e14_slash_commands/src/commands/id.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use serenity::builder::CreateApplicationCommand;
use serenity::builder::{CreateApplicationCommand, CreateApplicationCommandOption};
use serenity::model::prelude::command::CommandOptionType;
use serenity::model::prelude::interaction::application_command::{ResolvedOption, ResolvedValue};

Expand All @@ -13,12 +13,12 @@ pub fn run(options: &[ResolvedOption]) -> String {
}
}

pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("id").description("Get a user id").create_option(|option| {
option
pub fn register() -> CreateApplicationCommand {
CreateApplicationCommand::default().name("id").description("Get a user id").add_option(
CreateApplicationCommandOption::default()
.name("id")
.description("The user to lookup")
.kind(CommandOptionType::User)
.required(true)
})
.required(true),
)
}
24 changes: 11 additions & 13 deletions examples/e14_slash_commands/src/commands/numberinput.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,26 @@
use serenity::builder;
use serenity::builder::{CreateApplicationCommand, CreateApplicationCommandOption};
use serenity::model::prelude::command::CommandOptionType;

pub fn register(
command: &mut builder::CreateApplicationCommand,
) -> &mut builder::CreateApplicationCommand {
command
pub fn register() -> CreateApplicationCommand {
CreateApplicationCommand::default()
.name("numberinput")
.description("Test command for number input")
.create_option(|option| {
option
.add_option(
CreateApplicationCommandOption::default()
.name("int")
.description("An integer from 5 to 10")
.kind(CommandOptionType::Integer)
.min_int_value(5)
.max_int_value(10)
.required(true)
})
.create_option(|option| {
option
.required(true),
)
.add_option(
CreateApplicationCommandOption::default()
.name("number")
.description("A float from -3.3 to 234.5")
.kind(CommandOptionType::Number)
.min_number_value(-3.3)
.max_number_value(234.5)
.required(true)
})
.required(true),
)
}
4 changes: 2 additions & 2 deletions examples/e14_slash_commands/src/commands/ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ pub fn run(_options: &[ResolvedOption]) -> String {
"Hey, I'm alive!".to_string()
}

pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("ping").description("A ping command")
pub fn register() -> CreateApplicationCommand {
CreateApplicationCommand::default().name("ping").description("A ping command")
}
22 changes: 11 additions & 11 deletions examples/e14_slash_commands/src/commands/welcome.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
use serenity::builder::CreateApplicationCommand;
use serenity::builder::{CreateApplicationCommand, CreateApplicationCommandOption};
use serenity::model::prelude::command::CommandOptionType;

pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command
pub fn register() -> CreateApplicationCommand {
CreateApplicationCommand::default()
.name("welcome")
.name_localized("de", "begrüßen")
.description("Welcome a user")
.description_localized("de", "Einen Nutzer begrüßen")
.create_option(|option| {
option
.add_option(
CreateApplicationCommandOption::default()
.name("user")
.name_localized("de", "nutzer")
.description("The user to welcome")
.description_localized("de", "Der zu begrüßende Nutzer")
.kind(CommandOptionType::User)
.required(true)
})
.create_option(|option| {
option
.required(true),
)
.add_option(
CreateApplicationCommandOption::default()
.name("message")
.name_localized("de", "nachricht")
.description("The message to send")
Expand Down Expand Up @@ -48,6 +48,6 @@ pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicatio
"I hope that you brought a controller to play together!",
"game",
[("de", "Ich hoffe du hast einen Controller zum Spielen mitgebracht!")],
)
})
),
)
}
4 changes: 2 additions & 2 deletions examples/e14_slash_commands/src/commands/wonderful_command.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serenity::builder::CreateApplicationCommand;

pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("wonderful_command").description("An amazing command")
pub fn register() -> CreateApplicationCommand {
CreateApplicationCommand::default().name("wonderful_command").description("An amazing command")
}
49 changes: 27 additions & 22 deletions examples/e14_slash_commands/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ mod commands;
use std::env;

use serenity::async_trait;
use serenity::builder::{
CreateApplicationCommands as CreateCommands,
CreateInteractionResponse,
CreateInteractionResponseData,
};
use serenity::model::application::command::Command;
use serenity::model::application::interaction::{Interaction, InteractionResponseType};
use serenity::model::gateway::Ready;
Expand All @@ -24,14 +29,11 @@ impl EventHandler for Handler {
_ => "not implemented :(".to_string(),
};

if let Err(why) = command
.create_interaction_response(&ctx.http, |response| {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|message| message.content(content))
})
.await
{
let data = CreateInteractionResponseData::default().content(content);
let builder = CreateInteractionResponse::default()
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(data);
if let Err(why) = command.create_interaction_response(&ctx.http, builder).await {
println!("Cannot respond to slash command: {}", why);
}
}
Expand All @@ -47,21 +49,24 @@ impl EventHandler for Handler {
.expect("GUILD_ID must be an integer"),
);

let commands = GuildId::set_application_commands(&guild_id, &ctx.http, |commands| {
commands
.create_application_command(|command| commands::ping::register(command))
.create_application_command(|command| commands::id::register(command))
.create_application_command(|command| commands::welcome::register(command))
.create_application_command(|command| commands::numberinput::register(command))
.create_application_command(|command| commands::attachmentinput::register(command))
})
.await;
let commands = guild_id
.set_application_commands(
&ctx.http,
CreateCommands::default()
.add_application_command(commands::ping::register())
.add_application_command(commands::id::register())
.add_application_command(commands::welcome::register())
.add_application_command(commands::numberinput::register())
.add_application_command(commands::attachmentinput::register()),
)
.await;

println!("I now have the following guild slash commands: {:#?}", commands);

let guild_command = Command::create_global_application_command(&ctx.http, |command| {
commands::wonderful_command::register(command)
})
let guild_command = Command::create_global_application_command(
&ctx.http,
commands::wonderful_command::register(),
)
.await;

println!("I created the following global slash command: {:#?}", guild_command);
Expand All @@ -81,8 +86,8 @@ async fn main() {

// Finally, start a single shard, and start listening to events.
//
// Shards will automatically attempt to reconnect, and will perform
// exponential backoff until it reconnects.
// Shards will automatically attempt to reconnect, and will perform exponential backoff until
// it reconnects.
if let Err(why) = client.start().await {
println!("Client error: {:?}", why);
}
Expand Down
Loading

0 comments on commit f9cb040

Please sign in to comment.