1mod 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
34pub const DISCORD_CHANNEL: &str = "discord";
37
38pub const DISCORD: &str = "Discord";
40
41const DEFAULT_API_BASE: &str = "https://discord.com/api/v10";
42const INTENTS: u64 = 1 << 12;
44const MIN_BACKOFF: Duration = Duration::from_secs(1);
45const MAX_BACKOFF: Duration = Duration::from_secs(60);
46
47#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
62#[non_exhaustive]
63pub enum DiscordError {
64 #[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 #[error(
72 "Discord asked to wait {retry_after_ms} ms before {route}: the bot is sending too much"
73 )]
74 RateLimited {
75 route: String,
77 retry_after_ms: u64,
79 },
80 #[error("Discord refused {route} (HTTP {status}, code {code}): {message}")]
82 Refused {
83 route: String,
85 status: u16,
87 code: i64,
89 message: String,
91 },
92 #[error(
94 "the Discord Gateway closed the connection ({code}): {reason}; check the bot's intents \
95 in the Developer Portal"
96 )]
97 Gateway {
98 code: u16,
100 reason: String,
102 },
103 #[error(
105 "Discord could not be reached for {route}: {reason}; check the network and the API address"
106 )]
107 Unreachable {
108 route: String,
110 reason: String,
112 },
113 #[error("Discord's answer to {route} could not be read: {reason}")]
115 InvalidResponse {
116 route: String,
118 reason: String,
120 },
121}
122
123impl DiscordError {
124 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
163pub type DiscordConnection = ChannelConnection<DiscordError>;
165
166pub 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 #[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 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#[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#[derive(Debug, Clone)]
256struct Session {
257 id: String,
258 resume_url: String,
259 seq: Option<u64>,
260}
261
262enum Ended {
264 Resume,
266 Fresh,
268 Failed(String),
270}
271
272pub(crate) struct Event {
274 press: Option<Press>,
275 interaction: Option<Interaction>,
276 files: Vec<crate::channels::media::FileRef>,
277}
278
279tokio::task_local! {
280 static DEFERRED: Arc<Deferred>;
283}
284
285struct Deferred {
286 interaction: Interaction,
287 thread: String,
288 used: AtomicBool,
289}
290
291impl DiscordAdapter {
292 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 pub fn inbound(&self, dispatch: &Value) -> Option<ChannelInbound> {
325 wire::parse(dispatch).inbound
326 }
327
328 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 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 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 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 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 (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 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 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 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 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
588fn 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 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 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 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}