foukoapi 0.1.0-alpha.1

Cross-platform bot framework in Rust. Write your handlers once, run the same bot on Telegram and Discord with shared accounts, embeds, keyboards and SQLite storage.
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
//! Discord adapter built on top of [`serenity`].

use crate::{
    bot::Router,
    ctx::Ctx,
    error::{Error, Result},
    keyboard::{ButtonKind, Embed as FkEmbed, Reply},
    platform::PlatformKind,
};
use async_trait::async_trait;
use serenity::{
    all::{
        ButtonStyle, ChannelId, Command, CommandInteraction, CommandOptionType,
        ComponentInteraction, CreateActionRow, CreateButton, CreateCommand, CreateCommandOption,
        CreateEmbed, CreateEmbedFooter, CreateInteractionResponse,
        CreateInteractionResponseFollowup, CreateInteractionResponseMessage, CreateMessage,
        EditInteractionResponse, GatewayIntents, Interaction, Message, Ready,
    },
    client::{Context as SerenityContext, EventHandler},
    Client,
};
use std::sync::Arc;

/// Start the Discord adapter.
///
/// `commands` is the list of `(name, description)` pairs the bot has
/// registered. The adapter promotes each of them into a native Discord
/// slash command on startup so `/help`, `/menu`, etc. show up in the
/// client's autocomplete and can be invoked as real slash commands.
pub async fn run(
    token: String,
    router: Arc<Router>,
    commands: Vec<(String, Option<String>)>,
) -> Result<()> {
    tracing::info!("starting discord adapter");

    let intents = GatewayIntents::GUILD_MESSAGES
        | GatewayIntents::DIRECT_MESSAGES
        | GatewayIntents::MESSAGE_CONTENT;

    let mut client = Client::builder(&token, intents)
        .event_handler(Handler {
            router,
            commands: Arc::new(commands),
        })
        .await
        .map_err(|e| Error::platform("discord", e))?;

    client
        .start()
        .await
        .map_err(|e| Error::platform("discord", e))?;

    Ok(())
}

struct Handler {
    router: Arc<Router>,
    /// Bot commands to expose as native Discord slash commands. Each
    /// item is `(name_with_slash, description)`.
    commands: Arc<Vec<(String, Option<String>)>>,
}

