poise 0.6.2

A Discord bot framework for serenity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Just contains Context and `PartialContext` structs

use std::borrow::Cow;

use crate::{serenity_prelude as serenity, CommandInteractionType};

// needed for proc macro
#[doc(hidden)]
pub trait _GetGenerics {
    type U;
    type E;
}
impl<U, E> _GetGenerics for Context<'_, U, E> {
    type U = U;
    type E = E;
}

/// Wrapper around either [`crate::ApplicationContext`] or [`crate::PrefixContext`]
#[derive(Debug)]
pub enum Context<'a, U, E> {
    /// Application command context
    Application(crate::ApplicationContext<'a, U, E>),
    /// Prefix command context
    Prefix(crate::PrefixContext<'a, U, E>),
    // Not non_exhaustive.. adding a whole new category of commands would justify breakage lol
}
impl<U, E> Clone for Context<'_, U, E> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<U, E> Copy for Context<'_, U, E> {}
impl<'a, U, E> From<crate::ApplicationContext<'a, U, E>> for Context<'a, U, E> {
    fn from(x: crate::ApplicationContext<'a, U, E>) -> Self {
        Self::Application(x)
    }
}
impl<'a, U, E> From<crate::PrefixContext<'a, U, E>> for Context<'a, U, E> {
    fn from(x: crate::PrefixContext<'a, U, E>) -> Self {
        Self::Prefix(x)
    }
}
/// Macro to generate Context methods and also PrefixContext and ApplicationContext methods that
/// delegate to Context
macro_rules! context_methods {
    ( $(
        $( #[$($attrs:tt)*] )*
        // pub $(async $($dummy:block)?)? fn $fn_name:ident $()
        // $fn_name:ident ($($sig:tt)*) $body:block
        $($await:ident)? ( $fn_name:ident $self:ident $($arg:ident)* )
        ( $($sig:tt)* ) $body:block
    )* ) => {
        impl<'a, U, E> Context<'a, U, E> { $(
            $( #[$($attrs)*] )*
            $($sig)* $body
        )* }

        impl<'a, U, E> crate::PrefixContext<'a, U, E> { $(
            $( #[$($attrs)*] )*
            $($sig)* {
                $crate::Context::Prefix($self).$fn_name($($arg)*) $(.$await)?
            }
        )* }

        impl<'a, U, E> crate::ApplicationContext<'a, U, E> { $(
            $( #[$($attrs)*] )*
            $($sig)* {
                $crate::Context::Application($self).$fn_name($($arg)*) $(.$await)?
            }
        )* }
    };
}
// Note how you have to surround the function signature in parentheses, and also add a line before
// the signature with the function name, parameter names and maybe `await` token
context_methods! {
    /// Defer the response, giving the bot multiple minutes to respond without the user seeing an
    /// "interaction failed error".
    ///
    /// Also sets the [`crate::ApplicationContext::has_sent_initial_response`] flag so subsequent
    /// responses will be sent in the correct manner.
    ///
    /// No-op if this is an autocomplete context
    ///
    /// This will make the response public; to make it ephemeral, use [`Self::defer_ephemeral()`].
    await (defer self)
    (pub async fn defer(self) -> Result<(), serenity::Error>) {
        if let Self::Application(ctx) = self {
            ctx.defer_response(false).await?;
        }
        Ok(())
    }

    /// See [`Self::defer()`]
    ///
    /// This will make the response ephemeral; to make it public, use [`Self::defer()`].
    await (defer_ephemeral self)
    (pub async fn defer_ephemeral(self) -> Result<(), serenity::Error>) {
        if let Self::Application(ctx) = self {
            ctx.defer_response(true).await?;
        }
        Ok(())
    }

    /// If this is an application command, [`Self::defer()`] is called
    ///
    /// If this is a prefix command, a typing broadcast is started until the return value is
    /// dropped.
    // #[must_use = "The typing broadcast will only persist if you store it"] // currently doesn't work
    await (defer_or_broadcast self)
    (pub async fn defer_or_broadcast(self) -> Result<Option<serenity::Typing>, serenity::Error>) {
        Ok(match self {
            Self::Application(ctx) => {
                ctx.defer_response(false).await?;
                None
            }
            Self::Prefix(ctx) => Some(
                ctx.msg
                    .channel_id
                    .start_typing(&ctx.serenity_context.http),
            ),
        })
    }

    /// Shorthand of [`crate::say_reply`]
    ///
    /// Note: panics when called in an autocomplete context!
    await (say self text)
    (pub async fn say(
        self,
        text: impl Into<String>,
    ) -> Result<crate::ReplyHandle<'a>, serenity::Error>) {
        crate::say_reply(self, text).await
    }

    /// Like [`Self::say`], but formats the message as a reply to the user's command
    /// message.
    ///
    /// Equivalent to `.send(CreateReply::default().content("...").reply(true))`.
    ///
    /// Only has an effect in prefix context, because slash command responses are always
    /// formatted as a reply.
    ///
    /// Note: panics when called in an autocomplete context!
    await (reply self text)
    (pub async fn reply(
        self,
        text: impl Into<String>,
    ) -> Result<crate::ReplyHandle<'a>, serenity::Error>) {
        self.send(crate::CreateReply::default().content(text).reply(true)).await
    }

    /// Shorthand of [`crate::send_reply`]
    ///
    /// Note: panics when called in an autocomplete context!
    await (send self builder)
    (pub async fn send(
        self,
        builder: crate::CreateReply,
    ) -> Result<crate::ReplyHandle<'a>, serenity::Error>) {
        crate::send_reply(self, builder).await
    }

    /// Return the stored [`serenity::Context`] within the underlying context type.
    (serenity_context self)
    (pub fn serenity_context(self) -> &'a serenity::Context) {
        match self {
            Self::Application(ctx) => ctx.serenity_context,
            Self::Prefix(ctx) => ctx.serenity_context,
        }
    }

    /// Create a [`crate::CooldownContext`] based off the underlying context type.
    (cooldown_context self)
    (pub fn cooldown_context(self) -> crate::CooldownContext) {
        crate::CooldownContext {
            user_id: self.author().id,
            channel_id: self.channel_id(),
            guild_id: self.guild_id()
        }
    }

    /// See [`Self::serenity_context`].
    #[deprecated = "poise::Context can now be passed directly into most serenity functions. Otherwise, use `.serenity_context()` now"]
    #[allow(deprecated)]
    (discord self)
    (pub fn discord(self) -> &'a serenity::Context) {
        self.serenity_context()
    }

    /// Returns a view into data stored by the framework, like configuration
    (framework self)
    (pub fn framework(self) -> crate::FrameworkContext<'a, U, E>) {
        match self {
            Self::Application(ctx) => ctx.framework,
            Self::Prefix(ctx) => ctx.framework,
        }
    }

    /// Return a reference to your custom user data
    (data self)
    (pub fn data(self) -> &'a U) {
        match self {
            Self::Application(ctx) => ctx.data,
            Self::Prefix(ctx) => ctx.data,
        }
    }

    /// Return the channel ID of this context
    (channel_id self)
    (pub fn channel_id(self) -> serenity::ChannelId) {
        match self {
            Self::Application(ctx) => ctx.interaction.channel_id,
            Self::Prefix(ctx) => ctx.msg.channel_id,
        }
    }

    /// Returns the guild ID of this context, if we are inside a guild
    (guild_id self)
    (pub fn guild_id(self) -> Option<serenity::GuildId>) {
        match self {
            Self::Application(ctx) => ctx.interaction.guild_id,
            Self::Prefix(ctx) => ctx.msg.guild_id,
        }
    }

    /// Return the guild channel of this context, if we are inside a guild.
    #[cfg(feature = "cache")]
    await (guild_channel self)
    (pub async fn guild_channel(self) -> Option<serenity::GuildChannel>) {
        if let Ok(serenity::Channel::Guild(guild_channel)) = self.channel_id().to_channel(self.serenity_context()).await {
            return Some(guild_channel);
        }
        None
    }

    // Doesn't fit in with the rest of the functions here but it's convenient
    /// Return the guild of this context, if we are inside a guild.
    #[cfg(feature = "cache")]
    (guild self)
    (pub fn guild(self) -> Option<serenity::GuildRef<'a>>) {
        self.guild_id()?.to_guild_cached(self.serenity_context())
    }

    // Doesn't fit in with the rest of the functions here but it's convenient
    /// Return the partial guild of this context, if we are inside a guild.
    ///
    /// Attempts to find the guild in cache, if cache feature is enabled. Otherwise, falls back to
    /// an HTTP request
    ///
    /// Returns None if in DMs, or if the guild HTTP request fails
    await (partial_guild self)
    (pub async fn partial_guild(self) -> Option<serenity::PartialGuild>) {
        #[cfg(feature = "cache")]
        if let Some(guild) = self.guild() {
            return Some(guild.clone().into());
        }

        self.guild_id()?.to_partial_guild(self.serenity_context()).await.ok()
    }

    // Doesn't fit in with the rest of the functions here but it's convenient
    /// Returns the author of the invoking message or interaction, as a [`serenity::Member`]
    ///
    /// Returns a reference to the inner member object if in an [`crate::ApplicationContext`], otherwise
    /// clones the member out of the cache, or fetches from the discord API.
    ///
    /// Returns None if this command was invoked in DMs, or if the member cache lookup or HTTP
    /// request failed
    ///
    /// Warning: can clone the entire Member instance out of the cache
    await (author_member self)
    (pub async fn author_member(self) -> Option<Cow<'a, serenity::Member>>) {
        if let Self::Application(ctx) = self {
            ctx.interaction.member.as_deref().map(Cow::Borrowed)
        } else {
            self.guild_id()?
                .member(self.serenity_context(), self.author().id)
                .await
                .ok()
                .map(Cow::Owned)
        }
    }

    /// Return the datetime of the invoking message or interaction
    (created_at self)
    (pub fn created_at(self) -> serenity::Timestamp) {
        match self {
            Self::Application(ctx) => ctx.interaction.id.created_at(),
            Self::Prefix(ctx) => ctx.msg.timestamp,
        }
    }

    /// Get the author of the command message or application command.
    (author self)
    (pub fn author(self) -> &'a serenity::User) {
        match self {
            Self::Application(ctx) => &ctx.interaction.user,
            Self::Prefix(ctx) => &ctx.msg.author,
        }
    }

    /// Return a ID that uniquely identifies this command invocation.
    #[cfg(feature = "chrono")]
    (id self)
    (pub fn id(self) -> u64) {
        match self {
            Self::Application(ctx) => ctx.interaction.id.get(),
            Self::Prefix(ctx) => {
                let mut id = ctx.msg.id.get();
                if let Some(edited_timestamp) = ctx.msg.edited_timestamp {
                    // We replace the 42 datetime bits with msg.timestamp_edited so that the ID is
                    // unique even after edits

                    // Set existing datetime bits to zero
                    id &= !0 >> 42;

                    // Calculate Discord's datetime representation (millis since Discord epoch) and
                    // insert those bits into the ID
                    let timestamp_millis = edited_timestamp.timestamp_millis();

                    id |= ((timestamp_millis - 1420070400000) as u64) << 22;
                }
                id
            }
        }
    }

    /// If the invoked command was a subcommand, these are the parent commands, ordered top-level
    /// downwards.
    (parent_commands self)
    (pub fn parent_commands(self) -> &'a [&'a crate::Command<U, E>]) {
        match self {
            Self::Prefix(x) => x.parent_commands,
            Self::Application(x) => x.parent_commands,
        }
    }

    /// Returns a reference to the command.
    (command self)
    (pub fn command(self) -> &'a crate::Command<U, E>) {
        match self {
            Self::Prefix(x) => x.command,
            Self::Application(x) => x.command,
        }
    }

    /// Returns the prefix this command was invoked with, or a slash (`/`), if this is an
    /// application command.
    (prefix self)
    (pub fn prefix(self) -> &'a str) {
        match self {
            Context::Prefix(ctx) => ctx.prefix,
            Context::Application(_) => "/",
        }
    }

    /// Returns the command name that this command was invoked with
    ///
    /// Mainly useful in prefix context, for example to check whether a command alias was used.
    ///
    /// In slash contexts, the given command name will always be returned verbatim, since there are
    /// no slash command aliases and the user has no control over spelling
    (invoked_command_name self)
    (pub fn invoked_command_name(self) -> &'a str) {
        match self {
            Self::Prefix(ctx) => ctx.invoked_command_name,
            Self::Application(ctx) => &ctx.interaction.data.name,
        }
    }

    /// Re-runs this entire command invocation
    ///
    /// Permission checks are omitted; the command code is directly executed as a function. The
    /// result is returned by this function
    await (rerun self)
    (pub async fn rerun(self) -> Result<(), E>) {
        match self.rerun_inner().await {
            Ok(()) => Ok(()),
            Err(crate::FrameworkError::Command { error, ctx: _ }) => Err(error),
            // The only code that runs before the actual user code (which would trigger Command
            // error) is argument parsing. And that's pretty much deterministic. So, because the
            // current command invocation parsed successfully, we can always expect that a command
            // rerun will still parse successfully.
            // Also: can't debug print error because then we need U: Debug + E: Debug bound arghhhhh
            Err(_other) => panic!("unexpected error before entering command"),
        }
    }

    /// Returns the string with which this command was invoked.
    ///
    /// For example `"/slash_command subcommand arg1:value1 arg2:value2"`.
    (invocation_string self)
    (pub fn invocation_string(self) -> String) {
        match self {
            Context::Application(ctx) => {
                let mut string = String::from("/");
                for parent_command in ctx.parent_commands {
                    string += &parent_command.name;
                    string += " ";
                }
                string += &ctx.command.name;
                for arg in ctx.args {
                    #[allow(unused_imports)] // required for simd-json
                    use ::serenity::json::*;
                    use std::fmt::Write as _;

                    string += " ";
                    string += arg.name;
                    string += ":";

                    let _ = match arg.value {
                        // This was verified to match Discord behavior when copy-pasting a not-yet
                        // sent slash command invocation
                        serenity::ResolvedValue::Attachment(_) => write!(string, ""),
                        serenity::ResolvedValue::Boolean(x) => write!(string, "{}", x),
                        serenity::ResolvedValue::Integer(x) => write!(string, "{}", x),
                        serenity::ResolvedValue::Number(x) => write!(string, "{}", x),
                        serenity::ResolvedValue::String(x) => write!(string, "{}", x),
                        serenity::ResolvedValue::Channel(x) => {
                            write!(string, "#{}", x.name.as_deref().unwrap_or(""))
                        }
                        serenity::ResolvedValue::Role(x) => write!(string, "@{}", x.name),
                        serenity::ResolvedValue::User(x, _) => {
                            string.push('@');
                            string.push_str(&x.name);
                            if let Some(discrim) = x.discriminator {
                                let _ = write!(string, "#{discrim:04}");
                            }
                            Ok(())
                        }

                        serenity::ResolvedValue::Unresolved(_)
                        | serenity::ResolvedValue::SubCommand(_)
                        | serenity::ResolvedValue::SubCommandGroup(_)
                        | serenity::ResolvedValue::Autocomplete { .. } => {
                            tracing::warn!("unexpected interaction option type");
                            Ok(())
                        }
                        // We need this because ResolvedValue is #[non_exhaustive]
                        _ => {
                            tracing::warn!("newly-added unknown interaction option type");
                            Ok(())
                        }
                    };
                }
                string
            }
            Context::Prefix(ctx) => ctx.msg.content.clone(),
        }
    }

    /// Stores the given value as the data for this command invocation
    ///
    /// This data is carried across the `pre_command` hook, checks, main command execution, and
    /// `post_command`. It may be useful to cache data or pass information to later phases of command
    /// execution.
    await (set_invocation_data self data)
    (pub async fn set_invocation_data<T: 'static + Send + Sync>(self, data: T)) {
        *self.invocation_data_raw().lock().await = Box::new(data);
    }

    /// Attempts to get the invocation data with the requested type
    ///
    /// If the stored invocation data has a different type than requested, None is returned
    await (invocation_data self)
    (pub async fn invocation_data<T: 'static>(
        self,
    ) -> Option<impl std::ops::DerefMut<Target = T> + 'a>) {
        tokio::sync::MutexGuard::try_map(self.invocation_data_raw().lock().await, |any| {
            any.downcast_mut()
        })
        .ok()
    }

    /// If available, returns the locale (selected language) of the invoking user
    (locale self)
    (pub fn locale(self) -> Option<&'a str>) {
        match self {
            Context::Application(ctx) => Some(&ctx.interaction.locale),
            Context::Prefix(_) => None,
        }
    }

    /// Builds a [`crate::CreateReply`] by combining the builder closure with the defaults that were
    /// pre-configured in poise.
    ///
    /// This is primarily an internal function and only exposed for people who want to manually
    /// convert [`crate::CreateReply`] instances into Discord requests.
    #[allow(unused_mut)] // side effect of how macro works
    (reply_builder self builder)
    (pub fn reply_builder(self, mut builder: crate::CreateReply) -> crate::CreateReply) {
        let fw_options = self.framework().options();
        builder.ephemeral = builder.ephemeral.or(Some(self.command().ephemeral));
        builder.allowed_mentions = builder.allowed_mentions.or_else(|| fw_options.allowed_mentions.clone());

        if let Some(callback) = fw_options.reply_callback {
            builder = callback(self, builder);
        }

        builder
    }

    /// Returns serenity's cache which stores various useful data received from the gateway
    ///
    /// Shorthand for [`.serenity_context().cache`](serenity::Context::cache)
    #[cfg(feature = "cache")]
    (cache self)
    (pub fn cache(self) -> &'a serenity::Cache) {
        &self.serenity_context().cache
    }

    /// Returns serenity's raw Discord API client to make raw API requests, if needed.
    ///
    /// Shorthand for [`.serenity_context().http`](serenity::Context::http)
    (http self)
    (pub fn http(self) -> &'a serenity::Http) {
        &self.serenity_context().http
    }

    /// Returns the current gateway heartbeat latency ([`::serenity::gateway::Shard::latency()`]).
    ///
    /// If the shard has just connected, this value is zero.
    await (ping self)
    (pub async fn ping(self) -> std::time::Duration) {
        match self.framework().shard_manager.runners.lock().await.get(&self.serenity_context().shard_id) {
            Some(runner) => runner.latency.unwrap_or(std::time::Duration::ZERO),
            None => {
                tracing::error!("current shard is not in shard_manager.runners, this shouldn't happen");
                std::time::Duration::ZERO
            }
        }
    }
}

impl<'a, U, E> Context<'a, U, E> {
    /// Actual implementation of rerun() that returns `FrameworkError` for implementation convenience
    async fn rerun_inner(self) -> Result<(), crate::FrameworkError<'a, U, E>> {
        match self {
            Self::Application(ctx) => {
                // Skip autocomplete interactions
                if ctx.interaction_type == CommandInteractionType::Autocomplete {
                    return Ok(());
                }

                // Check slash command
                if ctx.interaction.data.kind == serenity::CommandType::ChatInput {
                    return if let Some(action) = ctx.command.slash_action {
                        action(ctx).await
                    } else {
                        Ok(())
                    };
                }

                // Check context menu command
                if let (Some(action), Some(target)) = (
                    ctx.command.context_menu_action,
                    &ctx.interaction.data.target(),
                ) {
                    return match action {
                        crate::ContextMenuCommandAction::User(action) => {
                            if let serenity::ResolvedTarget::User(user, _) = target {
                                action(ctx, (*user).clone()).await
                            } else {
                                Ok(())
                            }
                        }
                        crate::ContextMenuCommandAction::Message(action) => {
                            if let serenity::ResolvedTarget::Message(message) = target {
                                action(ctx, (*message).clone()).await
                            } else {
                                Ok(())
                            }
                        }
                        crate::ContextMenuCommandAction::__NonExhaustive => unreachable!(),
                    };
                }
            }
            Self::Prefix(ctx) => {
                if let Some(action) = ctx.command.prefix_action {
                    return action(ctx).await;
                }
            }
        }

        // Fallback if the Command doesn't have the action it needs to execute this context
        // (This should never happen, because if this context cannot be executed, how could this
        // method have been called)
        Ok(())
    }

    /// Returns the raw type erased invocation data
    fn invocation_data_raw(self) -> &'a tokio::sync::Mutex<Box<dyn std::any::Any + Send + Sync>> {
        match self {
            Context::Application(ctx) => ctx.invocation_data,
            Context::Prefix(ctx) => ctx.invocation_data,
        }
    }
}

