foukoapi 0.1.1-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
//! Context passed to every command handler.

use crate::{keyboard::Reply, platform::PlatformKind, Result};
use std::sync::Arc;

/// A lightweight handle to an incoming update.
///
/// A `Ctx` is what every handler receives. It exposes the platform the
/// message came from, the raw text, and a [`reply`](Ctx::reply) helper
/// that sends a message back through the same platform. For updates
/// that came from a button press it also carries an optional
/// [`edit_reply`](Ctx::edit_reply) that rewrites the original message
/// in place instead of sending a new one.
#[derive(Clone)]
pub struct Ctx {
    pub(crate) inner: Arc<CtxInner>,
}

pub(crate) struct CtxInner {
    pub(crate) platform: PlatformKind,
    pub(crate) chat_id: String,
    pub(crate) user_id: String,
    pub(crate) text: String,
    pub(crate) reply_fn: ReplyFn,
    /// Display name of the sender, when the adapter provides one (Telegram
    /// first name / username, Discord global or user name). `None` if
    /// unknown.
    pub(crate) user_name: Option<String>,
    /// `true` when this message is a reply to one of the bot's own
    /// messages. Lets handlers treat "replying to the bot" as addressing
    /// it directly.
    pub(crate) is_reply_to_bot: bool,
    /// `Some(true)` / `Some(false)` when the adapter knows for sure,
    /// `None` when it doesn't. Handlers that need a definitive answer
    /// should fall back to chat_id/user_id heuristics themselves.
    pub(crate) is_dm: Option<bool>,
    /// When this update came from a button press, the callback id the
    /// adapter associated with the pressed button. `None` for regular
    /// text messages.
    pub(crate) callback_data: Option<String>,
    /// When the update came from a button press, this callback lets a
    /// handler rewrite the **bot's own message** that carried the
    /// button, instead of sending a new message. Adapters set it only
    /// on callback updates where the original message is still
    /// reachable.
    pub(crate) edit_fn: Option<EditFn>,
    /// Optional lookup for the sending user's avatar URL.
    pub(crate) avatar_fn: Option<UrlFn>,
    /// Optional lookup for the sending user's banner URL (may hit the
    /// network on platforms that don't include it in the event).
    pub(crate) banner_fn: Option<UrlFn>,
    /// Optional lookup for chat/server info.
    pub(crate) chatinfo_fn: Option<ChatInfoFn>,
    /// Optional "user, I'm working on it" typing indicator.
    pub(crate) typing_fn: Option<TypingFn>,
    /// Optional self-deleting message sender for transient notices.
    pub(crate) temp_reply_fn: Option<TempReplyFn>,
    /// Optional lookup of another user's avatar by id.
    pub(crate) user_avatar_fn: Option<UserUrlFn>,
}

/// Adapter-provided send callback. Takes a fully built [`Reply`] and sends
/// it back through the underlying platform.
pub type ReplyFn =
    Box<dyn Fn(Reply) -> futures::future::BoxFuture<'static, Result<()>> + Send + Sync + 'static>;

/// Adapter-provided edit callback. Rewrites the bot's message that
/// carried the button the user just pressed.
pub type EditFn =
    Arc<dyn Fn(Reply) -> futures::future::BoxFuture<'static, Result<()>> + Send + Sync + 'static>;

/// Adapter-provided lookup returning an optional URL (avatar, banner, ...).
/// Resolves to `None` when the platform can't supply one.
pub type UrlFn =
    Arc<dyn Fn() -> futures::future::BoxFuture<'static, Result<Option<String>>> + Send + Sync>;

/// Adapter-provided lookup for chat/server info.
pub type ChatInfoFn =
    Arc<dyn Fn() -> futures::future::BoxFuture<'static, Result<ChatInfo>> + Send + Sync>;
/// Adapter-provided "show a typing indicator" callback.
pub type TypingFn = Arc<dyn Fn() -> futures::future::BoxFuture<'static, Result<()>> + Send + Sync>;