#[async_trait]
impl EventHandler for Handler {
    async fn ready(&self, ctx: SerenityContext, ready: Ready) {
        tracing::info!(bot = %ready.user.name, "discord adapter ready");

        // Register every bot command as a native Discord slash command.
        // Discord command names must be lowercase ASCII without the
        // leading `/`, so we strip it and skip anything that doesn't
        // translate (e.g. `/8ball` becomes `8ball` which Discord rejects
        // because it starts with a digit - those we silently skip).
        let mut batch: Vec<CreateCommand> = Vec::new();
        for (name, desc) in self.commands.iter() {
            let trimmed = name.trim_start_matches('/').to_ascii_lowercase();
            if trimmed.is_empty() || !is_valid_slash_name(&trimmed) {
                continue;
            }
            let description = desc
                .clone()
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| trimmed.clone());
            // Discord limits descriptions to 100 chars. Truncate safely
            // on char boundaries.
            let description = truncate_chars(&description, 100);
            // Every slash command gets an optional `args` string so the
            // Discord client shows a text field - that's how users type
            // codes for /link, city names for /weather, questions for
            // /8ball etc. The option is optional, so no-arg commands
            // (/ping, /help) stay as simple as ever.
            let opt = CreateCommandOption::new(
                CommandOptionType::String,
                "args",
                "arguments passed to the command (optional)",
            )
            .required(false);
            batch.push(
                CreateCommand::new(trimmed)
                    .description(description)
                    .add_option(opt),
            );
        }
        match Command::set_global_commands(&ctx.http, batch).await {
            Ok(cmds) => {
                tracing::info!(
                    count = cmds.len(),
                    "discord: registered global slash commands"
                );
            }
            Err(e) => {
                tracing::warn!(error = %e, "discord: could not register slash commands");
            }
        }
    }

    async fn message(&self, ctx: SerenityContext, msg: Message) {
        if msg.author.bot {
            return;
        }

        let router = Arc::clone(&self.router);
        let channel_id = msg.channel_id;
        let http = ctx.http.clone();

        // Ask the cache / HTTP for the channel kind. If we can't tell,
        // default to "not DM" to avoid leaking private data into groups.
        let is_dm = detect_dm(&ctx, channel_id).await;

        let reply_fn: crate::ctx::ReplyFn = Box::new(move |reply: Reply| {
            let http = http.clone();
            Box::pin(async move {
                let mut msg = CreateMessage::new();
                if !reply.get_text().is_empty() {
                    msg = msg.content(reply.get_text());
                }
                if let Some(em) = reply.get_embed() {
                    msg = msg.add_embed(to_discord_embed(em));
                }
                if let Some(kb) = reply.get_keyboard() {
                    msg = msg.components(build_rows(kb));
                }
                channel_id
                    .send_message(&http, msg)
                    .await
                    .map_err(|e| Error::platform("discord", e))?;
                Ok(())
            })
        });

        let fouko_ctx = Ctx::new_full(
            PlatformKind::Discord,
            channel_id.to_string(),
            msg.author.id.to_string(),
            msg.content.clone(),
            reply_fn,
            Some(is_dm),
            None,
        );

        if let Err(e) = router.dispatch(fouko_ctx).await {
            tracing::warn!(error = %e, "discord handler error");
        }
    }

    async fn interaction_create(&self, ctx: SerenityContext, interaction: Interaction) {
        match interaction {
            Interaction::Component(component) => {
                handle_component(&ctx, &self.router, component).await;
            }
            Interaction::Command(command) => {
                handle_command(&ctx, &self.router, command).await;
            }
            _ => {}
        }
    }
}

/// Treat a Discord slash-command invocation as if the user had typed
/// `/<name> <args>` into the chat, then forward it to the router.
async fn handle_command(ctx: &SerenityContext, router: &Router, command: CommandInteraction) {
    let channel_id = command.channel_id;
    let user_id = command.user.id.to_string();
    let is_dm = detect_dm(ctx, channel_id).await;

    // Stitch `/<name> <arg1> <arg2> ...` back together so the dispatch
    // layer sees what it would see from a real text message.
    let mut text = format!("/{}", command.data.name);
    for opt in &command.data.options {
        if let Some(v) = opt.value.as_str() {
            text.push(' ');
            text.push_str(v);
        }
    }

    // Defer the interaction so Discord knows we're working on it.
    // The first reply the handler sends replaces the "…" placeholder,
    // every next one comes through as a followup. That way buttons
    // that live on an embed stay attached to the same message as the
    // slash-command answer itself, and secondary messages (like a
    // "linked!" confirmation after /link CODE) still show up.
    let defer = CreateInteractionResponse::Defer(CreateInteractionResponseMessage::new());
    if let Err(e) = command.create_response(&ctx.http, defer).await {
        tracing::debug!(error = %e, "discord slash-cmd defer failed");
    }

    let http = ctx.http.clone();
    let cmd_clone = command.clone();
    let first_call = Arc::new(std::sync::atomic::AtomicBool::new(true));
    let reply_fn: crate::ctx::ReplyFn = Box::new(move |reply: Reply| {
        let http = http.clone();
        let command = cmd_clone.clone();
        let first = first_call.clone();
        Box::pin(async move {
            // First reply: edit the defered message so the slash-command
            // "bot is thinking…" placeholder turns into the real answer.
            // Every subsequent reply becomes a followup.
            let is_first = first
                .compare_exchange(
                    true,
                    false,
                    std::sync::atomic::Ordering::SeqCst,
                    std::sync::atomic::Ordering::SeqCst,
                )
                .is_ok();
            if is_first {
                let mut edit = EditInteractionResponse::new();
                if !reply.get_text().is_empty() {
                    edit = edit.content(reply.get_text());
                }
                if let Some(em) = reply.get_embed() {
                    edit = edit.embed(to_discord_embed(em));
                }
                if let Some(kb) = reply.get_keyboard() {
                    edit = edit.components(build_rows(kb));
                }
                command
                    .edit_response(&http, edit)
                    .await
                    .map_err(|e| Error::platform("discord", e))?;
            } else {
                let mut follow = CreateInteractionResponseFollowup::new();
                if !reply.get_text().is_empty() {
                    follow = follow.content(reply.get_text());
                }
                if let Some(em) = reply.get_embed() {
                    follow = follow.add_embed(to_discord_embed(em));
                }
                if let Some(kb) = reply.get_keyboard() {
                    follow = follow.components(build_rows(kb));
                }
                command
                    .create_followup(&http, follow)
                    .await
                    .map_err(|e| Error::platform("discord", e))?;
            }
            Ok(())
        })
    });

    let fouko_ctx = Ctx::new_full(
        PlatformKind::Discord,
        channel_id.to_string(),
        user_id,
        text,
        reply_fn,
        Some(is_dm),
        None,
    );

    if let Err(e) = router.dispatch(fouko_ctx).await {
        tracing::warn!(error = %e, "discord slash-cmd handler error");
    }
}