/// Forwards for serenity::Context's impls. With these, poise's Context types can be passed in as-is
/// to serenity API functions.
macro_rules! context_trait_impls {
    ($($type:tt)*) => {
        #[cfg(feature = "cache")]
        impl<U, E> AsRef<serenity::Cache> for $($type)*<'_, U, E> {
            fn as_ref(&self) -> &serenity::Cache {
                &self.serenity_context().cache
            }
        }
        impl<U, E> AsRef<serenity::Http> for $($type)*<'_, U, E> {
            fn as_ref(&self) -> &serenity::Http {
                &self.serenity_context().http
            }
        }
        impl<U, E> AsRef<serenity::ShardMessenger> for $($type)*<'_, U, E> {
            fn as_ref(&self) -> &serenity::ShardMessenger {
                &self.serenity_context().shard
            }
        }
        // Originally added as part of component interaction modals; not sure if this impl is really
        // required by anything else... It makes sense to have though imo
        impl<U, E> AsRef<serenity::Context> for $($type)*<'_, U, E> {
            fn as_ref(&self) -> &serenity::Context {
                self.serenity_context()
            }
        }
        impl<U: Send + Sync, E> serenity::CacheHttp for $($type)*<'_, U, E> {
            fn http(&self) -> &serenity::Http {
                &self.serenity_context().http
            }

            #[cfg(feature = "cache")]
            fn cache(&self) -> Option<&std::sync::Arc<serenity::Cache>> {
                Some(&self.serenity_context().cache)
            }
        }
    };
}
context_trait_impls!(Context);
context_trait_impls!(crate::ApplicationContext);
context_trait_impls!(crate::PrefixContext);

