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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! Discord Bot channel.
//!
//! Uses the Discord HTTP API for sending messages and a WebSocket
//! connection to the Discord Gateway for receiving events.
//!
//! Features:
//! - Gateway identify + heartbeat loop.
//! - MESSAGE_CREATE event dispatch.
//! - Text chunking (2000-char Discord limit).
//! - Exponential back-off on send failures.
//! - Preview streaming: partial mode sends a placeholder then edits it with
//! the full reply via PATCH /channels/{id}/messages/{msg_id} (agents.md
//! §21).
use std::{sync::Arc, time::Duration};
use anyhow::{Context, Result, bail};
use futures::{SinkExt as _, StreamExt as _, future::BoxFuture};
use reqwest::Client;
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::time::sleep;
use tokio_tungstenite::{connect_async, tungstenite::Message as WsMessage};
use tracing::{debug, info, warn};
/// Minimum reply length (chars) that triggers preview streaming.
const DISCORD_PREVIEW_THRESHOLD: usize = 200;
/// Delay between sending the placeholder and editing with the full reply.
const DISCORD_EDIT_DELAY: std::time::Duration = std::time::Duration::from_millis(500);
use super::{Channel, OutboundMessage};
use crate::channel::{
attachments::{mime_to_ext, parse_data_url, pick_file_mime},
chunker::{BreakPreference, ChunkConfig, chunk_text, platform_chunk_limit},
telegram::RetryConfig,
};
const DISCORD_API_BASE: &str = "https://discord.com/api/v10";
const DISCORD_GATEWAY: &str = "wss://gateway.discord.gg/?v=10&encoding=json";
const DISCORD_GATEWAY_BOT_PATH: &str = "/gateway/bot";
// ---------------------------------------------------------------------------
// Discord API types
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
pub struct GatewayPayload {
pub op: u8,
pub d: Option<Value>,
pub s: Option<u64>,
pub t: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct MessageCreate {
pub id: String,
pub content: String,
pub channel_id: String,
pub author: DiscordUser,
pub guild_id: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct DiscordUser {
pub id: String,
pub bot: Option<bool>,
}
// ---------------------------------------------------------------------------
// DiscordChannel
// ---------------------------------------------------------------------------
pub struct DiscordChannel {
token: String,
client: Client,
retry: RetryConfig,
allow_bots: bool,
#[allow(clippy::type_complexity)]
on_message: Arc<
dyn Fn(
String,
String,
String,
bool,
Vec<crate::agent::registry::ImageAttachment>,
Vec<crate::agent::registry::FileAttachment>,
) + Send
+ Sync,
>,
// (peer_id, text, channel_id, is_guild, images, files)
/// HTTP API base URL (overridable for testing).
api_base: String,
/// Gateway WebSocket URL override. When set, skip the /gateway/bot fetch.
gateway_url: Option<String>,
/// Bot's own user ID, captured from the READY event. Used to strip
/// the `<@bot_id>` mention prefix that Discord prepends in guild
/// messages — without stripping, slash commands like `/ss` arrive as
/// `<@123> /ss` and bypass the fast-preparse path.
bot_user_id: Arc<std::sync::RwLock<Option<String>>>,
}
impl DiscordChannel {
#[allow(clippy::type_complexity)]
pub fn new(
token: impl Into<String>,
allow_bots: bool,
on_message: Arc<
dyn Fn(
String,
String,
String,
bool,
Vec<crate::agent::registry::ImageAttachment>,
Vec<crate::agent::registry::FileAttachment>,
) + Send
+ Sync,
>,
api_base: Option<String>,
gateway_url: Option<String>,
) -> Self {
Self {
token: token.into(),
client: crate::config::build_proxy_client()
.timeout(Duration::from_secs(30))
.build()
.expect("reqwest client"),
retry: RetryConfig::default(),
allow_bots,
on_message,
api_base: api_base.unwrap_or_else(|| DISCORD_API_BASE.to_owned()),
gateway_url,
bot_user_id: Arc::new(std::sync::RwLock::new(None)),
}
}
fn auth_header(&self) -> String {
format!("Bot {}", self.token)
}
async fn send_chunk(&self, channel_id: &str, text: &str) -> Result<()> {
let body = json!({ "content": text });
for attempt in 0..self.retry.attempts {
let resp = self
.client
.post(format!("{}/channels/{channel_id}/messages", self.api_base))
.header("authorization", self.auth_header())
.json(&body)
.send()
.await
.context("Discord send message")?;
let status = resp.status();
if status.as_u16() == 429 {
// Respect Retry-After header if present.
let retry_after = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<f64>().ok())
.map(|s| Duration::from_millis((s * 1000.0) as u64))
.unwrap_or(Duration::from_millis(500));
warn!(attempt, ?retry_after, "Discord rate limit");
sleep(retry_after).await;
continue;
}
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
bail!("Discord send failed {status}: {body}");
}
return Ok(());
}
bail!("Discord send failed after {} attempts", self.retry.attempts)
}
/// POST a message to `channel_id` and return the Discord message ID.
/// Used by preview streaming to get the ID of the placeholder message.
async fn send_message_returning_id(&self, channel_id: &str, text: &str) -> Result<String> {
let body = json!({ "content": text });
for attempt in 0..self.retry.attempts {
let resp = self
.client
.post(format!("{}/channels/{channel_id}/messages", self.api_base))
.header("authorization", self.auth_header())
.json(&body)
.send()
.await
.context("Discord send message (preview)")?;
let status = resp.status();
if status.as_u16() == 429 {
let retry_after = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<f64>().ok())
.map(|s| std::time::Duration::from_millis((s * 1000.0) as u64))
.unwrap_or(std::time::Duration::from_millis(500));
warn!(attempt, ?retry_after, "Discord rate limit (preview send)");
sleep(retry_after).await;
continue;
}
if !status.is_success() {
let err = resp.text().await.unwrap_or_default();
bail!("Discord send (preview) failed {status}: {err}");
}
let v: Value = resp.json().await.context("parse Discord message result")?;
let id = v["id"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Discord: missing message id in response"))?
.to_owned();
return Ok(id);
}
bail!(
"Discord send (preview) failed after {} attempts",
self.retry.attempts
)
}
/// Edit an existing Discord message via PATCH
/// /channels/{id}/messages/{msg_id}.
///
/// Used by preview streaming (agents.md §21) to replace the placeholder
/// message with the final reply text.
async fn edit_message(&self, channel_id: &str, message_id: &str, new_text: &str) -> Result<()> {
let body = json!({ "content": new_text });
for attempt in 0..self.retry.attempts {
let resp = self
.client
.patch(format!(
"{}/channels/{channel_id}/messages/{message_id}",
self.api_base
))
.header("authorization", self.auth_header())
.json(&body)
.send()
.await
.context("Discord edit message")?;
let status = resp.status();
if status.as_u16() == 429 {
let retry_after = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<f64>().ok())
.map(|s| std::time::Duration::from_millis((s * 1000.0) as u64))
.unwrap_or(std::time::Duration::from_millis(500));
warn!(attempt, ?retry_after, "Discord rate limit (edit)");
sleep(retry_after).await;
continue;
}
if !status.is_success() {
let err = resp.text().await.unwrap_or_default();
bail!("Discord edit message failed {status}: {err}");
}
return Ok(());
}
bail!(
"Discord edit message failed after {} attempts",
self.retry.attempts
)
}
/// Preview streaming send (agents.md §21, "partial" mode).
///
/// For replies longer than `DISCORD_PREVIEW_THRESHOLD` characters:
/// 1. POST a placeholder message ("…") to show the user an immediate
/// response.
/// 2. PATCH the same message with the full reply text after a short
/// delay.
///
/// Shorter replies fall back to the standard `send_chunk` path.
pub async fn send_with_preview(&self, channel_id: &str, text: &str) -> Result<()> {
if text.len() <= DISCORD_PREVIEW_THRESHOLD {
return self.send_chunk(channel_id, text).await;
}
// Send placeholder so the user sees an immediate response.
let msg_id = self.send_message_returning_id(channel_id, "…").await?;
debug!(channel_id, msg_id, "Discord preview: placeholder sent");
// Simulate streaming delay then edit with the full reply.
sleep(DISCORD_EDIT_DELAY).await;
self.edit_message(channel_id, &msg_id, text).await?;
debug!(
channel_id,
msg_id, "Discord preview: message updated with full reply"
);
Ok(())
}
/// Get the WebSocket gateway URL.
async fn get_gateway_url(&self) -> Result<String> {
let resp = self
.client
.get(format!("{}{DISCORD_GATEWAY_BOT_PATH}", self.api_base))
.header("authorization", self.auth_header())
.send()
.await
.context("GET /gateway/bot")?;
let v: Value = resp.json().await.context("parse gateway")?;
let url = v["url"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing gateway url"))?;
Ok(format!("{url}/?v=10&encoding=json"))
}
/// Full Discord Gateway WebSocket loop.
///
/// Protocol:
/// OP 10 HELLO — receive heartbeat_interval
/// OP 2 IDENTIFY — send bot token + intents (MESSAGE: 1<<9 = 512)
/// OP 1 HEARTBEAT — send every heartbeat_interval ms
/// OP 11 HEARTBEAT_ACK — receive from server
/// OP 0 DISPATCH — receive events (READY, MESSAGE_CREATE)
async fn gateway_loop(&self) -> Result<()> {
let url = if let Some(ref override_url) = self.gateway_url {
override_url.clone()
} else {
self.get_gateway_url()
.await
.unwrap_or_else(|_| DISCORD_GATEWAY.to_owned())
};
info!("Discord: connecting to gateway {url}");
let (ws_stream, _) = connect_async(&url).await.context("Discord WS connect")?;
let (mut write, mut read) = ws_stream.split();
#[allow(unused_assignments)]
let mut heartbeat_interval = Duration::from_millis(41_250); // default; overwritten by OP10
let mut last_sequence: Option<u64> = None;
let mut heartbeat_ticker: Option<tokio::time::Interval> = None;
let mut identified = false;
loop {
// Drive heartbeat + read concurrently.
let ws_msg = if let Some(ref mut ticker) = heartbeat_ticker {
tokio::select! {
_ = ticker.tick() => {
let hb = json!({"op": 1, "d": last_sequence});
debug!("Discord: sending heartbeat (seq={last_sequence:?})");
if write.send(WsMessage::Text(hb.to_string().into())).await.is_err() {
bail!("Discord: WS write error on heartbeat");
}
continue;
}
msg = read.next() => msg,
}
} else {
read.next().await
};
let raw = match ws_msg {
Some(Ok(WsMessage::Text(s))) => s.to_string(),
Some(Ok(WsMessage::Close(frame))) => {
let code = frame.as_ref().map(|f| f.code.into()).unwrap_or(0u16);
info!("Discord: gateway closed (code {code})");
bail!("Discord: gateway closed (code {code})");
}
Some(Ok(_)) => continue, // binary/ping/pong
Some(Err(e)) => bail!("Discord: WS error: {e}"),
None => bail!("Discord: WS stream ended"),
};
let payload: Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(e) => {
warn!("Discord: parse error: {e}");
continue;
}
};
if let Some(s) = payload["s"].as_u64() {
last_sequence = Some(s);
}
let op = payload["op"].as_u64().unwrap_or(255);
match op {
// OP 10 HELLO
10 => {
let ms = payload["d"]["heartbeat_interval"]
.as_u64()
.unwrap_or(41_250);
heartbeat_interval = Duration::from_millis(ms);
heartbeat_ticker = Some(tokio::time::interval(heartbeat_interval));
info!("Discord: HELLO — heartbeat every {ms}ms");
if !identified {
// Intents: GUILD_MESSAGES (1<<9) + DIRECT_MESSAGES (1<<12)
let identify = json!({
"op": 2,
"d": {
"token": self.token,
// GUILDS | GUILD_MESSAGES | DIRECT_MESSAGES | MESSAGE_CONTENT
"intents": (1u32 << 0) | (1u32 << 9) | (1u32 << 12) | (1u32 << 15),
"properties": {
"os": "linux",
"browser": "rsclaw",
"device": "rsclaw",
}
}
});
write
.send(WsMessage::Text(identify.to_string().into()))
.await
.context("Discord: send IDENTIFY")?;
identified = true;
debug!("Discord: sent IDENTIFY");
}
}
// OP 11 HEARTBEAT_ACK
11 => {
debug!("Discord: heartbeat ACK");
}
// OP 1 HEARTBEAT request from server
1 => {
let hb = json!({"op": 1, "d": last_sequence});
let _ = write.send(WsMessage::Text(hb.to_string().into())).await;
}
// OP 0 DISPATCH
0 => {
let event_type = payload["t"].as_str().unwrap_or("");
match event_type {
"READY" => {
let user = &payload["d"]["user"]["username"];
let uid = payload["d"]["user"]["id"].as_str().unwrap_or("");
if !uid.is_empty() {
if let Ok(mut g) = self.bot_user_id.write() {
*g = Some(uid.to_owned());
}
}
info!("Discord: READY as {user}");
}
"MESSAGE_CREATE" => {
let d = &payload["d"];
let is_bot = d["author"]["bot"].as_bool().unwrap_or(false);
if is_bot && !self.allow_bots {
continue;
}
let mut content = d["content"].as_str().unwrap_or("").to_owned();
let channel_id = d["channel_id"].as_str().unwrap_or("").to_owned();
let peer_id = d["author"]["id"].as_str().unwrap_or("").to_owned();
let is_guild = d["guild_id"].is_string();
// Process attachments (images, audio, video, files).
// Images go into `images` so the runtime can hand
// them to the vision model AND so `pending_files`
// gets a chance to fire (analyze vs save prompt).
// Other files go into `files` for the same reason.
// Audio/video still get auto-transcribed inline.
let mut images: Vec<crate::agent::registry::ImageAttachment> =
Vec::new();
let mut files: Vec<crate::agent::registry::FileAttachment> =
Vec::new();
if let Some(attachments) = d["attachments"].as_array() {
for att in attachments {
let url = att["url"].as_str().unwrap_or("");
let filename = att["filename"].as_str().unwrap_or("file");
let content_type = att["content_type"].as_str().unwrap_or("");
if url.is_empty() { continue; }
let download = self.client.get(url).send().await;
let bytes = match download {
Ok(resp) if resp.status().is_success() => {
resp.bytes().await.ok().map(|b| b.to_vec())
}
_ => None,
};
if let Some(bytes) = bytes {
if content_type.starts_with("audio/") || content_type.starts_with("video/") {
match crate::channel::transcription::transcribe_audio(
&self.client, &bytes, filename, content_type,
).await {
Ok(text) => {
info!("Discord: attachment transcribed ({} chars)", text.len());
if !content.is_empty() { content.push('\n'); }
content.push_str(&text);
}
Err(_) => {
if !content.is_empty() { content.push('\n'); }
content.push_str(&format!("[{content_type} attachment: {filename}]"));
}
}
} else if content_type.starts_with("image/") {
use base64::Engine as _;
let b64 = base64::engine::general_purpose::STANDARD
.encode(&bytes);
let mime = if content_type.is_empty() {
"image/png"
} else {
content_type
};
images.push(crate::agent::registry::ImageAttachment {
data: format!("data:{mime};base64,{b64}"),
mime_type: mime.to_owned(),
});
info!(
size = bytes.len(),
%filename,
"Discord: image attachment forwarded for vision"
);
} else {
// Forward as a FileAttachment so
// the runtime's PendingFile flow
// can prompt analyze/save. Also
// keep the inline text extraction
// (PDF/Office/text) so plain Q&A
// works without two roundtrips.
let processed =
discord_process_file(filename, &bytes);
files.push(crate::agent::registry::FileAttachment {
filename: filename.to_owned(),
data: bytes.clone(),
mime_type: if content_type.is_empty() {
"application/octet-stream".to_owned()
} else {
content_type.to_owned()
},
});
if !content.is_empty() { content.push('\n'); }
content.push_str(&processed);
}
} else {
if !content.is_empty() { content.push('\n'); }
content.push_str(&format!("[attachment download failed: {filename}]"));
}
}
}
// Strip a leading bot mention so commands like
// `<@bot_id> /ss` reach is_fast_preparse intact.
let bot_id = self.bot_user_id.read().ok().and_then(|g| g.clone());
if let Some(bid) = bot_id.as_deref() {
content = strip_bot_mention(&content, bid);
}
// Allow `\xxx` as an alias for `/xxx` — Discord
// intercepts a leading `/` for native slash
// commands so users sometimes can't easily type
// /ss / /webshot / /help. Mirrors the Slack
// alias added earlier.
if let Some(rest) = content.strip_prefix('\\') {
if rest.chars().next().is_some_and(|c| c.is_ascii_alphanumeric()) {
content = format!("/{rest}");
}
}
if content.is_empty() { continue; }
debug!(peer = %peer_id, channel = %channel_id, "Discord: MESSAGE_CREATE");
(self.on_message)(peer_id, content, channel_id, is_guild, images, files);
}
_ => {
debug!("Discord: event {event_type}");
}
}
}
_ => {
debug!("Discord: unknown op {op}");
}
}
}
}
}
impl Channel for DiscordChannel {
fn name(&self) -> &str {
"discord"
}
fn send(&self, msg: OutboundMessage) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
let cfg = ChunkConfig {
max_chars: platform_chunk_limit("discord"),
min_chars: 1,
break_preference: BreakPreference::Newline,
};
if !msg.text.is_empty() {
let chunks = chunk_text(&msg.text, &cfg);
for chunk in &chunks {
self.send_chunk(&msg.target_id, chunk).await?;
}
}
// Send image attachments. Two modes:
// - http(s):// URL → embed.image.url (no upload, Discord fetches)
// - data:image/<mime>;base64,... → multipart upload with the
// correct MIME and matching filename extension.
//
// Previously this path only recognised PNG/JPEG data URLs and fell
// back to feeding the entire `data:image/webp;base64,...` string
// (or http URL) into the base64 decoder, producing garbage bytes
// that Discord rendered as a blank attachment.
if !msg.images.is_empty() {
info!(count = msg.images.len(), "discord: sending images");
}
for (idx, image_data) in msg.images.iter().enumerate() {
if image_data.starts_with("http://") || image_data.starts_with("https://") {
let payload = serde_json::json!({
"embeds": [{ "image": { "url": image_data } }],
});
let url = format!(
"{}/channels/{}/messages",
self.api_base, msg.target_id
);
match self
.client
.post(&url)
.header("authorization", self.auth_header())
.header("content-type", "application/json")
.body(payload.to_string())
.send()
.await
{
Ok(resp) if !resp.status().is_success() => {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
warn!(idx, %status, "discord: image embed failed: {body}");
}
Err(e) => warn!(idx, "discord: image embed request failed: {e}"),
Ok(_) => {}
}
continue;
}
let (mime, b64) = parse_data_url(image_data)
.unwrap_or(("image/png", image_data.as_str()));
use base64::Engine;
let bytes = match base64::engine::general_purpose::STANDARD.decode(b64) {
Ok(b) => b,
Err(e) => {
warn!(idx, "discord: base64 decode failed: {e}");
continue;
}
};
let ext = mime_to_ext(mime);
let part = match reqwest::multipart::Part::bytes(bytes)
.file_name(format!("image.{ext}"))
.mime_str(mime)
{
Ok(p) => p,
Err(e) => {
warn!(idx, "discord: build multipart failed: {e}");
continue;
}
};
let form = reqwest::multipart::Form::new()
.part("files[0]", part)
.text(
"payload_json",
serde_json::json!({"content": ""}).to_string(),
);
let url = format!(
"{}/channels/{}/messages",
self.api_base, msg.target_id
);
match self
.client
.post(&url)
.header("authorization", self.auth_header())
.multipart(form)
.send()
.await
{
Ok(resp) if !resp.status().is_success() => {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
warn!(idx, %status, "discord: image upload failed: {body}");
}
Err(e) => warn!(idx, "discord: image upload request failed: {e}"),
Ok(_) => {}
}
}
// Send file attachments via multipart upload. Pass the MIME the
// tool layer attached so Discord can render inline previews for
// video/audio/PDF/etc.; previously this was hardcoded to
// application/octet-stream which made every file show up as a
// generic blob (videos in particular wouldn't play in-line).
for (idx, (filename, mime, path)) in msg.files.iter().enumerate() {
let bytes = match std::fs::read(path) {
Ok(b) => b,
Err(e) => {
warn!(idx, %filename, "discord: file read failed: {e}");
continue;
}
};
let mime_str = pick_file_mime(mime, filename);
let part = match reqwest::multipart::Part::bytes(bytes)
.file_name(filename.clone())
.mime_str(mime_str)
{
Ok(p) => p,
Err(e) => {
warn!(idx, "discord: build multipart failed: {e}");
continue;
}
};
let form = reqwest::multipart::Form::new()
.part("files[0]", part)
.text(
"payload_json",
serde_json::json!({"content": ""}).to_string(),
);
let url = format!(
"{}/channels/{}/messages",
self.api_base, msg.target_id
);
match self
.client
.post(&url)
.header("authorization", self.auth_header())
.multipart(form)
.send()
.await
{
Ok(resp) if !resp.status().is_success() => {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
warn!(idx, %status, "discord: file upload failed: {body}");
}
Err(e) => warn!(idx, "discord: file upload request failed: {e}"),
Ok(_) => info!(idx, %filename, "discord: file sent"),
}
}
Ok(())
})
}
fn run(self: Arc<Self>) -> BoxFuture<'static, Result<()>> {
Box::pin(async move {
let mut backoff = Duration::from_secs(1);
loop {
match self.gateway_loop().await {
Ok(()) => {
info!("Discord gateway loop exited cleanly, reconnecting");
backoff = Duration::from_secs(1);
}
Err(e) => {
warn!(
"Discord gateway error: {e:#}, reconnecting in {}s",
backoff.as_secs()
);
sleep(backoff).await;
backoff = (backoff * 2).min(Duration::from_secs(120));
}
}
}
})
}
}
// ---------------------------------------------------------------------------
// File processing helpers
// ---------------------------------------------------------------------------
fn discord_is_text_file(name: &str) -> bool {
let exts = [
".txt", ".md", ".csv", ".json", ".toml", ".yaml", ".yml", ".xml", ".html",
".rs", ".py", ".js", ".ts", ".go", ".sh", ".log", ".conf", ".cfg", ".c", ".h", ".java",
];
exts.iter().any(|e| name.ends_with(e))
}
fn discord_process_file(filename: &str, bytes: &[u8]) -> String {
let lower = filename.to_lowercase();
if lower.ends_with(".pdf") {
if let Ok(text) = crate::agent::doc::safe_extract_pdf_from_mem(bytes) {
return format!("[PDF: {filename}]\n{}", &text[..text.len().min(20000)]);
}
// Fallback to pdftotext CLI
let tmp = std::env::temp_dir().join(format!("rsclaw_discord_{filename}"));
if std::fs::write(&tmp, bytes).is_ok() {
let output = std::process::Command::new("pdftotext")
.args([tmp.to_str().unwrap_or(""), "-"])
.output();
let _ = std::fs::remove_file(&tmp);
if let Ok(o) = output {
if o.status.success() {
let text = String::from_utf8_lossy(&o.stdout);
return format!("[PDF: {filename}]\n{}", &text[..text.len().min(20000)]);
}
}
format!("[PDF: {filename} ({} bytes)]", bytes.len())
} else {
format!("[file: {filename}]")
}
} else if lower.ends_with(".docx") || lower.ends_with(".xlsx") || lower.ends_with(".pptx") {
if let Some(text) = crate::channel::extract_office_text(filename, bytes) {
let label = if lower.ends_with(".docx") { "Word" }
else if lower.ends_with(".xlsx") { "Excel" }
else { "PowerPoint" };
format!("[{label}: {filename}]\n{}", &text[..text.len().min(20000)])
} else {
let label = if lower.ends_with(".docx") { "Word" }
else if lower.ends_with(".xlsx") { "Excel" }
else { "PowerPoint" };
format!("[{label} file: {filename} ({} bytes)]", bytes.len())
}
} else if discord_is_text_file(&lower) {
let text = String::from_utf8_lossy(bytes);
format!("[File: {filename}]\n```\n{}\n```", &text[..text.len().min(20000)])
} else {
let ws = crate::config::loader::base_dir().join("workspace/uploads");
let _ = std::fs::create_dir_all(&ws);
let dest = ws.join(filename);
let _ = std::fs::write(&dest, bytes);
format!("[File saved: {filename} ({} bytes) at {}]", bytes.len(), dest.display())
}
}
/// Strip a leading `<@bot_id>` or `<@!bot_id>` mention (with surrounding
/// whitespace) from a Discord message body.
///
/// Without this, guild messages like `<@123> /ss` arrive at
/// `is_fast_preparse` with the mention prefix, so the slash command
/// detector returns false and the message is routed through the LLM
/// instead of the local fast path.
pub(crate) fn strip_bot_mention(content: &str, bot_id: &str) -> String {
let trimmed = content.trim_start();
for prefix in [format!("<@{bot_id}>"), format!("<@!{bot_id}>")] {
if let Some(rest) = trimmed.strip_prefix(&prefix) {
return rest.trim_start().to_owned();
}
}
content.to_owned()
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
fn init_crypto() {
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
}
#[test]
fn channel_name() {
init_crypto();
let ch = DiscordChannel::new("token", false, Arc::new(|_, _, _, _, _, _| {}), None, None);
assert_eq!(ch.name(), "discord");
}
#[test]
fn auth_header_format() {
init_crypto();
let ch = DiscordChannel::new("my-token", false, Arc::new(|_, _, _, _, _, _| {}), None, None);
assert_eq!(ch.auth_header(), "Bot my-token");
}
#[test]
fn strip_mention_removes_simple_prefix() {
assert_eq!(strip_bot_mention("<@123> /ss", "123"), "/ss");
}
#[test]
fn strip_mention_removes_nickname_form() {
// Discord's legacy `<@!id>` form (used when the bot has a server nick).
assert_eq!(strip_bot_mention("<@!123> /screenshot", "123"), "/screenshot");
}
#[test]
fn strip_mention_handles_leading_whitespace() {
assert_eq!(strip_bot_mention(" <@123> hello", "123"), "hello");
}
#[test]
fn strip_mention_leaves_other_users_alone() {
// Mention of a different user — must not be stripped.
let s = "<@999> hi";
assert_eq!(strip_bot_mention(s, "123"), s);
}
#[test]
fn strip_mention_noop_when_no_mention() {
assert_eq!(strip_bot_mention("/ss", "123"), "/ss");
}
}