foukoapi 0.1.2-alpha.2

Cross-platform bot framework in Rust: one codebase, many platforms. Shared accounts, embeds, keyboards, economy, i18n and pluggable storage; Telegram and Discord adapters included.
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
//! Cross-platform buttons, keyboards and rich "embed" replies.
//!
//! Every supported platform has a notion of an "attach me to a message"
//! button: Telegram has inline keyboards, Discord has message components,
//! Matrix has plain message reactions / buttons in custom event types.
//!
//! FoukoApi gives you one type ([`Keyboard`]) that every adapter converts
//! into the platform's native equivalent.
//!
//! For pretty output there's also [`Embed`] - a platform-agnostic
//! description of "title + body + some labelled fields + footer". On
//! Discord it turns into a real embed. Elsewhere adapters render it as
//! nicely-formatted text (HTML on Telegram, Markdown/HTML on Matrix).

/// Hard cap for raw image bytes attached via [`Reply::image_bytes`].
/// Discord allows 8 MB on a regular server and Telegram 10 MB per photo,
/// so 8 MB keeps one reply portable across both.
pub(crate) const MAX_IMAGE_BYTES: usize = 8 * 1024 * 1024;

/// Hard cap for raw video/audio bytes attached via [`Reply::video_bytes`]
/// / [`Reply::audio_bytes`]. Telegram bots may upload up to 50 MB, so the
/// shared cap sits at 25 MiB; Discord regular servers still stop at 8 MiB,
/// which its adapter enforces separately at send time.
pub(crate) const MAX_MEDIA_BYTES: usize = 25 * 1024 * 1024;

/// What kind of media a raw-bytes attachment carries. Decides both the
/// size cap and the native send path each adapter picks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AttachmentKind {
    Photo,
    Video,
    Audio,
}

/// Reject attachments over their kind's cap ([`MAX_IMAGE_BYTES`] for
/// photos, [`MAX_MEDIA_BYTES`] for video/audio). Adapters call this at
/// send time - media can't be usefully truncated, so oversize is an error.
pub(crate) fn check_attachment_size(
    bytes: &[u8],
    kind: AttachmentKind,
) -> crate::error::Result<()> {
    let (max, noun) = match kind {
        AttachmentKind::Photo => (MAX_IMAGE_BYTES, "image"),
        AttachmentKind::Video => (MAX_MEDIA_BYTES, "video"),
        AttachmentKind::Audio => (MAX_MEDIA_BYTES, "audio"),
    };
    if bytes.len() > max {
        tracing::warn!(len = bytes.len(), max, "{noun} attachment too large");
        return Err(crate::error::Error::Other(format!(
            "{noun} too large: {} bytes (max {max})",
            bytes.len()
        )));
    }
    Ok(())
}

/// One button inside a [`Keyboard`].
#[derive(Debug, Clone)]
pub struct Button {
    pub(crate) label: String,
    pub(crate) kind: ButtonKind,
}

#[derive(Debug, Clone)]
pub(crate) enum ButtonKind {
    /// Clicking sends a callback with this id back to the bot.
    Callback(String),
    /// Clicking opens this URL in the user's browser.
    Url(String),
    /// Clicking opens a Telegram Mini App at this URL. Platforms without
    /// an equivalent render it as a plain link.
    WebApp(String),
}

impl Button {
    /// Callback button. `id` is what comes back when the user presses it.
    pub fn callback(label: impl Into<String>, id: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            kind: ButtonKind::Callback(id.into()),
        }
    }

    /// Link button. The user's client opens the URL when pressed.
    pub fn url(label: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            kind: ButtonKind::Url(url.into()),
        }
    }

    /// A button that opens a Telegram Mini App at `url`. On platforms
    /// without an equivalent (Discord) it degrades to a plain link.
    /// Telegram only shows web_app buttons in private chats.
    pub fn web_app(label: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            kind: ButtonKind::WebApp(url.into()),
        }
    }

    /// The label shown on the button.
    pub fn label(&self) -> &str {
        &self.label
    }

    /// The callback id, if this is a callback button.
    pub fn callback_id(&self) -> Option<&str> {
        match &self.kind {
            ButtonKind::Callback(id) => Some(id.as_str()),
            _ => None,
        }
    }

    /// The target url, if this is a url button.
    pub fn url_target(&self) -> Option<&str> {
        match &self.kind {
            ButtonKind::Url(u) => Some(u.as_str()),
            _ => None,
        }
    }

    /// The Mini App url, if this is a web_app button.
    pub fn web_app_url(&self) -> Option<&str> {
        match &self.kind {
            ButtonKind::WebApp(u) => Some(u.as_str()),
            _ => None,
        }
    }
}

