Skip to main content

adk_surface/channels/discord/
mod.rs

1//! The Discord adapter (spec 3.5 §10 X12, on spec 3.3 §5.3): the Gateway in, REST out.
2
3mod api;
4mod wire;
5
6use std::fmt;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::time::Duration;
10
11use adk_core::{AdkError, ErrorCategory, ErrorComponent};
12use adk_kernel::KernelError;
13use adk_kernel::channels::{
14    ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
15    InboundOutcome, StopNotice,
16};
17use async_trait::async_trait;
18use chrono::Utc;
19use futures::{SinkExt, StreamExt};
20use reqwest::Method;
21use serde_json::{Value, json};
22use tokio::sync::mpsc;
23use tokio_tungstenite::tungstenite::Message;
24
25use super::shared::{
26    ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
27    PressedCard, REQUEST_TIMEOUT, Taker, Update, checked_base, dispatch, kit_builder, notice_words,
28    patient, stopped_words,
29};
30use crate::error::{Result, SurfaceError};
31use api::DiscordApi;
32use wire::{Interaction, Press};
33
34/// The channel the Discord adapter serves, as the kernel names it: pairings, thread sessions
35/// and `kernel.channel` audit records carry it (spec 3.5 §10 X12).
36pub const DISCORD_CHANNEL: &str = "discord";
37
38/// Discord as a person reads it, in "You said yes in Discord at 07:31" (spec 3.3 §8.1).
39pub const DISCORD: &str = "Discord";
40
41const DEFAULT_API_BASE: &str = "https://discord.com/api/v10";
42/// Direct messages (`DIRECT_MESSAGES`): their content needs no privileged intent.
43const INTENTS: u64 = 1 << 12;
44const MIN_BACKOFF: Duration = Duration::from_secs(1);
45const MAX_BACKOFF: Duration = Duration::from_secs(60);
46
47/// Why the Discord adapter could not talk to Discord (spec 3.5 §10 X12).
48///
49/// Never carries the bot token. Converts into [`AdkError`] with a `surface.discord.*` code
50/// and provider `discord`.
51///
52/// # Example
53///
54/// ```rust
55/// use adk_surface::channels::DiscordError;
56///
57/// let error = DiscordError::Unauthorized;
58/// assert_eq!(error.code(), "surface.discord.unauthorized");
59/// assert!(error.to_string().contains("DISCORD_BOT_TOKEN"));
60/// ```
61#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
62#[non_exhaustive]
63pub enum DiscordError {
64    /// Discord refused the bot token.
65    #[error(
66        "Discord refused the bot token: check DISCORD_BOT_TOKEN, or reset it in the Developer \
67         Portal (Bot → Reset Token)"
68    )]
69    Unauthorized,
70    /// Discord asked the bot to slow down for longer than the adapter waits.
71    #[error(
72        "Discord asked to wait {retry_after_ms} ms before {route}: the bot is sending too much"
73    )]
74    RateLimited {
75        /// The REST route.
76        route: String,
77        /// How long Discord asked to wait, in milliseconds.
78        retry_after_ms: u64,
79    },
80    /// Discord refused the call, such as a user who does not accept direct messages.
81    #[error("Discord refused {route} (HTTP {status}, code {code}): {message}")]
82    Refused {
83        /// The REST route.
84        route: String,
85        /// The HTTP status.
86        status: u16,
87        /// Discord's JSON error code.
88        code: i64,
89        /// Discord's message.
90        message: String,
91    },
92    /// The Gateway closed the connection for good.
93    #[error(
94        "the Discord Gateway closed the connection ({code}): {reason}; check the bot's intents \
95         in the Developer Portal"
96    )]
97    Gateway {
98        /// The close code, such as 4014 for disallowed intents.
99        code: u16,
100        /// Discord's reason.
101        reason: String,
102    },
103    /// Discord could not be reached.
104    #[error(
105        "Discord could not be reached for {route}: {reason}; check the network and the API address"
106    )]
107    Unreachable {
108        /// The REST route, or `gateway`.
109        route: String,
110        /// What failed.
111        reason: String,
112    },
113    /// Discord's answer was not the API's JSON.
114    #[error("Discord's answer to {route} could not be read: {reason}")]
115    InvalidResponse {
116        /// The REST route.
117        route: String,
118        /// What was wrong with it.
119        reason: String,
120    },
121}
122
123impl DiscordError {
124    /// The error code: `surface.discord.unauthorized`, `.rate_limited`, `.refused`,
125    /// `.gateway`, `.unreachable` or `.invalid_response`.
126    pub fn code(&self) -> &'static str {
127        match self {
128            Self::Unauthorized => "surface.discord.unauthorized",
129            Self::RateLimited { .. } => "surface.discord.rate_limited",
130            Self::Refused { .. } => "surface.discord.refused",
131            Self::Gateway { .. } => "surface.discord.gateway",
132            Self::Unreachable { .. } => "surface.discord.unreachable",
133            Self::InvalidResponse { .. } => "surface.discord.invalid_response",
134        }
135    }
136}
137
138impl From<DiscordError> for AdkError {
139    fn from(error: DiscordError) -> Self {
140        let category = match &error {
141            DiscordError::Unauthorized => ErrorCategory::Unauthorized,
142            DiscordError::RateLimited { .. } => ErrorCategory::RateLimited,
143            DiscordError::Refused { status: 403, .. } => ErrorCategory::Forbidden,
144            DiscordError::Refused { status: 404, .. } => ErrorCategory::NotFound,
145            DiscordError::Refused { status: 400, .. } => ErrorCategory::InvalidInput,
146            DiscordError::Refused { .. } | DiscordError::Unreachable { .. } => {
147                ErrorCategory::Unavailable
148            }
149            DiscordError::Gateway { .. } => ErrorCategory::Forbidden,
150            DiscordError::InvalidResponse { .. } => ErrorCategory::Internal,
151        };
152        AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
153            .with_provider("discord")
154    }
155}
156
157impl From<DiscordError> for KernelError {
158    fn from(error: DiscordError) -> Self {
159        Self::Core(error.into())
160    }
161}
162
163/// The Gateway connection a [`DiscordAdapter::start`] runs; dropping it stops it.
164pub type DiscordConnection = ChannelConnection<DiscordError>;
165
166/// Builds a [`DiscordAdapter`].
167pub struct DiscordAdapterBuilder {
168    token: String,
169    api_base: String,
170    kit: Kit,
171}
172
173impl fmt::Debug for DiscordAdapterBuilder {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        f.debug_struct("DiscordAdapterBuilder")
176            .field("api_base", &self.api_base)
177            .finish_non_exhaustive()
178    }
179}
180
181impl DiscordAdapterBuilder {
182    /// The REST API's address; defaults to `https://discord.com/api/v10`. Plain `http` is
183    /// accepted on loopback only (a test double), since the token travels with every call.
184    #[must_use]
185    pub fn api_base(mut self, url: impl Into<String>) -> Self {
186        self.api_base = url.into();
187        self
188    }
189
190    kit_builder!("Discord");
191
192    /// The adapter.
193    ///
194    /// # Errors
195    ///
196    /// Returns `surface.invalid` for an empty or malformed token, or an API address that is
197    /// not `https` (or `http` on loopback).
198    pub fn build(self) -> Result<DiscordAdapter> {
199        let api = DiscordApi::new(&self.api_base, &self.token).map_err(SurfaceError::Invalid)?;
200        Ok(DiscordAdapter { inner: Arc::new(Inner { api, kit: self.kit }) })
201    }
202}
203
204/// The Discord adapter (spec 3.5 §10 X12): a bot's direct messages as the person's chat
205/// thread with their agents, over the kernel's channel contract (spec 3.3 §10 K1).
206///
207/// It is the gateway's [`ChannelSink`] for the channel [`DISCORD_CHANNEL`], and
208/// [`start`](Self::start) reads the bot's events over the Gateway — a WebSocket the adapter
209/// opens, so no inbound port — identifying, keeping the heartbeat, resuming the session after
210/// a reconnect, and hands each to [`ChannelGateway::receive`].
211///
212/// | Direction | What |
213/// |---|---|
214/// | Out | A card: "Waiting for you · since 18:00", the call in plain words, the agent and the risk, a button for each answer the card offers and no others, and "Open in home" — never the call's arguments (S-I5). Every message escapes Discord's markdown and sends `allowed_mentions: {"parse": []}` (S-I9). A `429` is waited out per `retry_after`, never for a stranger |
215/// | In | New messages from a person in a direct message with the bot (`MESSAGE_CREATE`), and pressed buttons (`INTERACTION_CREATE`), each interaction answered through its callback at once; servers, bots and edits are ignored. Typed text never answers a decision (S-I4) and loses the characters a chat app shows as nothing (S-I6) |
216/// | Commands | `/stop`, declared as the bot's application command, and "stop all" stop everything; resuming is refused (S-I10) |
217///
218/// # Example
219///
220/// ```rust,no_run
221/// use std::sync::Arc;
222/// use adk_kernel::channels::{ChannelDoorbell, ChannelGateway, InMemoryChannelBindingStore};
223/// use adk_surface::channels::DiscordAdapter;
224///
225/// # async fn example(kernel: adk_kernel::Kernel, doorbell: Arc<ChannelDoorbell>) -> Result<(), Box<dyn std::error::Error>> {
226/// let discord = DiscordAdapter::builder(std::env::var("DISCORD_BOT_TOKEN")?).build()?;
227/// let gateway = ChannelGateway::builder(Arc::new(kernel), Arc::new(InMemoryChannelBindingStore::new()))
228///     .sink(Arc::new(discord.clone()))
229///     .home_url("http://127.0.0.1:8080/ui/")
230///     .doorbell(doorbell)
231///     .build();
232/// gateway.start().await?;
233/// let connection = discord.start(gateway);
234/// connection.join().await?;
235/// # Ok(())
236/// # }
237/// ```
238#[derive(Clone)]
239pub struct DiscordAdapter {
240    inner: Arc<Inner>,
241}
242
243struct Inner {
244    api: DiscordApi,
245    kit: Kit,
246}
247
248impl fmt::Debug for DiscordAdapter {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("DiscordAdapter").field("channel", &DISCORD_CHANNEL).finish_non_exhaustive()
251    }
252}
253
254/// A Gateway session the adapter resumes after a reconnect.
255#[derive(Debug, Clone)]
256struct Session {
257    id: String,
258    resume_url: String,
259    seq: Option<u64>,
260}
261
262/// Why a Gateway connection ended.
263enum Ended {
264    /// Connect again and resume the session.
265    Resume,
266    /// The session is gone: connect again and identify.
267    Fresh,
268    /// The connection failed; connect again after a wait and resume.
269    Failed(String),
270}
271
272/// What an event carries beyond its inbound value.
273pub(crate) struct Event {
274    press: Option<Press>,
275    interaction: Option<Interaction>,
276    files: Vec<crate::channels::media::FileRef>,
277}
278
279tokio::task_local! {
280    /// The `/stop` command being handled, whose deferred reply the first message to its
281    /// thread becomes.
282    static DEFERRED: Arc<Deferred>;
283}
284
285struct Deferred {
286    interaction: Interaction,
287    thread: String,
288    used: AtomicBool,
289}
290
291impl DiscordAdapter {
292    /// An adapter for the bot with `token`, from the Developer Portal.
293    pub fn builder(token: impl Into<String>) -> DiscordAdapterBuilder {
294        DiscordAdapterBuilder {
295            token: token.into(),
296            api_base: DEFAULT_API_BASE.to_string(),
297            kit: Kit::default(),
298        }
299    }
300
301    /// What the adapter makes of one Gateway dispatch, `{"op": 0, "t": …, "d": …}` (spec 3.3
302    /// S-I4, S-I6): a typed message, a pressed answer, `/stop`, or `None` for anything the
303    /// gateway is not given.
304    ///
305    /// # Example
306    ///
307    /// ```rust
308    /// use adk_kernel::channels::InboundBody;
309    /// use adk_surface::channels::DiscordAdapter;
310    ///
311    /// let discord = DiscordAdapter::builder("example-token").build().unwrap();
312    /// let dispatch = serde_json::json!({
313    ///     "op": 0, "s": 4, "t": "MESSAGE_CREATE",
314    ///     "d": {
315    ///         "id": "1300000000000000001", "channel_id": "1300000000000000002", "type": 0,
316    ///         "content": "stop all",
317    ///         "author": { "id": "1300000000000000003", "username": "ana" },
318    ///     },
319    /// });
320    /// let inbound = discord.inbound(&dispatch).unwrap();
321    /// assert_eq!(inbound.body, InboundBody::Text { text: "stop all".into() });
322    /// assert_eq!(inbound.thread, "1300000000000000002");
323    /// ```
324    pub fn inbound(&self, dispatch: &Value) -> Option<ChannelInbound> {
325        wire::parse(dispatch).inbound
326    }
327
328    /// Connects to the Gateway and hands each event to `gateway`, which must have this adapter
329    /// as its sink, until [`DiscordConnection::stop`].
330    ///
331    /// Each interaction is answered through its callback as it arrives. A paired account's
332    /// events go to the gateway first, each account's in the order sent (S-I6, S-I10); one
333    /// the gateway fails on is taken again only when it is a paired account's and the failure
334    /// may clear. When Discord asks for a reconnect, the heartbeat goes unanswered or the
335    /// socket fails, the adapter connects again and resumes the session, identifying anew
336    /// when Discord says it cannot be resumed. A refused token ends the connection with
337    /// [`DiscordError::Unauthorized`], and disallowed intents with [`DiscordError::Gateway`].
338    pub fn start(&self, gateway: ChannelGateway) -> DiscordConnection {
339        let adapter = self.clone();
340        ChannelConnection::spawn(async move { adapter.run(gateway).await })
341    }
342
343    async fn run(&self, gateway: ChannelGateway) -> std::result::Result<(), DiscordError> {
344        let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
345        let _dispatcher = AbortOnDrop(task);
346        let mut session: Option<Session> = None;
347        let mut backoff = MIN_BACKOFF;
348        loop {
349            let url = match &session {
350                Some(session) => session.resume_url.clone(),
351                None => match self.inner.api.gateway_url().await {
352                    Ok(url) => url,
353                    Err(DiscordError::Unauthorized) => return Err(DiscordError::Unauthorized),
354                    Err(error) => {
355                        tracing::warn!(error = %error, "the discord gateway could not be found; retrying");
356                        tokio::time::sleep(backoff).await;
357                        backoff = (backoff * 2).min(MAX_BACKOFF);
358                        continue;
359                    }
360                },
361            };
362            match self.serve(&url, &mut session, &sender).await? {
363                Ended::Resume => backoff = MIN_BACKOFF,
364                Ended::Fresh => {
365                    session = None;
366                    tokio::time::sleep(MIN_BACKOFF).await;
367                }
368                Ended::Failed(reason) => {
369                    tracing::warn!(reason = %reason, "the discord gateway connection ended; connecting again");
370                    tokio::time::sleep(backoff).await;
371                    backoff = (backoff * 2).min(MAX_BACKOFF);
372                }
373            }
374        }
375    }
376
377    /// Reads one Gateway connection until it ends.
378    async fn serve(
379        &self,
380        url: &str,
381        session: &mut Option<Session>,
382        sender: &mpsc::UnboundedSender<Update<Event>>,
383    ) -> std::result::Result<Ended, DiscordError> {
384        let url = format!("{}/?v=10&encoding=json", url.trim_end_matches('/'));
385        if let Err(reason) = checked_base(&url, "the Discord Gateway address", true) {
386            return Ok(Ended::Failed(reason));
387        }
388        adk_core::ensure_crypto_provider();
389        let connect = tokio_tungstenite::connect_async(url.as_str());
390        let mut socket = match tokio::time::timeout(REQUEST_TIMEOUT, connect).await {
391            Ok(Ok((socket, _))) => socket,
392            Ok(Err(error)) => return Ok(Ended::Failed(error.to_string())),
393            Err(_) => return Ok(Ended::Failed("the gateway did not open in time".into())),
394        };
395        // Hello first: how often to beat.
396        let hello = tokio::time::timeout(REQUEST_TIMEOUT, socket.next()).await;
397        let interval = match hello {
398            Ok(Some(Ok(Message::Text(text)))) => serde_json::from_str::<Value>(text.as_str())
399                .ok()
400                .filter(|hello| hello["op"] == 10)
401                .and_then(|hello| hello["d"]["heartbeat_interval"].as_u64()),
402            _ => None,
403        };
404        let Some(interval) = interval.filter(|interval| *interval > 0) else {
405            return Ok(Ended::Failed("the gateway did not say hello".into()));
406        };
407        let token = self.inner.api.token();
408        let mut seq = session.as_ref().and_then(|session| session.seq);
409        let opening = match session.as_ref() {
410            Some(session) => {
411                json!({ "op": 6, "d": { "token": token, "session_id": session.id, "seq": seq } })
412            }
413            None => json!({ "op": 2, "d": {
414                "token": token,
415                "intents": INTENTS,
416                "properties": { "os": std::env::consts::OS, "browser": "adk-rust", "device": "adk-rust" },
417            }}),
418        };
419        if let Err(error) = socket.send(Message::Text(opening.to_string().into())).await {
420            return Ok(Ended::Failed(error.to_string()));
421        }
422        // The first beat comes after a random part of the interval, as Discord asks.
423        let jitter = u64::try_from(uuid::Uuid::new_v4().as_u128() % 1000).unwrap_or(500);
424        let period = Duration::from_millis(interval);
425        let first = tokio::time::Instant::now() + period.mul_f64(jitter as f64 / 1000.0);
426        let mut beat = tokio::time::interval_at(first, period);
427        let mut acked = true;
428        loop {
429            let frame = tokio::select! {
430                _ = beat.tick() => {
431                    if !acked {
432                        return Ok(Ended::Failed("the gateway did not answer the heartbeat".into()));
433                    }
434                    acked = false;
435                    let heartbeat = json!({ "op": 1, "d": seq }).to_string();
436                    if let Err(error) = socket.send(Message::Text(heartbeat.into())).await {
437                        return Ok(Ended::Failed(error.to_string()));
438                    }
439                    continue;
440                }
441                frame = socket.next() => frame,
442            };
443            let text = match frame {
444                Some(Ok(Message::Text(text))) => text,
445                Some(Ok(Message::Close(frame))) => {
446                    let (code, reason) = frame
447                        .map(|frame| (u16::from(frame.code), frame.reason.to_string()))
448                        .unwrap_or((1000, String::new()));
449                    return match code {
450                        4004 => Err(DiscordError::Unauthorized),
451                        4010..=4014 => Err(DiscordError::Gateway { code, reason }),
452                        4007 | 4009 => Ok(Ended::Fresh),
453                        _ => Ok(Ended::Failed(format!("closed ({code})"))),
454                    };
455                }
456                None => return Ok(Ended::Failed("the gateway closed".into())),
457                Some(Ok(_)) => continue,
458                Some(Err(error)) => return Ok(Ended::Failed(error.to_string())),
459            };
460            let Ok(payload) = serde_json::from_str::<Value>(text.as_str()) else { continue };
461            match payload["op"].as_u64() {
462                Some(0) => {
463                    if let Some(s) = payload["s"].as_u64() {
464                        seq = Some(s);
465                        if let Some(session) = session.as_mut() {
466                            session.seq = seq;
467                        }
468                    }
469                    match payload["t"].as_str() {
470                        Some("READY") => {
471                            let d = &payload["d"];
472                            *session = Some(Session {
473                                id: d["session_id"].as_str().unwrap_or_default().to_string(),
474                                resume_url: d["resume_gateway_url"]
475                                    .as_str()
476                                    .unwrap_or(&url)
477                                    .to_string(),
478                                seq,
479                            });
480                            if let Some(application) = d["application"]["id"].as_str() {
481                                self.declare_commands(application);
482                            }
483                        }
484                        Some("RESUMED") => tracing::debug!("the discord session resumed"),
485                        _ => self.dispatched(&payload, sender).await,
486                    }
487                }
488                Some(1) => {
489                    let heartbeat = json!({ "op": 1, "d": seq }).to_string();
490                    if let Err(error) = socket.send(Message::Text(heartbeat.into())).await {
491                        return Ok(Ended::Failed(error.to_string()));
492                    }
493                }
494                Some(7) => return Ok(Ended::Resume),
495                Some(9) if payload["d"].as_bool() == Some(true) => return Ok(Ended::Resume),
496                Some(9) => return Ok(Ended::Fresh),
497                Some(11) => acked = true,
498                _ => {}
499            }
500        }
501    }
502
503    /// Answers a dispatch's interaction through its callback at once, then hands what it
504    /// carries over.
505    async fn dispatched(&self, payload: &Value, sender: &mpsc::UnboundedSender<Update<Event>>) {
506        let parsed = wire::parse(payload);
507        if let Some(interaction) = &parsed.interaction {
508            let taken = parsed.inbound.is_some();
509            let answer = match (interaction.command, taken) {
510                // The deferred reply becomes the stop notice.
511                (true, true) => json!({ "type": 5 }),
512                (true, false) => json!({ "type": 4, "data": {
513                    "content": "This works in a direct message with the bot.",
514                    "flags": 64,
515                    "allowed_mentions": { "parse": [] },
516                }}),
517                (false, _) => json!({ "type": 6 }),
518            };
519            let route = format!("/interactions/{}/{}/callback", interaction.id, interaction.token);
520            if let Err(error) =
521                self.inner.api.request(Method::POST, &route, Some(&answer), false).await
522            {
523                tracing::debug!(error = %error, "a discord interaction could not be answered");
524            }
525        }
526        if parsed.inbound.is_some() {
527            let event =
528                Event { press: parsed.press, interaction: parsed.interaction, files: parsed.files };
529            let _ = sender.send(Update { inbound: parsed.inbound, press: Some(event) });
530        }
531    }
532
533    /// Declares `/stop` as the bot's application command, as Telegram's adapter lists it.
534    fn declare_commands(&self, application: &str) {
535        let adapter = self.clone();
536        let route = format!("/applications/{application}/commands");
537        tokio::spawn(async move {
538            let commands = wire::commands();
539            if let Err(error) =
540                adapter.inner.api.request(Method::PUT, &route, Some(&commands), true).await
541            {
542                tracing::warn!(error = %error, "the bot's /stop command could not be declared");
543            }
544        });
545    }
546
547    /// Takes the answer buttons off an answered card, so it is not pressed again.
548    async fn clear_buttons(&self, press: &Press) {
549        let Some((channel, message)) = &press.card else { return };
550        if !id_like(channel) || !id_like(message) {
551            return;
552        }
553        let route = format!("/channels/{channel}/messages/{message}");
554        let body = wire::answered(press);
555        if let Err(error) = self.inner.api.request(Method::PATCH, &route, Some(&body), true).await {
556            tracing::debug!(error = %error, "an answered card's buttons could not be removed");
557        }
558    }
559
560    async fn post(&self, thread: &str, body: Value) -> adk_kernel::Result<()> {
561        // A `/stop` in hand: its deferred reply says what happened.
562        if let Ok(deferred) = DEFERRED.try_with(Arc::clone)
563            && deferred.thread == thread
564            && !deferred.used.swap(true, Ordering::SeqCst)
565        {
566            let Interaction { application, token, .. } = &deferred.interaction;
567            let route = format!("/webhooks/{application}/{token}/messages/@original");
568            self.inner.api.request(Method::PATCH, &route, Some(&body), true).await?;
569            return Ok(());
570        }
571        if !id_like(thread) {
572            return Err(DiscordError::Refused {
573                route: "/channels".into(),
574                status: 400,
575                code: 0,
576                message: "the thread is not a Discord channel id".into(),
577            }
578            .into());
579        }
580        // A rate limit on a reply to an account that is not paired is not waited out.
581        let patient = patient(DISCORD_CHANNEL, thread);
582        let route = format!("/channels/{thread}/messages");
583        self.inner.api.request(Method::POST, &route, Some(&body), patient).await?;
584        Ok(())
585    }
586}
587
588/// Whether `id` can stand in a route: Discord's snowflakes, and the names the contract
589/// suite gives its threads.
590fn id_like(id: &str) -> bool {
591    !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
592}
593
594#[async_trait]
595impl Taker for DiscordAdapter {
596    type Press = Event;
597
598    fn channel_name(&self) -> &'static str {
599        DISCORD_CHANNEL
600    }
601
602    /// Hands one event to the gateway; an answered card loses its answer buttons, and a
603    /// `/stop` whose deferred reply said nothing has it removed.
604    async fn take(
605        &self,
606        gateway: &ChannelGateway,
607        update: &Update<Event>,
608        paired: bool,
609    ) -> adk_kernel::Result<()> {
610        let Some(mut inbound) = update.inbound.clone() else { return Ok(()) };
611        let event = update.press.as_ref();
612        // A paired account's images, for a host that takes them; a stranger's are never
613        // downloaded (spec 3.5 §10 X12).
614        let files = event.map_or(&[][..], |event| event.files.as_slice());
615        if paired && !files.is_empty() {
616            let api = &self.inner.api;
617            let attachments =
618                crate::channels::media::fetch_all(files, |file| api.download(file)).await;
619            inbound = inbound.with_attachments(attachments);
620        }
621        let press = event.and_then(|event| event.press.as_ref());
622        let card = match (&inbound.body, press) {
623            (InboundBody::Answer { decision, .. }, Some(press)) => Some(PressedCard {
624                card: press.card.as_ref().map(|(_, message)| message.clone()),
625                decision: decision.clone(),
626            }),
627            _ => None,
628        };
629        let command = event.and_then(|event| event.interaction.clone()).filter(|i| i.command);
630        let handling = Handling::of(DISCORD_CHANNEL, gateway, &inbound, paired, card);
631        let thread = inbound.thread.clone();
632        let receive = HANDLING.scope(handling, gateway.receive(inbound));
633        let outcome = match command {
634            Some(interaction) => {
635                let deferred =
636                    Arc::new(Deferred { interaction, thread, used: AtomicBool::new(false) });
637                let outcome = DEFERRED.scope(deferred.clone(), receive).await;
638                if !deferred.used.load(Ordering::SeqCst) {
639                    let Interaction { application, token, .. } = &deferred.interaction;
640                    let route = format!("/webhooks/{application}/{token}/messages/@original");
641                    let _ = self.inner.api.request(Method::DELETE, &route, None, false).await;
642                }
643                outcome
644            }
645            None => receive.await,
646        };
647        let Some(press) = press else { return outcome.map(drop) };
648        if matches!(
649            outcome?,
650            InboundOutcome::Decided { .. }
651                | InboundOutcome::AlreadyDecided { .. }
652                | InboundOutcome::DecisionChanged { .. }
653                | InboundOutcome::DecisionRefused { .. }
654        ) {
655            self.clear_buttons(press).await;
656        }
657        Ok(())
658    }
659
660    async fn not_taken(&self, update: &Update<Event>) {
661        let Some(inbound) = &update.inbound else { return };
662        let answered = update.press.as_ref().is_some_and(|event| event.press.is_some());
663        let text = if answered { ANSWER_NOT_TAKEN } else { MESSAGE_NOT_TAKEN };
664        for body in wire::plain(text) {
665            if let Err(error) = self.post(&inbound.thread, body).await {
666                tracing::debug!(error = %error, "a person could not be told their message was not taken");
667            }
668        }
669    }
670}
671
672#[async_trait]
673impl ChannelSink for DiscordAdapter {
674    fn channel(&self) -> &str {
675        DISCORD_CHANNEL
676    }
677
678    async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
679        for body in wire::plain(text) {
680            self.post(thread, body).await?;
681        }
682        Ok(())
683    }
684
685    async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
686        let (heading, card) = self.inner.kit.prepare(card).await;
687        self.post(thread, wire::card(&card, &heading, self.inner.kit.offset)).await
688    }
689
690    async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
691        self.post(thread, wire::message(&stopped_words(notice))).await
692    }
693
694    /// A notice about a pressed card records the answer with where it was given before the
695    /// confirmation is sent, as a reply to the card (spec 3.3 §8.1, §11).
696    async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
697        let card = self.inner.kit.before_notice(DISCORD_CHANNEL, DISCORD, thread, notice).await;
698        let words = notice_words(notice, self.inner.kit.offset, Utc::now(), card.is_some());
699        let mut body = wire::message(&words);
700        if let Some(card) = card {
701            body["message_reference"] = json!({ "message_id": card, "fail_if_not_exists": false });
702        }
703        self.post(thread, body).await
704    }
705}
706
707#[cfg(test)]
708mod tests {
709    use super::*;
710
711    #[test]
712    fn errors_say_what_to_do_and_keep_their_category() {
713        let error: AdkError = DiscordError::Unauthorized.into();
714        assert_eq!(
715            (error.code, error.category),
716            ("surface.discord.unauthorized", ErrorCategory::Unauthorized)
717        );
718        let closed = DiscordError::Gateway { code: 4014, reason: "Disallowed intent(s).".into() };
719        assert!(closed.to_string().contains("intents"));
720        let limited =
721            DiscordError::RateLimited { route: "/channels".into(), retry_after_ms: 90_000 };
722        assert!(AdkError::from(limited).is_retryable());
723    }
724
725    #[test]
726    fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
727        let error = DiscordAdapter::builder("secret-token")
728            .api_base("http://example.com")
729            .build()
730            .unwrap_err();
731        assert!(!error.to_string().contains("secret"), "{error}");
732        assert!(DiscordAdapter::builder("").build().is_err());
733        let adapter = DiscordAdapter::builder("secret-token").build().unwrap();
734        assert!(!format!("{adapter:?}").contains("secret"));
735        assert_eq!(ChannelSink::channel(&adapter), "discord");
736        assert!(
737            id_like("1300000000000000002") && id_like("t-ana") && !id_like("../x") && !id_like("")
738        );
739    }
740}