rustigram-bot 0.12.0

High-level bot dispatcher, update listener, and handler framework for rustigram
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
use rustigram_types::update::UpdateKind;

use crate::context::Context;

/// A predicate evaluated against an incoming [`Context`].
///
/// Filters are `Send + Sync + 'static` and cheap to clone, making them safe
/// to share across tasks. Combine filters with [`FilterExt::and`],
/// [`FilterExt::or`], and [`FilterExt::not`].
///
/// Implement this trait to create custom filters:
///
/// ```rust,ignore
/// use rustigram_bot::filter::Filter;
/// use rustigram_bot::Context;
///
/// #[derive(Clone)]
/// struct HasPhotoFilter;
///
/// impl Filter for HasPhotoFilter {
///     fn check(&self, ctx: &Context) -> bool {
///         ctx.message().and_then(|m| m.photo.as_ref()).is_some()
///     }
/// }
/// ```
pub trait Filter: Send + Sync + 'static {
    /// Returns `true` if this filter matches the given context.
    fn check(&self, ctx: &Context) -> bool;
}

/// Extension methods for composing [`Filter`] values.
///
/// Automatically implemented for every type that implements [`Filter`].
pub trait FilterExt: Filter + Sized + Clone {
    /// Passes only when both `self` and `other` match.
    fn and<F: Filter + Clone>(self, other: F) -> And<Self, F> {
        And {
            left: self,
            right: other,
        }
    }

    /// Passes when `self` or `other` (or both) match.
    fn or<F: Filter + Clone>(self, other: F) -> Or<Self, F> {
        Or {
            left: self,
            right: other,
        }
    }

    /// Inverts this filter.
    fn not(self) -> Not<Self> {
        Not { inner: self }
    }
}

impl<F: Filter + Clone> FilterExt for F {}

// ─── Combinators ─────────────────────────────────────────────────────────────

/// Combines two filters with logical AND: passes only if both filters pass.
#[derive(Clone)]
pub struct And<L, R> {
    left: L,
    right: R,
}
impl<L: Filter, R: Filter> Filter for And<L, R> {
    fn check(&self, ctx: &Context) -> bool {
        self.left.check(ctx) && self.right.check(ctx)
    }
}

/// Combines two filters with logical OR: passes if either filter (or both) pass.
#[derive(Clone)]
pub struct Or<L, R> {
    left: L,
    right: R,
}
impl<L: Filter, R: Filter> Filter for Or<L, R> {
    fn check(&self, ctx: &Context) -> bool {
        self.left.check(ctx) || self.right.check(ctx)
    }
}

/// Inverts a filter: passes when the inner filter fails, and vice versa.
#[derive(Clone)]
pub struct Not<F> {
    inner: F,
}
impl<F: Filter> Filter for Not<F> {
    fn check(&self, ctx: &Context) -> bool {
        !self.inner.check(ctx)
    }
}

// ─── Function filter ──────────────────────────────────────────────────────────

#[derive(Clone)]
/// Wraps a plain function or closure as a [`Filter`].
pub struct FnFilter<F>(pub F);

impl<F: Fn(&Context) -> bool + Send + Sync + Clone + 'static> Filter for FnFilter<F> {
    fn check(&self, ctx: &Context) -> bool {
        (self.0)(ctx)
    }
}

/// Creates a [`Filter`] from any closure with signature `fn(&Context) -> bool`.
pub fn filter_fn<F>(f: F) -> FnFilter<F>
where
    F: Fn(&Context) -> bool + Send + Sync + Clone + 'static,
{
    FnFilter(f)
}

// ─── Built-in filters ─────────────────────────────────────────────────────────

#[derive(Clone, Copy)]
/// Passes only for [`Message`](rustigram_types::update::UpdateKind::Message) updates.
pub struct MessageFilter;
impl Filter for MessageFilter {
    fn check(&self, ctx: &Context) -> bool {
        matches!(ctx.update.kind, UpdateKind::Message(_))
    }
}

/// Passes only for `EditedMessage` updates.
#[derive(Clone, Copy)]
/// Passes only for [`EditedMessage`](rustigram_types::update::UpdateKind::EditedMessage) updates.
pub struct EditedMessageFilter;
impl Filter for EditedMessageFilter {
    fn check(&self, ctx: &Context) -> bool {
        matches!(ctx.update.kind, UpdateKind::EditedMessage(_))
    }
}

