Skip to main content

zaun_bot/
context.rs

1//! [`Context`]: one interaction and the ways to answer it.
2
3use crate::interactions;
4use crate::types::{
5    HostError, Id, Interaction, InteractionData, Member, Message, MessageBody, Modal, Response,
6};
7use crate::{Modal as ModalBuilder, Reply};
8
9/// The interaction being handled, without its data (handlers get the data separately).
10///
11/// The first answer must be one of [`reply`](Self::reply),
12/// [`reply_ephemeral`](Self::reply_ephemeral), [`respond`](Self::respond),
13/// [`defer`](Self::defer), [`defer_update`](Self::defer_update),
14/// [`update_message`](Self::update_message) or [`show_modal`](Self::show_modal), within 3 s.
15/// After it, use [`followup`](Self::followup) and [`edit_original`](Self::edit_original) for
16/// 15 minutes.
17#[derive(Debug, Clone)]
18pub struct Context {
19    /// The interaction id.
20    pub id: Id,
21    /// The bot's id in this community.
22    pub bot_id: Id,
23    /// The channel it happened in.
24    pub channel_id: Id,
25    /// Who triggered it.
26    pub member: Member,
27    /// The bot's effective permissions in the channel.
28    pub app_permissions: u64,
29    /// The invoker's locale (BCP 47), if their client sent one.
30    pub locale: Option<String>,
31    /// For component interactions: the message holding the component.
32    pub message: Option<Message>,
33    /// When the host received it (ms).
34    pub created_at: u64,
35}
36
37impl Context {
38    /// Splits an interaction into its context and data.
39    #[must_use]
40    pub fn split(i: Interaction) -> (Self, InteractionData) {
41        let ctx = Self {
42            id: i.interaction_id,
43            bot_id: i.bot_id,
44            channel_id: i.channel_id,
45            member: i.member,
46            app_permissions: i.app_permissions,
47            locale: i.locale,
48            message: i.message,
49            created_at: i.created_at,
50        };
51        (ctx, i.data)
52    }
53
54    /// Sends any initial [`Response`]. Returns the created message id, if any.
55    ///
56    /// # Errors
57    /// The host's refusal (already answered, too late, a message the bot may not send).
58    pub fn respond(&self, response: Response) -> Result<Option<Id>, HostError> {
59        interactions::respond(&self.id, &response)
60    }
61
62    /// Answers with a message in the channel.
63    ///
64    /// # Errors
65    /// See [`respond`](Self::respond).
66    pub fn reply(&self, reply: impl Into<Reply>) -> Result<Option<Id>, HostError> {
67        self.respond(Response::Message(reply.into().build()))
68    }
69
70    /// Answers with a message only the invoker sees.
71    ///
72    /// # Errors
73    /// See [`respond`](Self::respond).
74    pub fn reply_ephemeral(&self, reply: impl Into<Reply>) -> Result<Option<Id>, HostError> {
75        self.respond(Response::Message(reply.into().ephemeral().build()))
76    }
77
78    /// Shows "thinking…" and buys 15 minutes; finish with [`edit_original`](Self::edit_original).
79    ///
80    /// # Errors
81    /// See [`respond`](Self::respond).
82    pub fn defer(&self, ephemeral: bool) -> Result<Option<Id>, HostError> {
83        self.respond(Response::DeferredMessage(ephemeral))
84    }
85
86    /// Acknowledges a component click without changing anything yet.
87    ///
88    /// # Errors
89    /// See [`respond`](Self::respond).
90    pub fn defer_update(&self) -> Result<Option<Id>, HostError> {
91        self.respond(Response::DeferredUpdate)
92    }
93
94    /// Replaces the message holding the clicked component (it must be the bot's).
95    ///
96    /// # Errors
97    /// See [`respond`](Self::respond).
98    pub fn update_message(&self, reply: impl Into<Reply>) -> Result<Option<Id>, HostError> {
99        self.respond(Response::UpdateMessage(reply.into().build()))
100    }
101
102    /// Opens a modal for the invoker. Not allowed in answer to a modal submit.
103    ///
104    /// # Errors
105    /// See [`respond`](Self::respond).
106    pub fn show_modal(&self, modal: impl Into<Modal>) -> Result<Option<Id>, HostError> {
107        self.respond(Response::Modal(modal.into()))
108    }
109
110    /// Sends a follow-up message (at most 10).
111    ///
112    /// # Errors
113    /// The host's refusal.
114    pub fn followup(&self, reply: impl Into<Reply>) -> Result<Option<Id>, HostError> {
115        interactions::followup(&self.id, &reply.into().build())
116    }
117
118    /// Replaces the original response.
119    ///
120    /// # Errors
121    /// The host's refusal.
122    pub fn edit_original(&self, reply: impl Into<Reply>) -> Result<(), HostError> {
123        let body: MessageBody = reply.into().build();
124        interactions::edit_original(&self.id, &body)
125    }
126
127    /// Deletes the original response.
128    ///
129    /// # Errors
130    /// The host's refusal.
131    pub fn delete_original(&self) -> Result<(), HostError> {
132        interactions::delete_original(&self.id)
133    }
134
135    /// Sends a direct message to a member (capability `dms`), for example the invoker:
136    /// `ctx.dm(&ctx.member.member_id, "details")`. Returns the DM's channel id and the
137    /// message id.
138    ///
139    /// # Errors
140    /// The host's refusal (`FORBIDDEN` with reason `dms_closed` when the member does not take
141    /// DMs from bots).
142    pub fn dm(&self, member_id: &str, reply: impl Into<Reply>) -> Result<(Id, Id), HostError> {
143        let body: MessageBody = reply.into().build();
144        crate::messages::dm(member_id, &body)
145    }
146}
147
148impl From<ModalBuilder> for Modal {
149    fn from(m: ModalBuilder) -> Self {
150        m.build()
151    }
152}
153
154/// Presence shortcuts, for handlers that already hold a [`Context`].
155impl Context {
156    /// Sets the bot's status and activity ([`crate::presence::set`]).
157    pub fn set_presence(
158        &self,
159        status: crate::presence::Status,
160        activity: impl Into<Option<crate::presence::Activity>>,
161    ) {
162        crate::presence::set(status, activity);
163    }
164
165    /// Sets the bot's custom status text ([`crate::presence::set_status_text`]).
166    ///
167    /// # Errors
168    /// The host's refusal.
169    pub fn set_status_text(&self, text: impl Into<String>) -> Result<(), HostError> {
170        crate::presence::set_status_text(text)
171    }
172}