Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement get_replied_msg_author #259

Closed
wants to merge 12 commits into from
44 changes: 44 additions & 0 deletions examples/get_replied_user/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use poise::serenity_prelude as serenity;

struct Data {} // User data, which is stored and accessible in all command invocations
type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, Data, Error>;

/// Displays your or another user's avatar.
#[poise::command(slash_command, prefix_command)]
async fn avatar(
ctx: Context<'_>,
#[description = "Selected user (you can also use message replies)"] user: Option<
serenity::User,
>,
) -> Result<(), Error> {
let u = user.as_ref().unwrap_or(ctx.get_replied_msg_author());

let response = u.face().replace(".webp", ".png");
ctx.say(response).await?;
Ok(())
}

#[tokio::main]
async fn main() {
let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
let intents = serenity::GatewayIntents::non_privileged();

let framework = poise::Framework::builder()
.options(poise::FrameworkOptions {
commands: vec![avatar()],
..Default::default()
})
.setup(|ctx, _ready, framework| {
Box::pin(async move {
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(Data {})
})
})
.build();

let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;
client.unwrap().start().await.unwrap();
}
10 changes: 10 additions & 0 deletions src/structs/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,16 @@ context_methods! {
}
}

/// Return a reference to a replied message author or the context author if there's no replied
/// message
(author self)
(pub fn get_replied_msg_author(self) -> &'a serenity::User) {
match self {
Self::Application(ctx) => &ctx.interaction.user,
Self::Prefix(ctx) => &ctx.msg.referenced_message.as_deref().unwrap_or(ctx.msg).author,
}
}

/// Return a ID that uniquely identifies this command invocation.
#[cfg(any(feature = "chrono", feature = "time"))]
(id self)
Expand Down