/// Trimmed down, more general version of [`Context`]
pub struct PartialContext<'a, U, E> {
    /// ID of the guild, if not invoked in DMs
    pub guild_id: Option<serenity::GuildId>,
    /// ID of the invocation channel
    pub channel_id: serenity::ChannelId,
    /// ID of the invocation author
    pub author: &'a serenity::User,
    /// Serenity's context, like HTTP or cache
    pub serenity_context: &'a serenity::Context,
    /// Useful if you need the list of commands, for example for a custom help command
    pub framework: crate::FrameworkContext<'a, U, E>,
    /// Your custom user data
    // TODO: redundant with framework
    pub data: &'a U,
    #[doc(hidden)]
    pub __non_exhaustive: (),
}

impl<U, E> Copy for PartialContext<'_, U, E> {}
impl<U, E> Clone for PartialContext<'_, U, E> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, U, E> From<Context<'a, U, E>> for PartialContext<'a, U, E> {
    fn from(ctx: Context<'a, U, E>) -> Self {
        Self {
            guild_id: ctx.guild_id(),
            channel_id: ctx.channel_id(),
            author: ctx.author(),
            serenity_context: ctx.serenity_context(),
            framework: ctx.framework(),
            data: ctx.data(),
            __non_exhaustive: (),
        }
    }
}