/// Handle a button / select press the same way we handle messages,
/// routing the custom-id back through the router as `callback_data`.
///
/// The incoming `component` interaction is deferred (so Discord stops
/// the spinner) and then the handler is free to either:
///
/// - send followups against the interaction token (`ctx.reply`), which
///   post fresh messages in the same channel, or
/// - edit the **original** message that carried the pressed button
///   (`ctx.edit_reply`), wiping or replacing its text/keyboard.
async fn handle_component(ctx: &SerenityContext, router: &Router, component: ComponentInteraction) {
    let channel_id = component.channel_id;
    let http = ctx.http.clone();
    let data = component.data.custom_id.clone();
    let user_id = component.user.id.to_string();
    let is_dm = detect_dm(ctx, channel_id).await;

    // Defer the component update so Discord stops the "thinking" spinner
    // on the button. DeferredUpdateMessage keeps the original message
    // intact - we can still edit it via edit_response.
    let defer = CreateInteractionResponse::Acknowledge;
    if let Err(e) = component.create_response(&http, defer).await {
        tracing::debug!(error = %e, "discord component defer failed");
    }

    let http_for_reply = http.clone();
    let comp_for_reply = component.clone();
    let reply_fn: crate::ctx::ReplyFn = Box::new(move |reply: Reply| {
        let http = http_for_reply.clone();
        let comp = comp_for_reply.clone();
        Box::pin(async move {
            // Send as a followup so the reply belongs to the same
            // interaction. That's how buttons "produce" new messages
            // in Discord; plain channel_id.send_message would work but
            // would show the bot posting out of the blue instead of
            // being tied to the user's click.
            let mut follow = CreateInteractionResponseFollowup::new();
            if !reply.get_text().is_empty() {
                follow = follow.content(reply.get_text());
            }
            if let Some(em) = reply.get_embed() {
                follow = follow.add_embed(to_discord_embed(em));
            }
            if let Some(kb) = reply.get_keyboard() {
                follow = follow.components(build_rows(kb));
            }
            comp.create_followup(&http, follow)
                .await
                .map_err(|e| Error::platform("discord", e))?;
            Ok(())
        })
    });

    // Edit callback: rewrite the message that carried the button.
    let http_for_edit = http.clone();
    let comp_for_edit = component.clone();
    let edit_fn: crate::ctx::EditFn = Arc::new(move |reply: Reply| {
        let http = http_for_edit.clone();
        let comp = comp_for_edit.clone();
        Box::pin(async move {
            let mut edit = serenity::all::EditMessage::new();
            // Always clear embeds/components first so stale ones don't
            // linger when the new reply doesn't include them.
            edit = edit.content(reply.get_text().to_string());
            let mut embeds = Vec::new();
            if let Some(em) = reply.get_embed() {
                embeds.push(to_discord_embed(em));
            }
            edit = edit.embeds(embeds);
            let components = match reply.get_keyboard() {
                Some(kb) => build_rows(kb),
                None => Vec::new(),
            };
            edit = edit.components(components);
            let mut msg = comp.message.clone();
            msg.edit(&http, edit)
                .await
                .map_err(|e| Error::platform("discord", e))?;
            Ok(())
        })
    });

    let fouko_ctx = Ctx::new_with_edit(
        PlatformKind::Discord,
        channel_id.to_string(),
        user_id,
        data.clone(),
        reply_fn,
        Some(is_dm),
        Some(data),
        Some(edit_fn),
    );

    if let Err(e) = router.dispatch(fouko_ctx).await {
        tracing::warn!(error = %e, "discord interaction handler error");
    }
}