/// Adapter-provided "send a message that deletes itself" callback. Takes
/// the reply and how long it should live, in seconds.
pub type TempReplyFn =
    Arc<dyn Fn(Reply, u64) -> futures::future::BoxFuture<'static, Result<()>> + Send + Sync>;

/// Adapter-provided lookup for another user's avatar URL by their id.
/// May hit the network. Resolves to `None` when the user can't be found
/// or the platform doesn't expose avatars.
pub type UserUrlFn = Arc<
    dyn Fn(String) -> futures::future::BoxFuture<'static, Result<Option<String>>> + Send + Sync,
>;

/// Cross-platform snapshot of the chat/server a command ran in.
///
/// Filled by [`Ctx::chat_info`]. Fields an adapter can't determine are
/// left `None`, so a handler renders whatever is present.
#[derive(Debug, Clone, Default)]
pub struct ChatInfo {
    /// Platform id of the chat/guild.
    pub id: String,
    /// Display name / title, if any.
    pub title: Option<String>,
    /// Approximate member count, if the platform reports one.
    pub member_count: Option<u64>,
    /// Icon / avatar URL for the chat, if any.
    pub icon_url: Option<String>,
    /// Description / topic, if any.
    pub description: Option<String>,
    /// Whether this is a one-to-one/private chat rather than a group/guild.
    pub is_private: bool,
}

impl Ctx {
    /// Build a `Ctx` from its parts. Adapters use this when they receive an
    /// update from their underlying client.
    pub fn new(
        platform: PlatformKind,
        chat_id: impl Into<String>,
        user_id: impl Into<String>,
        text: impl Into<String>,
        reply_fn: ReplyFn,
    ) -> Self {
        Self {
            inner: Arc::new(CtxInner {
                platform,
                chat_id: chat_id.into(),
                user_id: user_id.into(),
                text: text.into(),
                reply_fn,
                user_name: None,
                is_reply_to_bot: false,
                is_dm: None,
                callback_data: None,
                edit_fn: None,
                avatar_fn: None,
                banner_fn: None,
                chatinfo_fn: None,
                typing_fn: None,
                temp_reply_fn: None,
                user_avatar_fn: None,
            }),
        }
    }

    /// Builder-style variant of [`Ctx::new`] that also records whether the
    /// update came from a direct message. Adapters that can tell for sure
    /// should use this; others keep passing `None` via [`Ctx::new`].
    pub fn new_full(
        platform: PlatformKind,
        chat_id: impl Into<String>,
        user_id: impl Into<String>,
        text: impl Into<String>,
        reply_fn: ReplyFn,
        is_dm: Option<bool>,
        callback_data: Option<String>,
    ) -> Self {
        Self {
            inner: Arc::new(CtxInner {
                platform,
                chat_id: chat_id.into(),
                user_id: user_id.into(),
                text: text.into(),
                reply_fn,
                user_name: None,
                is_reply_to_bot: false,
                is_dm,
                callback_data,
                edit_fn: None,
                avatar_fn: None,
                banner_fn: None,
                chatinfo_fn: None,
                typing_fn: None,
                temp_reply_fn: None,
                user_avatar_fn: None,
            }),
        }
    }