/// A grid of [`Button`]s attached to a message.
///
/// Rows are vecs of buttons; the outer vec is the list of rows.
#[derive(Debug, Clone, Default)]
pub struct Keyboard {
    pub(crate) rows: Vec<Vec<Button>>,
}

impl Keyboard {
    /// Start a new, empty keyboard.
    pub fn new() -> Self {
        Self { rows: Vec::new() }
    }

    /// Append a row of buttons.
    pub fn row(mut self, buttons: impl IntoIterator<Item = Button>) -> Self {
        self.rows.push(buttons.into_iter().collect());
        self
    }

    /// Access the stored rows (useful for adapters).
    pub fn rows(&self) -> &[Vec<Button>] {
        &self.rows
    }

    /// Total number of buttons on the keyboard.
    pub fn len(&self) -> usize {
        self.rows.iter().map(|r| r.len()).sum()
    }

    /// `true` if there are no buttons at all.
    pub fn is_empty(&self) -> bool {
        self.rows.iter().all(|r| r.is_empty())
    }
}

/// One labelled row inside an [`Embed`].
#[derive(Debug, Clone)]
pub struct EmbedField {
    pub(crate) name: String,
    pub(crate) value: String,
    /// When `true`, adapters that support it (Discord) try to lay the
    /// field out side-by-side with its neighbours.
    pub(crate) inline: bool,
}

impl EmbedField {
    /// New field with the given name/value. Not inline by default.
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
            inline: false,
        }
    }

    /// Mark this field as inline (Discord side-by-side layout).
    pub fn inline(mut self, yes: bool) -> Self {
        self.inline = yes;
        self
    }

    /// The field's label.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The field's body text.
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Whether the adapter should try to render this field inline.
    pub fn is_inline(&self) -> bool {
        self.inline
    }
}

/// A platform-agnostic pretty-printed block.
///
/// Every field is optional. Adapters render whichever bits are present:
/// Discord builds a real embed, Telegram uses HTML, Matrix uses an HTML
/// body with a plain-text fallback. Keep `title` short and `description`
/// meaningful; the rest is sprinkles.
#[derive(Debug, Clone, Default)]
pub struct Embed {
    pub(crate) title: Option<String>,
    pub(crate) description: Option<String>,
    pub(crate) fields: Vec<EmbedField>,
    pub(crate) footer: Option<String>,
    /// Accent colour as a 0xRRGGBB integer. Discord-only, ignored
    /// elsewhere.
    pub(crate) color: Option<u32>,
    pub(crate) url: Option<String>,
    /// Big picture rendered under the description. Discord shows it as
    /// part of the embed; Telegram/Matrix append it as a plain URL the
    /// client link-previews.
    pub(crate) image_url: Option<String>,
    /// Small thumbnail in the top-right of the embed. Discord only.
    pub(crate) thumbnail_url: Option<String>,
}

impl Embed {
    /// Start a new, empty embed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Title (top of the embed).
    pub fn title(mut self, t: impl Into<String>) -> Self {
        self.title = Some(t.into());
        self
    }

    /// Main body text.
    pub fn description(mut self, d: impl Into<String>) -> Self {
        self.description = Some(d.into());
        self
    }

    /// Add one labelled field.
    pub fn field(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.push(EmbedField::new(name, value));
        self
    }

    /// Add one labelled field laid out inline (side by side on Discord).
    pub fn field_inline(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.push(EmbedField::new(name, value).inline(true));
        self
    }