/// Passes only for `CallbackQuery` updates.
#[derive(Clone, Copy)]
/// Passes only for [`CallbackQuery`](rustigram_types::update::UpdateKind::CallbackQuery) updates.
pub struct CallbackQueryFilter;
impl Filter for CallbackQueryFilter {
    fn check(&self, ctx: &Context) -> bool {
        matches!(ctx.update.kind, UpdateKind::CallbackQuery(_))
    }
}

/// Passes only for `InlineQuery` updates.
#[derive(Clone, Copy)]
/// Passes only for [`InlineQuery`](rustigram_types::update::UpdateKind::InlineQuery) updates.
pub struct InlineQueryFilter;
impl Filter for InlineQueryFilter {
    fn check(&self, ctx: &Context) -> bool {
        matches!(ctx.update.kind, UpdateKind::InlineQuery(_))
    }
}

#[derive(Clone)]
/// Passes when the message is a bot command matching `command`.
///
/// The check is case-insensitive and strips the leading `/` and any
/// `@BotName` suffix automatically.
pub struct CommandFilter {
    command: String,
}

impl CommandFilter {
    /// Creates a new filter matching the command `command`.
    pub fn new(command: impl Into<String>) -> Self {
        Self {
            command: command.into(),
        }
    }
}

impl Filter for CommandFilter {
    fn check(&self, ctx: &Context) -> bool {
        ctx.command()
            .is_some_and(|cmd| cmd.eq_ignore_ascii_case(&self.command))
    }
}

#[derive(Clone)]
/// Passes when the message text exactly equals `text`.
pub struct TextFilter {
    text: String,
}

impl TextFilter {
    /// Creates a new filter matching the exact text `text`.
    pub fn new(text: impl Into<String>) -> Self {
        Self { text: text.into() }
    }
}

impl Filter for TextFilter {
    fn check(&self, ctx: &Context) -> bool {
        ctx.text().is_some_and(|t| t == self.text)
    }
}

#[derive(Clone)]
/// Passes when the message text contains `needle` as a substring.
pub struct TextContainsFilter {
    needle: String,
}

impl TextContainsFilter {
    /// Creates a new filter matching text containing `needle`.
    pub fn new(needle: impl Into<String>) -> Self {
        Self {
            needle: needle.into(),
        }
    }
}

impl Filter for TextContainsFilter {
    fn check(&self, ctx: &Context) -> bool {
        ctx.text().is_some_and(|t| t.contains(self.needle.as_str()))
    }
}

#[derive(Clone)]
/// Passes when the callback query data exactly equals `data`.
pub struct CallbackDataFilter {
    data: String,
}

impl CallbackDataFilter {
    /// Creates a new filter matching the callback data `data`.
    pub fn new(data: impl Into<String>) -> Self {
        Self { data: data.into() }
    }
}

impl Filter for CallbackDataFilter {
    fn check(&self, ctx: &Context) -> bool {
        ctx.callback_query()
            .and_then(|q| q.data.as_deref())
            .is_some_and(|d| d == self.data)
    }
}

#[derive(Clone)]
/// Passes when the callback query data starts with `prefix`.
pub struct CallbackDataPrefixFilter {
    prefix: String,
}

impl CallbackDataPrefixFilter {
    /// Creates a new filter matching callback data starting with `prefix`.
    pub fn new(prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
        }
    }
}

impl Filter for CallbackDataPrefixFilter {
    fn check(&self, ctx: &Context) -> bool {
        ctx.callback_query()
            .and_then(|q| q.data.as_deref())
            .is_some_and(|d| d.starts_with(self.prefix.as_str()))
    }
}

#[derive(Clone, Copy)]
/// Passes only for messages in private chats.
pub struct PrivateChatFilter;
impl Filter for PrivateChatFilter {
    fn check(&self, ctx: &Context) -> bool {
        ctx.message()
            .is_some_and(|m| matches!(m.chat.kind, rustigram_types::chat::ChatType::Private))
    }
}

#[derive(Clone, Copy)]
/// Passes only for messages in group and supergroup chats.
pub struct GroupFilter;
impl Filter for GroupFilter {
    fn check(&self, ctx: &Context) -> bool {
        ctx.message().is_some_and(|m| {
            matches!(
                m.chat.kind,
                rustigram_types::chat::ChatType::Group
                    | rustigram_types::chat::ChatType::Supergroup
            )
        })
    }
}

