Skip to content

Commit

Permalink
Remove redundant ctx or user_data fields (#239)
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev committed May 3, 2024
1 parent 186897a commit 5fd9459
Show file tree
Hide file tree
Showing 19 changed files with 223 additions and 295 deletions.
326 changes: 156 additions & 170 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion examples/basic_structure/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ 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: |_framework, event| {
Box::pin(async move {
println!(
"Got an event in event handler: {:?}",
Expand Down
11 changes: 5 additions & 6 deletions examples/event_handler/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ async fn main() {
})
})
.options(poise::FrameworkOptions {
event_handler: |ctx, event, framework, data| {
Box::pin(event_handler(ctx, event, framework, data))
},
event_handler: |framework, event| Box::pin(event_handler(framework, event)),
..Default::default()
})
.build();
Expand All @@ -46,11 +44,12 @@ async fn main() {
}

async fn event_handler(
ctx: &serenity::Context,
framework: poise::FrameworkContext<'_, Data, Error>,
event: &serenity::FullEvent,
_framework: poise::FrameworkContext<'_, Data, Error>,
data: &Data,
) -> Result<(), Error> {
let data = framework.user_data;
let ctx = framework.serenity_context;

match event {
serenity::FullEvent::Ready { data_about_bot, .. } => {
println!("Logged in as {}", data_about_bot.user.name);
Expand Down
2 changes: 1 addition & 1 deletion examples/feature_showcase/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async fn main() {
],
prefix_options: poise::PrefixFrameworkOptions {
prefix: Some("~".into()),
non_command_message: Some(|_, _, msg| {
non_command_message: Some(|_, msg| {
Box::pin(async move {
println!("non command message!: {}", msg.content);
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions examples/manual_dispatch/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ impl serenity::EventHandler for Handler {
// FrameworkContext contains all data that poise::Framework usually manages
let shard_manager = (*self.shard_manager.lock().unwrap()).clone().unwrap();
let framework_data = poise::FrameworkContext {
bot_id: serenity::UserId::new(846453852164587620),
serenity_context: &ctx,
options: &self.options,
user_data: &(),
shard_manager: &shard_manager,
};

let event = serenity::FullEvent::Message { new_message };
poise::dispatch_event(framework_data, &ctx, event).await;
poise::dispatch_event(framework_data, event).await;
}

// For slash commands or edit tracking to work, forward interaction_create and message_update
Expand Down
2 changes: 1 addition & 1 deletion macros/src/command/prefix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub fn generate_prefix_action(inv: &Invocation) -> Result<proc_macro2::TokenStre
Ok(quote::quote! {
|ctx| Box::pin(async move {
let ( #( #param_idents, )* .. ) = ::poise::parse_prefix_args!(
ctx.serenity_context, ctx.msg, ctx.args, 0 =>
ctx.serenity_context(), ctx.msg, ctx.args, 0 =>
#( #param_specs, )*
#wildcard_arg
).await.map_err(|(error, input)| poise::FrameworkError::new_argument_parse(
Expand Down
2 changes: 1 addition & 1 deletion macros/src/command/slash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ pub fn generate_slash_action(inv: &Invocation) -> Result<proc_macro2::TokenStrea
#[allow(clippy::needless_question_mark)]

let ( #( #param_identifiers, )* ) = ::poise::parse_slash_args!(
ctx.serenity_context, ctx.interaction, ctx.args =>
ctx.serenity_context(), ctx.interaction, ctx.args =>
#( (#param_names: #param_types), )*
).await.map_err(|error| error.to_framework_error(ctx))?;

Expand Down
2 changes: 1 addition & 1 deletion src/dispatch/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ async fn check_permissions_and_cooldown_single<'a, U, E>(
}

// Before running any pre-command checks, make sure the bot has the permissions it needs
match missing_permissions(ctx, ctx.framework().bot_id, cmd.required_bot_permissions).await {
match missing_permissions(ctx, ctx.framework().bot_id(), cmd.required_bot_permissions).await {
Some(missing_permissions) if missing_permissions.is_empty() => {}
Some(missing_permissions) => {
return Err(crate::FrameworkError::MissingBotPermissions {
Expand Down
29 changes: 16 additions & 13 deletions src/dispatch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ pub use slash::*;

use crate::serenity_prelude as serenity;

// TODO: integrate serenity::Context in here? Every place where FrameworkContext is passed is also
// passed serenity::Context
/// A view into data stored by [`crate::Framework`]
pub struct FrameworkContext<'a, U, E> {
/// User ID of this bot
/// Serenity's context
pub serenity_context: &'a serenity::Context,
/// User ID of this bot, available through serenity_context if cache is enabled.
#[cfg(not(feature = "cache"))]
pub bot_id: serenity::UserId,
/// Framework configuration
pub options: &'a crate::FrameworkOptions<U, E>,
Expand All @@ -32,6 +33,16 @@ impl<U, E> Clone for FrameworkContext<'_, U, E> {
}
}
impl<'a, U, E> FrameworkContext<'a, U, E> {
/// Returns the user ID of the bot.
pub fn bot_id(&self) -> serenity::UserId {
#[cfg(feature = "cache")]
let bot_id = self.serenity_context.cache.current_user().id;
#[cfg(not(feature = "cache"))]
let bot_id = self.bot_id;

bot_id
}

/// Returns the stored framework options, including commands.
///
/// This function exists for API compatiblity with [`crate::Framework`]. On this type, you can
Expand Down Expand Up @@ -61,7 +72,6 @@ impl<'a, U, E> FrameworkContext<'a, U, E> {
/// Central event handling function of this library
pub async fn dispatch_event<U: Send + Sync, E>(
framework: crate::FrameworkContext<'_, U, E>,
ctx: &serenity::Context,
event: serenity::FullEvent,
) {
match &event {
Expand All @@ -71,7 +81,6 @@ pub async fn dispatch_event<U: Send + Sync, E>(
let trigger = crate::MessageDispatchTrigger::MessageCreate;
if let Err(error) = prefix::dispatch_message(
framework,
ctx,
new_message,
trigger,
&invocation_data,
Expand Down Expand Up @@ -101,7 +110,6 @@ pub async fn dispatch_event<U: Send + Sync, E>(
};
if let Err(error) = prefix::dispatch_message(
framework,
ctx,
&msg,
trigger,
&invocation_data,
Expand All @@ -123,7 +131,7 @@ pub async fn dispatch_event<U: Send + Sync, E>(
.unwrap()
.process_message_delete(*deleted_message_id);
if let Some(bot_response) = bot_response {
if let Err(e) = bot_response.delete(ctx).await {
if let Err(e) = bot_response.delete(framework.serenity_context).await {
tracing::warn!("failed to delete bot response: {}", e);
}
}
Expand All @@ -136,7 +144,6 @@ pub async fn dispatch_event<U: Send + Sync, E>(
let mut parent_commands = Vec::new();
if let Err(error) = slash::dispatch_interaction(
framework,
ctx,
interaction,
&std::sync::atomic::AtomicBool::new(false),
&invocation_data,
Expand All @@ -155,7 +162,6 @@ pub async fn dispatch_event<U: Send + Sync, E>(
let mut parent_commands = Vec::new();
if let Err(error) = slash::dispatch_autocomplete(
framework,
ctx,
interaction,
&std::sync::atomic::AtomicBool::new(false),
&invocation_data,
Expand All @@ -172,12 +178,9 @@ pub async fn dispatch_event<U: Send + Sync, E>(

// Do this after the framework's Ready handling, so that get_user_data() doesnt
// potentially block infinitely
if let Err(error) =
(framework.options.event_handler)(ctx, &event, framework, framework.user_data).await
{
if let Err(error) = (framework.options.event_handler)(framework, &event).await {
let error = crate::FrameworkError::EventHandler {
error,
ctx,
event: &event,
framework,
};
Expand Down
43 changes: 16 additions & 27 deletions src/dispatch/prefix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,13 @@ use crate::serenity_prelude as serenity;
/// Returns tuple of stripped prefix and rest of the message, if any prefix matches
async fn strip_prefix<'a, U, E>(
framework: crate::FrameworkContext<'a, U, E>,
ctx: &'a serenity::Context,
msg: &'a serenity::Message,
) -> Option<(&'a str, &'a str)> {
let partial_ctx = crate::PartialContext {
guild_id: msg.guild_id,
channel_id: msg.channel_id,
author: &msg.author,
serenity_context: ctx,
framework,
data: framework.user_data,
__non_exhaustive: (),
};

Expand Down Expand Up @@ -68,7 +65,7 @@ async fn strip_prefix<'a, U, E>(
}

if let Some(dynamic_prefix) = framework.options.prefix_options.stripped_dynamic_prefix {
match dynamic_prefix(ctx, msg, framework.user_data).await {
match dynamic_prefix(framework.serenity_context, msg, framework.user_data).await {
Ok(result) => {
if let Some((prefix, content)) = result {
return Some((prefix, content));
Expand All @@ -91,7 +88,7 @@ async fn strip_prefix<'a, U, E>(
msg.content
.strip_prefix("<@")?
.trim_start_matches('!')
.strip_prefix(&framework.bot_id.to_string())?
.strip_prefix(&framework.bot_id().to_string())?
.strip_prefix('>')
})() {
let mention_prefix = &msg.content[..(msg.content.len() - stripped_content.len())];
Expand Down Expand Up @@ -186,21 +183,13 @@ pub fn find_command<'a, U, E>(
/// Manually dispatches a message with the prefix framework
pub async fn dispatch_message<'a, U: Send + Sync, E>(
framework: crate::FrameworkContext<'a, U, E>,
ctx: &'a serenity::Context,
msg: &'a serenity::Message,
trigger: crate::MessageDispatchTrigger,
invocation_data: &'a tokio::sync::Mutex<Box<dyn std::any::Any + Send + Sync>>,
parent_commands: &'a mut Vec<&'a crate::Command<U, E>>,
) -> Result<(), crate::FrameworkError<'a, U, E>> {
if let Some(ctx) = parse_invocation(
framework,
ctx,
msg,
trigger,
invocation_data,
parent_commands,
)
.await?
if let Some(ctx) =
parse_invocation(framework, msg, trigger, invocation_data, parent_commands).await?
{
crate::catch_unwind_maybe(run_invocation(ctx))
.await
Expand All @@ -209,14 +198,13 @@ pub async fn dispatch_message<'a, U: Send + Sync, E>(
ctx: ctx.into(),
})??;
} else if let Some(non_command_message) = framework.options.prefix_options.non_command_message {
non_command_message(&framework, ctx, msg)
.await
.map_err(|e| crate::FrameworkError::NonCommandMessage {
non_command_message(&framework, msg).await.map_err(|e| {
crate::FrameworkError::NonCommandMessage {
error: e,
ctx,
framework,
msg,
})?;
}
})?;
}
Ok(())
}
Expand All @@ -229,7 +217,6 @@ pub async fn dispatch_message<'a, U: Send + Sync, E>(
/// fully parsed.
pub async fn parse_invocation<'a, U: Send + Sync, E>(
framework: crate::FrameworkContext<'a, U, E>,
ctx: &'a serenity::Context,
msg: &'a serenity::Message,
trigger: crate::MessageDispatchTrigger,
invocation_data: &'a tokio::sync::Mutex<Box<dyn std::any::Any + Send + Sync>>,
Expand All @@ -241,7 +228,8 @@ pub async fn parse_invocation<'a, U: Send + Sync, E>(
}

// Check if we're allowed to execute our own messages
if framework.bot_id == msg.author.id && !framework.options.prefix_options.execute_self_messages
if framework.bot_id() == msg.author.id
&& !framework.options.prefix_options.execute_self_messages
{
return Ok(None);
}
Expand All @@ -254,7 +242,7 @@ pub async fn parse_invocation<'a, U: Send + Sync, E>(
}

// Strip prefix, trim whitespace between prefix and rest, split rest into command name and args
let (prefix, msg_content) = match strip_prefix(framework, ctx, msg).await {
let (prefix, msg_content) = match strip_prefix(framework, msg).await {
Some(x) => x,
None => return Ok(None),
};
Expand All @@ -267,7 +255,6 @@ pub async fn parse_invocation<'a, U: Send + Sync, E>(
parent_commands,
)
.ok_or(crate::FrameworkError::UnknownCommand {
ctx,
msg,
prefix,
msg_content,
Expand All @@ -283,13 +270,11 @@ pub async fn parse_invocation<'a, U: Send + Sync, E>(
};

Ok(Some(crate::PrefixContext {
serenity_context: ctx,
msg,
prefix,
invoked_command_name,
args,
framework,
data: framework.user_data,
parent_commands,
command,
invocation_data,
Expand Down Expand Up @@ -326,7 +311,11 @@ pub async fn run_invocation<U, E>(

// Typing is broadcasted as long as this object is alive
let _typing_broadcaster = if ctx.command.broadcast_typing {
Some(ctx.msg.channel_id.start_typing(&ctx.serenity_context.http))
Some(
ctx.msg
.channel_id
.start_typing(&ctx.framework.serenity_context.http),
)
} else {
None
};
Expand Down
Loading

0 comments on commit 5fd9459

Please sign in to comment.