    /// Same as [`Ctx::new_full`], plus an `edit_fn` that rewrites the
    /// original message. Adapters use this on callback updates.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_edit(
        platform: PlatformKind,
        chat_id: impl Into<String>,
        user_id: impl Into<String>,
        text: impl Into<String>,
        reply_fn: ReplyFn,
        is_dm: Option<bool>,
        callback_data: Option<String>,
        edit_fn: Option<EditFn>,
    ) -> Self {
        Self {
            inner: Arc::new(CtxInner {
                platform,
                chat_id: chat_id.into(),
                user_id: user_id.into(),
                text: text.into(),
                reply_fn,
                user_name: None,
                is_reply_to_bot: false,
                is_dm,
                callback_data,
                edit_fn,
                avatar_fn: None,
                banner_fn: None,
                chatinfo_fn: None,
                typing_fn: None,
                temp_reply_fn: None,
                user_avatar_fn: None,
            }),
        }
    }

    /// Attach adapter capability lookups (avatar/banner/chat-info) to a
    /// freshly built `Ctx`. Adapters call this right after construction,
    /// before the context is cloned into handlers, so the in-place update
    /// through `Arc::get_mut` always succeeds. Pass `None` for anything the
    /// platform can't provide.
    pub fn with_lookups(
        mut self,
        avatar_fn: Option<UrlFn>,
        banner_fn: Option<UrlFn>,
        chatinfo_fn: Option<ChatInfoFn>,
    ) -> Self {
        if let Some(inner) = Arc::get_mut(&mut self.inner) {
            inner.avatar_fn = avatar_fn;
            inner.banner_fn = banner_fn;
            inner.chatinfo_fn = chatinfo_fn;
        }
        self
    }

    /// Attach a typing-indicator callback. Adapters set this right after
    /// construction, same as [`Ctx::with_lookups`].
    pub fn with_typing(mut self, typing_fn: Option<TypingFn>) -> Self {
        if let Some(inner) = Arc::get_mut(&mut self.inner) {
            inner.typing_fn = typing_fn;
        }
        self
    }

    /// Attach a self-deleting message sender for transient notices.
    pub fn with_temp_reply(mut self, temp_reply_fn: Option<TempReplyFn>) -> Self {
        if let Some(inner) = Arc::get_mut(&mut self.inner) {
            inner.temp_reply_fn = temp_reply_fn;
        }
        self
    }

    /// Attach a by-id avatar lookup for other users.
    pub fn with_user_avatar(mut self, user_avatar_fn: Option<UserUrlFn>) -> Self {
        if let Some(inner) = Arc::get_mut(&mut self.inner) {
            inner.user_avatar_fn = user_avatar_fn;
        }
        self
    }

    /// Record the sender's display name. Adapters set this at construction.
    pub fn with_user_name(mut self, name: Option<String>) -> Self {
        if let Some(inner) = Arc::get_mut(&mut self.inner) {
            inner.user_name = name;
        }
        self
    }

    /// Mark this update as a reply to one of the bot's own messages.
    pub fn with_reply_to_bot(mut self, yes: bool) -> Self {
        if let Some(inner) = Arc::get_mut(&mut self.inner) {
            inner.is_reply_to_bot = yes;
        }
        self
    }

    /// `true` when the user replied to a message the bot sent.
    pub fn is_reply_to_bot(&self) -> bool {
        self.inner.is_reply_to_bot
    }

    /// The sender's display name, if the platform provided one.
    pub fn user_name(&self) -> Option<&str> {
        self.inner.user_name.as_deref()
    }

    /// Which platform sent this update.
    pub fn platform(&self) -> PlatformKind {
        self.inner.platform
    }

    /// The chat/channel id this update came from, as a string so it's
    /// platform-agnostic.
    pub fn chat_id(&self) -> &str {
        &self.inner.chat_id
    }

    /// Id of the user who sent this update.
    pub fn user_id(&self) -> &str {
        &self.inner.user_id
    }

    /// Raw text of the incoming message.
    pub fn text(&self) -> &str {
        &self.inner.text
    }

    /// Everything after the command, trimmed.
    ///
    /// For `"/roll 3d6"` this returns `"3d6"`.
    /// For `"/help"` it returns `""`.
    pub fn args(&self) -> &str {
        self.inner
            .text
            .split_once(char::is_whitespace)
            .map(|(_, rest)| rest.trim())
            .unwrap_or("")
    }

    /// `true` when we are certain this update is a direct/private chat with
    /// the bot (one-on-one conversation). `false` when it's definitely a
    /// group/channel. Adapters that can't tell return `false` conservatively,
    /// so treat the answer as "is this safe to post private info into?".
    pub fn is_dm(&self) -> bool {
        match self.inner.is_dm {
            Some(v) => v,
            None => {
                // Fallback heuristic. Telegram uses the same id for private
                // chat and user, so they happen to match. Discord/Matrix
                // channels have distinct ids, so we bail.
                matches!(self.inner.platform, PlatformKind::Telegram)
                    && self.inner.chat_id == self.inner.user_id
            }
        }
    }

    /// Callback data attached to this update, when the user pressed a
    /// button registered via [`crate::Keyboard`]. `None` for regular text.
    pub fn callback_data(&self) -> Option<&str> {
        self.inner.callback_data.as_deref()
    }

    /// `true` when this update came from a button press (as opposed to
    /// a typed message). Convenience wrapper around
    /// [`Ctx::callback_data`].
    pub fn is_callback(&self) -> bool {
        self.inner.callback_data.is_some()
    }

    /// Send a plain-text reply back to the same chat on the same platform.
    pub async fn reply(&self, text: impl Into<String>) -> Result<()> {
        (self.inner.reply_fn)(Reply::text(text)).await
    }

    /// Send a reply with attached buttons / keyboard.
    pub async fn reply_with(&self, reply: impl Into<Reply>) -> Result<()> {
        (self.inner.reply_fn)(reply.into()).await
    }

    /// Rewrite the original message (the one that carried the button
    /// the user just pressed) with `reply`'s text / keyboard. Falls
    /// back to a fresh message when editing isn't possible (no
    /// callback, platform doesn't support editing, original message
    /// gone, etc.) so callers don't need to branch.
    pub async fn edit_reply(&self, reply: impl Into<Reply>) -> Result<()> {
        let r = reply.into();
        if let Some(edit) = &self.inner.edit_fn {
            return (edit)(r).await;
        }
        (self.inner.reply_fn)(r).await
    }

    /// URL of the sending user's avatar, when the platform can supply one.
    /// Returns `Ok(None)` if it can't (e.g. no adapter support).
    pub async fn avatar_url(&self) -> Result<Option<String>> {
        match &self.inner.avatar_fn {
            Some(f) => f().await,
            None => Ok(None),
        }
    }

    /// URL of *another* user's avatar, looked up by their platform id.
    /// May make a network request. `Ok(None)` when the user can't be
    /// resolved or the platform has no adapter support for this.
    pub async fn avatar_url_of(&self, user_id: &str) -> Result<Option<String>> {
        match &self.inner.user_avatar_fn {
            Some(f) => f(user_id.to_owned()).await,
            None => Ok(None),
        }
    }

    /// URL of the sending user's profile banner, when available. May make a
    /// network request on platforms that don't include it in the event.
    pub async fn banner_url(&self) -> Result<Option<String>> {
        match &self.inner.banner_fn {
            Some(f) => f().await,
            None => Ok(None),
        }
    }

    /// Info about the chat/server this update came from. Returns
    /// [`ChatInfo`] with whatever fields the platform can determine; errors
    /// only if the lookup itself fails. Without adapter support you get a
    /// minimal `ChatInfo` carrying just the chat id.
    pub async fn chat_info(&self) -> Result<ChatInfo> {
        match &self.inner.chatinfo_fn {
            Some(f) => f().await,
            None => Ok(ChatInfo {
                id: self.inner.chat_id.clone(),
                is_private: self.is_dm(),
                ..Default::default()
            }),
        }
    }

    /// Show a "typing…" indicator in the chat, if the platform supports it.
    /// Handy right before a slow operation so the user knows the bot is
    /// working. A no-op where it isn't supported; errors are swallowed so a
    /// failed indicator never breaks the actual reply.
    pub async fn typing(&self) {
        if let Some(f) = &self.inner.typing_fn {
            let _ = f().await;
        }
    }

    /// Send a notice that removes itself after `secs` seconds - for
    /// transient warnings ("slow down", "not your button") that would
    /// otherwise pile up in the chat. Falls back to a normal reply where
    /// the platform can't delete messages.
    pub async fn reply_temporary(&self, reply: impl Into<Reply>, secs: u64) -> Result<()> {
        let r = reply.into();
        if let Some(f) = &self.inner.temp_reply_fn {
            return f(r, secs).await;
        }
        (self.inner.reply_fn)(r).await
    }
}