    /// Append an already-built field.
    pub fn push_field(mut self, field: EmbedField) -> Self {
        self.fields.push(field);
        self
    }

    /// Footer text (small line at the bottom).
    pub fn footer(mut self, f: impl Into<String>) -> Self {
        self.footer = Some(f.into());
        self
    }

    /// Accent colour as `0xRRGGBB`. Only Discord actually paints it.
    pub fn color(mut self, rgb: u32) -> Self {
        self.color = Some(rgb & 0x00FF_FFFF);
        self
    }

    /// Hyperlink the title to a URL. Discord-only, silently ignored
    /// elsewhere.
    pub fn url(mut self, u: impl Into<String>) -> Self {
        self.url = Some(u.into());
        self
    }

    /// Big image under the description. Shown as a real embed image on
    /// Discord; Telegram/Matrix tack it on as a preview-friendly URL.
    pub fn image(mut self, url: impl Into<String>) -> Self {
        self.image_url = Some(url.into());
        self
    }

    /// Small thumbnail in the corner. Discord-only (elsewhere ignored).
    pub fn thumbnail(mut self, url: impl Into<String>) -> Self {
        self.thumbnail_url = Some(url.into());
        self
    }

    /// Title, if any.
    pub fn get_title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Description, if any.
    pub fn get_description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// All fields in the order they were added.
    pub fn get_fields(&self) -> &[EmbedField] {
        &self.fields
    }

    /// Footer, if any.
    pub fn get_footer(&self) -> Option<&str> {
        self.footer.as_deref()
    }

    /// Accent colour, if any.
    pub fn get_color(&self) -> Option<u32> {
        self.color
    }

    /// Title URL, if any.
    pub fn get_url(&self) -> Option<&str> {
        self.url.as_deref()
    }

    /// Big-image URL, if any.
    pub fn get_image(&self) -> Option<&str> {
        self.image_url.as_deref()
    }

    /// Thumbnail URL, if any.
    pub fn get_thumbnail(&self) -> Option<&str> {
        self.thumbnail_url.as_deref()
    }

    /// `true` when every slot is empty.
    pub fn is_empty(&self) -> bool {
        self.title.is_none()
            && self.description.is_none()
            && self.fields.is_empty()
            && self.footer.is_none()
    }
}

/// A reply you want to send from a handler: optional text, optional
/// embed, optional keyboard.
///
/// Returned by convenience builders; `Ctx::reply_with` takes one.
#[derive(Debug, Clone, Default)]
pub struct Reply {
    pub(crate) text: String,
    pub(crate) embed: Option<Embed>,
    pub(crate) keyboard: Option<Keyboard>,
    /// When `true`, adapters send the text verbatim instead of converting
    /// the bot's markdown (`` `code` ``, `**bold**`, links) into the
    /// platform's formatting. Off by default.
    pub(crate) raw: bool,
    /// Raw media bytes plus a filename and kind, sent as a native
    /// photo/video/audio or attachment. One per reply; the last
    /// `image_bytes`/`video_bytes`/`audio_bytes` call wins.
    pub(crate) attachment: Option<(Vec<u8>, String, AttachmentKind)>,
}