fn build_rows(kb: &crate::keyboard::Keyboard) -> Vec<CreateActionRow> {
    kb.rows()
        .iter()
        .map(|row| {
            let buttons: Vec<CreateButton> = row
                .iter()
                .map(|b| match &b.kind {
                    ButtonKind::Callback(id) => CreateButton::new(id.clone())
                        .label(b.label())
                        .style(ButtonStyle::Primary),
                    ButtonKind::Url(u) => CreateButton::new_link(u.clone()).label(b.label()),
                })
                .collect();
            CreateActionRow::Buttons(buttons)
        })
        .collect()
}

/// Discord requires slash-command names to start with a letter and only
/// contain `[a-z0-9_-]`. Everything else (starting with a digit like
/// `8ball`, containing spaces, etc.) is rejected server-side, so we
/// filter out non-conforming names before the register call.
fn is_valid_slash_name(s: &str) -> bool {
    let mut chars = s.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !first.is_ascii_lowercase() {
        return false;
    }
    chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
        && s.len() <= 32
}

/// Truncate `s` to at most `max_chars` Unicode characters without
/// slicing in the middle of a multi-byte codepoint.
fn truncate_chars(s: &str, max_chars: usize) -> String {
    let mut out = String::new();
    for (i, ch) in s.chars().enumerate() {
        if i >= max_chars {
            break;
        }
        out.push(ch);
    }
    out
}

async fn detect_dm(ctx: &SerenityContext, channel_id: ChannelId) -> bool {
    // Fetch the channel via HTTP. If the lookup fails, we conservatively
    // say "not DM" - better silent than leaking private data into a guild.
    match channel_id.to_channel(&ctx.http).await {
        Ok(ch) => ch.private().is_some(),
        Err(_) => false,
    }
}

/// Translate a cross-platform [`FkEmbed`] into a [`CreateEmbed`] that
/// serenity knows how to send.
fn to_discord_embed(src: &FkEmbed) -> CreateEmbed {
    let mut em = CreateEmbed::new();
    if let Some(t) = src.get_title() {
        em = em.title(t);
    }
    if let Some(u) = src.get_url() {
        em = em.url(u);
    }
    if let Some(d) = src.get_description() {
        em = em.description(d);
    }
    if let Some(c) = src.get_color() {
        em = em.colour(c);
    }
    for f in src.get_fields() {
        em = em.field(f.name(), f.value(), f.is_inline());
    }
    if let Some(url) = src.get_image() {
        em = em.image(url);
    }
    if let Some(url) = src.get_thumbnail() {
        em = em.thumbnail(url);
    }
    if let Some(foot) = src.get_footer() {
        em = em.footer(CreateEmbedFooter::new(foot));
    }
    em
}