Skip to content

Commit

Permalink
Swap to serenity 0.12.0-rc2
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev committed Nov 24, 2023
1 parent c33ebdc commit 42f36dd
Show file tree
Hide file tree
Showing 48 changed files with 1,346 additions and 1,862 deletions.
848 changes: 524 additions & 324 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 2 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ repository = "https://github.com/serenity-rs/poise/"
tokio = { version = "1.25.1", default-features = false } # for async in general
futures-core = { version = "0.3.13", default-features = false } # for async in general
futures-util = { version = "0.3.13", default-features = false } # for async in general
once_cell = { version = "1.7.2", default-features = false, features = ["std"] } # to store and set user data
poise_macros = { path = "macros", version = "0.5.7" } # remember to update the version on changes!
async-trait = { version = "0.1.48", default-features = false } # various traits
regex = { version = "1.6.0", default-features = false, features = ["std"] } # prefix
Expand All @@ -22,8 +21,8 @@ parking_lot = "0.12.1"

[dependencies.serenity]
default-features = false
features = ["builder", "client", "gateway", "model", "utils", "collector"]
version = "0.11.5"
features = ["builder", "client", "gateway", "model", "utils", "collector", "framework"]
version = "0.12.0-rc2"

[dev-dependencies]
# For the examples
Expand All @@ -39,7 +38,6 @@ rand = "0.8.5"
default = ["serenity/rustls_backend", "cache", "chrono", "handle_panics"]
chrono = ["serenity/chrono"]
cache = ["serenity/cache"]
time = ["serenity/time"]
# No-op feature because serenity/collector is now enabled by default
collector = []
# Enables support for handling panics inside commands via FrameworkError::CommandPanic.
Expand Down
14 changes: 9 additions & 5 deletions examples/advanced_cooldowns/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ async fn dynamic_cooldowns(ctx: Context<'_>) -> Result<(), Error> {

// You can change the cooldown duration depending on the message author, for example
let mut cooldown_durations = poise::CooldownConfig::default();
if ctx.author().id.0 == 472029906943868929 {
if ctx.author().id == 472029906943868929 {
cooldown_durations.user = Some(std::time::Duration::from_secs(10));
}

Expand All @@ -29,6 +29,7 @@ async fn dynamic_cooldowns(ctx: Context<'_>) -> Result<(), Error> {

#[tokio::main]
async fn main() {
let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
let framework = poise::Framework::builder()
.options(poise::FrameworkOptions {
commands: vec![dynamic_cooldowns()],
Expand All @@ -37,14 +38,17 @@ async fn main() {
manual_cooldowns: true,
..Default::default()
})
.token(std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN"))
.intents(serenity::GatewayIntents::non_privileged())
.setup(|ctx, _ready, framework| {
Box::pin(async move {
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(Data {})
})
});
})
.build();

let client = serenity::Client::builder(token, serenity::GatewayIntents::non_privileged())
.framework(framework)
.await;

framework.run().await.unwrap();
client.unwrap().start().await.unwrap();
}
42 changes: 27 additions & 15 deletions examples/basic_structure/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
mod commands;

use poise::serenity_prelude as serenity;
use std::{collections::HashMap, env::var, sync::Mutex, time::Duration};
use std::{
collections::HashMap,
env::var,
sync::{Arc, Mutex},
time::Duration,
};

// Types used by all command functions
type Error = Box<dyn std::error::Error + Send + Sync>;
Expand Down Expand Up @@ -41,7 +46,9 @@ async fn main() {
commands: vec![commands::help(), commands::vote(), commands::getvotes()],
prefix_options: poise::PrefixFrameworkOptions {
prefix: Some("~".into()),
edit_tracker: Some(poise::EditTracker::for_timespan(Duration::from_secs(3600))),
edit_tracker: Some(Arc::new(poise::EditTracker::for_timespan(
Duration::from_secs(3600),
))),
additional_prefixes: vec![
poise::Prefix::Literal("hey bot"),
poise::Prefix::Literal("hey bot,"),
Expand Down Expand Up @@ -74,20 +81,19 @@ async fn main() {
// Enforce command checks even for owners (enforced by default)
// Set to true to bypass checks, which is useful for testing
skip_checks_for_owners: false,
event_handler: |_ctx, event, _framework, _data| {
event_handler: |event, _framework, _data| {
Box::pin(async move {
println!("Got an event in event handler: {:?}", event.name());
println!(
"Got an event in event handler: {:?}",
event.snake_case_name()
);
Ok(())
})
},
..Default::default()
};

poise::Framework::builder()
.token(
var("DISCORD_TOKEN")
.expect("Missing `DISCORD_TOKEN` env var, see README for more information."),
)
let framework = poise::Framework::builder()
.setup(move |ctx, _ready, framework| {
Box::pin(async move {
println!("Logged in as {}", _ready.user.name);
Expand All @@ -98,10 +104,16 @@ async fn main() {
})
})
.options(options)
.intents(
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT,
)
.run()
.await
.unwrap();
.build();

let token = var("DISCORD_TOKEN")
.expect("Missing `DISCORD_TOKEN` env var, see README for more information.");
let intents =
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;

let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;

client.unwrap().start().await.unwrap()
}
42 changes: 19 additions & 23 deletions examples/event_handler/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::env::var;
use std::sync::atomic::{AtomicU32, Ordering};

use poise::serenity_prelude as serenity;
use poise::Event;

// Types used by all command functions
type Error = Box<dyn std::error::Error + Send + Sync>;
Expand All @@ -18,45 +17,42 @@ pub struct Data {
async fn main() {
env_logger::init();

let options = poise::FrameworkOptions {
event_handler: |_ctx, event, _framework, _data| {
Box::pin(event_handler(_ctx, event, _framework, _data))
},
..Default::default()
};
let token = var("DISCORD_TOKEN")
.expect("Missing `DISCORD_TOKEN` env var, see README for more information.");
let intents =
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;

poise::Framework::builder()
.token(
var("DISCORD_TOKEN")
.expect("Missing `DISCORD_TOKEN` env var, see README for more information."),
)
let framework = poise::Framework::builder()
.setup(move |_ctx, _ready, _framework| {
Box::pin(async move {
Ok(Data {
poise_mentions: AtomicU32::new(0),
})
})
})
.options(options)
.intents(
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT,
)
.run()
.await
.unwrap();
.options(poise::FrameworkOptions {
event_handler: |event, framework, data| Box::pin(event_handler(event, framework, data)),
..Default::default()
})
.build();

let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;

client.unwrap().start().await.unwrap();
}

async fn event_handler(
ctx: &serenity::Context,
event: &Event<'_>,
event: &serenity::FullEvent,
_framework: poise::FrameworkContext<'_, Data, Error>,
data: &Data,
) -> Result<(), Error> {
match event {
Event::Ready { data_about_bot } => {
serenity::FullEvent::Ready { data_about_bot, .. } => {
println!("Logged in as {}", data_about_bot.user.name);
}
Event::Message { new_message } => {
serenity::FullEvent::Message { ctx, new_message } => {
if new_message.content.to_lowercase().contains("poise") {
let mentions = data.poise_mentions.load(Ordering::SeqCst) + 1;
data.poise_mentions.store(mentions, Ordering::SeqCst);
Expand Down
2 changes: 1 addition & 1 deletion examples/feature_showcase/attachment_parameter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub async fn totalsize(
ctx: Context<'_>,
#[description = "File to rename"] files: Vec<serenity::Attachment>,
) -> Result<(), Error> {
let total = files.iter().map(|f| f.size).sum::<u64>();
let total = files.iter().map(|f| f.size as u64).sum::<u64>();

ctx.say(format!(
"Total file size: `{}B`. Average size: `{}B`",
Expand Down
13 changes: 8 additions & 5 deletions examples/feature_showcase/autocomplete.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use crate::{Context, Error};
use futures::{Stream, StreamExt};
use std::fmt::Write as _;

use poise::serenity_prelude as serenity;

use crate::{Context, Error};

// Poise supports autocomplete on slash command parameters. You need to provide an autocomplete
// function, which will be called on demand when the user is typing a command.
//
Expand All @@ -12,15 +15,15 @@ use std::fmt::Write as _;
// IntoIterator like Vec<T> and [T; N].
//
// The returned collection type must be a &str/String (or number, if you're implementing
// autocomplete on a number type). Wrap the type in poise::AutocompleteChoice to set a custom label
// autocomplete on a number type). Wrap the type in serenity::AutocompleteChoice to set a custom label
// for each choice which will be displayed in the Discord UI.
//
// Example function return types (assuming non-number parameter -> autocomplete choices are string):
// - `-> impl Stream<String>`
// - `-> Vec<String>`
// - `-> impl Iterator<String>`
// - `-> impl Iterator<&str>`
// - `-> impl Iterator<poise::AutocompleteChoice<&str>>`
// - `-> impl Iterator<serenity::AutocompleteChoice>

async fn autocomplete_name<'a>(
_ctx: Context<'_>,
Expand All @@ -34,10 +37,10 @@ async fn autocomplete_name<'a>(
async fn autocomplete_number(
_ctx: Context<'_>,
_partial: &str,
) -> impl Iterator<Item = poise::AutocompleteChoice<u32>> {
) -> impl Iterator<Item = serenity::AutocompleteChoice> {
// Dummy choices
[1_u32, 2, 3, 4, 5].iter().map(|&n| {
poise::AutocompleteChoice::new_with_value(
serenity::AutocompleteChoice::new(
format!("{n} (why did discord even give autocomplete choices separate labels)"),
n,
)
Expand Down
7 changes: 1 addition & 6 deletions examples/feature_showcase/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,7 @@ use poise::serenity_prelude as serenity;

#[poise::command(prefix_command, owners_only, hide_in_help)]
pub async fn shutdown(ctx: Context<'_>) -> Result<(), Error> {
ctx.framework()
.shard_manager()
.lock()
.await
.shutdown_all()
.await;
ctx.framework().shard_manager().shutdown_all().await;
Ok(())
}

Expand Down
28 changes: 13 additions & 15 deletions examples/feature_showcase/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,11 @@ pub async fn boop(ctx: Context<'_>) -> Result<(), Error> {
let uuid_boop = ctx.id();

let reply = {
let mut components = serenity::CreateComponents::default();
components.create_action_row(|ar| {
ar.create_button(|b| {
b.style(serenity::ButtonStyle::Primary)
.label("Boop me!")
.custom_id(uuid_boop)
})
});
let components = vec![serenity::CreateActionRow::Buttons(vec![
serenity::CreateButton::new(format!("{uuid_boop}"))
.style(serenity::ButtonStyle::Primary)
.label("Boop me!"),
])];

CreateReply::default()
.content("I want some boops!")
Expand All @@ -24,7 +21,7 @@ pub async fn boop(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(reply).await?;

let mut boop_count = 0;
while let Some(mci) = serenity::CollectComponentInteraction::new(ctx)
while let Some(mci) = serenity::ComponentInteractionCollector::new(ctx)
.author_id(ctx.author().id)
.channel_id(ctx.channel_id())
.timeout(std::time::Duration::from_secs(120))
Expand All @@ -34,13 +31,14 @@ pub async fn boop(ctx: Context<'_>) -> Result<(), Error> {
boop_count += 1;

let mut msg = mci.message.clone();
msg.edit(ctx, |m| m.content(format!("Boop count: {}", boop_count)))
.await?;

mci.create_interaction_response(ctx, |ir| {
ir.kind(serenity::InteractionResponseType::DeferredUpdateMessage)
})
msg.edit(
ctx,
serenity::EditMessage::new().content(format!("Boop count: {boop_count}")),
)
.await?;

mci.create_response(ctx, serenity::CreateInteractionResponse::Acknowledge)
.await?;
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/feature_showcase/localization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,6 @@ pub async fn welcome(
let message = message
.localized_name(ctx.locale().unwrap_or(""))
.unwrap_or_else(|| message.name());
ctx.say(format!("<@{}> {}", user.id.0, message)).await?;
ctx.say(format!("<@{}> {}", user.id, message)).await?;
Ok(())
}
17 changes: 11 additions & 6 deletions examples/feature_showcase/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,16 +91,21 @@ async fn main() {
},
..Default::default()
})
.token(std::env::var("DISCORD_TOKEN").unwrap())
.intents(
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT,
)
.setup(move |ctx, _ready, framework| {
Box::pin(async move {
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(Data {})
})
});
})
.build();

let token = std::env::var("DISCORD_TOKEN").unwrap();
let intents =
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;

let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;

framework.run().await.unwrap();
client.unwrap().start().await.unwrap()
}
Loading

0 comments on commit 42f36dd

Please sign in to comment.