impl Reply {
    /// Start a reply with just text.
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            ..Self::default()
        }
    }

    /// Start a reply with just an [`Embed`].
    pub fn embed(embed: Embed) -> Self {
        Self {
            embed: Some(embed),
            ..Self::default()
        }
    }

    /// Replace (or add) the embed attached to this reply.
    pub fn with_embed(mut self, embed: Embed) -> Self {
        self.embed = Some(embed);
        self
    }

    /// Attach a keyboard.
    pub fn keyboard(mut self, kb: Keyboard) -> Self {
        self.keyboard = Some(kb);
        self
    }

    /// Replace the body text.
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.text = text.into();
        self
    }

    /// Body text.
    pub fn get_text(&self) -> &str {
        &self.text
    }

    /// Send the text exactly as written, without markdown-to-platform
    /// conversion. Use this when you want literal backticks/asterisks.
    pub fn raw(mut self, raw: bool) -> Self {
        self.raw = raw;
        self
    }

    /// Whether this reply opted out of markdown conversion.
    pub fn is_raw(&self) -> bool {
        self.raw
    }

    /// Attach an image by raw bytes; sent as a native photo/attachment.
    ///
    /// Handy for AI-generated pictures that arrive as base64: decode and
    /// pass the bytes here instead of hosting them somewhere for a URL.
    /// Text and/or embed on the same reply become the caption; a keyboard
    /// sticks to the photo message. Adapters reject images over 8 MB with
    /// `Error::Other` at send time. A reply carries at most one raw
    /// attachment: this replaces any earlier video/audio bytes.
    pub fn image_bytes(mut self, bytes: Vec<u8>, filename: impl Into<String>) -> Self {
        self.attachment = Some((bytes, filename.into(), AttachmentKind::Photo));
        self
    }

    /// Attach a video by raw bytes; sent as a native video on Telegram
    /// and a plain file attachment on Discord.
    ///
    /// Text and/or embed on the same reply become the caption on
    /// Telegram; on Discord the file rides next to the message (no
    /// embed preview). The shared cap is 25 MiB, but Discord regular
    /// servers only accept 8 MiB - its adapter rejects bigger files
    /// with `Error::Other` at send time. Replaces any earlier
    /// image/audio bytes on the same reply.
    pub fn video_bytes(mut self, bytes: Vec<u8>, filename: impl Into<String>) -> Self {
        self.attachment = Some((bytes, filename.into(), AttachmentKind::Video));
        self
    }

    /// Attach an audio track by raw bytes; sent via `sendAudio` on
    /// Telegram (the music-player bubble showing the filename, unlike
    /// `sendVoice` which renders a round voice note) and a plain file
    /// attachment on Discord.
    ///
    /// Same limits as [`Reply::video_bytes`]: 25 MiB overall, 8 MiB on
    /// Discord. Replaces any earlier image/video bytes on the same reply.
    pub fn audio_bytes(mut self, bytes: Vec<u8>, filename: impl Into<String>) -> Self {
        self.attachment = Some((bytes, filename.into(), AttachmentKind::Audio));
        self
    }

    /// Attached raw image, if any: `(bytes, filename)`. Only reports
    /// photo attachments; video/audio come back through the adapters'
    /// generic attachment path.
    pub fn get_image_bytes(&self) -> Option<(&[u8], &str)> {
        match &self.attachment {
            Some((b, n, AttachmentKind::Photo)) => Some((b.as_slice(), n.as_str())),
            _ => None,
        }
    }

    /// Attached raw media of any kind, if any: `(bytes, filename, kind)`.
    pub(crate) fn get_attachment(&self) -> Option<(&[u8], &str, AttachmentKind)> {
        self.attachment
            .as_ref()
            .map(|(b, n, k)| (b.as_slice(), n.as_str(), *k))
    }

    /// Attached embed, if any.
    pub fn get_embed(&self) -> Option<&Embed> {
        self.embed.as_ref()
    }

    /// Attached keyboard, if any.
    pub fn get_keyboard(&self) -> Option<&Keyboard> {
        self.keyboard.as_ref()
    }
}