/// Passes when the message contains a `web_app_data` field.
///
/// Triggered when a user taps a Web App keyboard button that sends data
/// directly to the bot (as opposed to launching a full TMA session).
///
/// Requires the `tma` feature on `rustigram-bot`.
#[cfg(feature = "tma")]
#[derive(Clone, Copy)]
pub struct WebAppDataFilter;

#[cfg(feature = "tma")]
impl Filter for WebAppDataFilter {
    fn check(&self, ctx: &Context) -> bool {
        ctx.message()
            .and_then(|m| m.web_app_data.as_ref())
            .is_some()
    }
}

/// Passes when the message contains `web_app_data` AND the given predicate
/// returns `true` for `button_text`.
///
/// Useful when multiple Web App buttons have different labels and you want
/// to route them to separate handlers.
///
/// Requires the `tma` feature on `rustigram-bot`.
#[cfg(feature = "tma")]
#[derive(Clone)]
pub struct WebAppDataMatchingFilter<F> {
    predicate: F,
}

#[cfg(feature = "tma")]
impl<F> Filter for WebAppDataMatchingFilter<F>
where
    F: Fn(&str) -> bool + Send + Sync + Clone + 'static,
{
    fn check(&self, ctx: &Context) -> bool {
        ctx.message()
            .and_then(|m| m.web_app_data.as_ref())
            .is_some_and(|d| (self.predicate)(d.button_text.as_str()))
    }
}

/// Convenience constructors for all built-in filters.
///
/// Import this module and call functions to create filters:
///
/// ```rust,ignore
/// use rustigram_bot::filter::filters;
/// use rustigram_bot::filter::FilterExt;
///
/// let f = filters::command("start")
///             .and(filters::private());
/// ```
pub mod filters {
    use super::*;

    /// Passes for any `Message` update.
    pub fn message() -> MessageFilter {
        MessageFilter
    }
    /// Passes for any `EditedMessage` update.
    pub fn edited_message() -> EditedMessageFilter {
        EditedMessageFilter
    }
    /// Passes for any `CallbackQuery` update.
    pub fn callback_query() -> CallbackQueryFilter {
        CallbackQueryFilter
    }
    /// Passes for any `InlineQuery` update.
    pub fn inline_query() -> InlineQueryFilter {
        InlineQueryFilter
    }
    /// Passes when the message is the given bot command (case-insensitive).
    pub fn command(cmd: impl Into<String>) -> CommandFilter {
        CommandFilter::new(cmd)
    }
    /// Passes when the message text exactly equals `t`.
    pub fn text(t: impl Into<String>) -> TextFilter {
        TextFilter::new(t)
    }
    /// Passes when the message text contains `needle` as a substring.
    pub fn text_contains(needle: impl Into<String>) -> TextContainsFilter {
        TextContainsFilter::new(needle)
    }
    /// Passes when the callback query data exactly equals `data`.
    pub fn callback_data(data: impl Into<String>) -> CallbackDataFilter {
        CallbackDataFilter::new(data)
    }
    /// Passes when the callback query data starts with `prefix`.
    pub fn callback_data_prefix(prefix: impl Into<String>) -> CallbackDataPrefixFilter {
        CallbackDataPrefixFilter::new(prefix)
    }
    /// Passes for messages in private chats.
    pub fn private() -> PrivateChatFilter {
        PrivateChatFilter
    }
    /// Passes for messages in group and supergroup chats.
    pub fn group() -> GroupFilter {
        GroupFilter
    }
    /// Always passes — useful as a catch-all fallback route.
    pub fn any() -> FnFilter<fn(&Context) -> bool> {
        FnFilter(|_| true)
    }
    /// Passes for any message that carries `web_app_data`.
    ///
    /// Requires the `tma` feature on `rustigram-bot`.
    #[cfg(feature = "tma")]
    pub fn web_app_data() -> WebAppDataFilter {
        WebAppDataFilter
    }
    /// Passes for messages whose `web_app_data.button_text` satisfies `predicate`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// filters::web_app_data_matching(|btn| btn == "Open Wallet")
    /// ```
    ///
    /// Requires the `tma` feature on `rustigram-bot`.
    #[cfg(feature = "tma")]
    pub fn web_app_data_matching<F>(predicate: F) -> WebAppDataMatchingFilter<F>
    where
        F: Fn(&str) -> bool + Send + Sync + Clone + 'static,
    {
        WebAppDataMatchingFilter { predicate }
    }
}