impl From<&str> for Reply {
    fn from(s: &str) -> Self {
        Self::text(s)
    }
}
impl From<String> for Reply {
    fn from(s: String) -> Self {
        Self::text(s)
    }
}
impl From<Embed> for Reply {
    fn from(e: Embed) -> Self {
        Self::embed(e)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn image_bytes_is_stored() {
        let reply = Reply::text("look").image_bytes(vec![1, 2, 3], "pic.png");
        let (bytes, name) = reply.get_image_bytes().expect("image should be set");
        assert_eq!(bytes, &[1, 2, 3]);
        assert_eq!(name, "pic.png");
    }

    #[test]
    fn image_bytes_absent_by_default() {
        assert!(Reply::text("hi").get_image_bytes().is_none());
        assert!(Reply::embed(Embed::new()).get_image_bytes().is_none());
    }

    #[test]
    fn image_size_within_cap_is_ok() {
        assert!(check_attachment_size(&[0u8; 16], AttachmentKind::Photo).is_ok());
        assert!(check_attachment_size(&vec![0u8; MAX_IMAGE_BYTES], AttachmentKind::Photo).is_ok());
    }

    #[test]
    fn image_size_over_cap_is_rejected() {
        let err = check_attachment_size(&vec![0u8; MAX_IMAGE_BYTES + 1], AttachmentKind::Photo)
            .unwrap_err();
        assert!(matches!(err, crate::error::Error::Other(_)));
        assert!(err.to_string().contains("image too large"));
    }

    #[test]
    fn media_size_within_cap_is_ok() {
        assert!(check_attachment_size(&vec![0u8; MAX_MEDIA_BYTES], AttachmentKind::Video).is_ok());
        assert!(check_attachment_size(&vec![0u8; MAX_MEDIA_BYTES], AttachmentKind::Audio).is_ok());
    }

    #[test]
    fn media_size_over_cap_is_rejected() {
        let err = check_attachment_size(&vec![0u8; MAX_MEDIA_BYTES + 1], AttachmentKind::Video)
            .unwrap_err();
        assert!(err.to_string().contains("video too large"));
        let err = check_attachment_size(&vec![0u8; MAX_MEDIA_BYTES + 1], AttachmentKind::Audio)
            .unwrap_err();
        assert!(err.to_string().contains("audio too large"));
    }

    #[test]
    fn video_bytes_is_stored() {
        let reply = Reply::text("watch").video_bytes(vec![4, 5], "clip.mp4");
        let (bytes, name, kind) = reply.get_attachment().expect("video should be set");
        assert_eq!(bytes, &[4, 5]);
        assert_eq!(name, "clip.mp4");
        assert_eq!(kind, AttachmentKind::Video);
        // Not a photo, so the photo accessor stays empty.
        assert!(reply.get_image_bytes().is_none());
    }

    #[test]
    fn audio_bytes_is_stored() {
        let reply = Reply::text("listen").audio_bytes(vec![7], "song.mp3");
        let (bytes, name, kind) = reply.get_attachment().expect("audio should be set");
        assert_eq!(bytes, &[7]);
        assert_eq!(name, "song.mp3");
        assert_eq!(kind, AttachmentKind::Audio);
        assert!(reply.get_image_bytes().is_none());
    }

    #[test]
    fn last_attachment_wins() {
        let reply = Reply::text("x")
            .image_bytes(vec![1], "a.png")
            .video_bytes(vec![2], "b.mp4")
            .audio_bytes(vec![3], "c.mp3");
        let (bytes, name, kind) = reply.get_attachment().expect("attachment should be set");
        assert_eq!(bytes, &[3]);
        assert_eq!(name, "c.mp3");
        assert_eq!(kind, AttachmentKind::Audio);

        let reply = Reply::text("y")
            .audio_bytes(vec![3], "c.mp3")
            .image_bytes(vec![1], "a.png");
        let (bytes, name) = reply.get_image_bytes().expect("photo should win");
        assert_eq!(bytes, &[1]);
        assert_eq!(name, "a.png");
    }

    #[test]
    fn web_app_button_keeps_kind() {
        let btn = Button::web_app("Open app", "https://app.example.com/game");
        assert_eq!(btn.label(), "Open app");
        assert_eq!(btn.web_app_url(), Some("https://app.example.com/game"));
        assert!(btn.callback_id().is_none());
        assert!(btn.url_target().is_none());
        // Other kinds don't leak into the web_app accessor.
        assert!(Button::url("x", "https://x.example")
            .web_app_url()
            .is_none());
        assert!(Button::callback("y", "y").web_app_url().is_none());
    }

    #[test]
    fn image_bytes_combines_with_embed_and_keyboard() {
        let reply = Reply::embed(Embed::new().title("t"))
            .keyboard(Keyboard::new().row([Button::callback("ok", "ok")]))
            .image_bytes(vec![9], "gen.jpg");
        assert!(reply.get_embed().is_some());
        assert!(reply.get_keyboard().is_some());
        assert!(reply.get_image_bytes().is_some());
    }
}