vaegram 0.2.0

Telegram MTProto client library for users and bots
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
use crate::Client;
use crate::crypto::random;
use crate::enums::ParseMode;
use crate::errors::Result;
use crate::raw::{base, functions, types};
use crate::types::{Message, PeerRef, ReplyMarkup, ReplyParameters, RichMessage, SuggestedPostParameters, Text};

#[derive(Default)]
pub(crate) struct SendOptions {
    pub(crate) reply_to: Option<ReplyParameters>,
    pub(crate) message_thread_id: Option<i32>,
    pub(crate) direct_messages_topic_id: Option<PeerRef>,
    pub(crate) reply_markup: Option<ReplyMarkup>,
    pub(crate) business_connection_id: Option<String>,
    pub(crate) disable_notification: bool,
    pub(crate) protect_content: bool,
    pub(crate) allow_paid_broadcast: bool,
    pub(crate) paid_message_star_count: Option<i64>,
    pub(crate) message_effect_id: Option<i64>,
    pub(crate) suggested_post_parameters: Option<SuggestedPostParameters>,
    pub(crate) schedule_date: Option<i32>,
    pub(crate) no_webpage: bool,
    pub(crate) invert_media: bool,
}

macro_rules! send_builder {
    ($builder:ident) => {
        send_builder!($builder, $crate::types::Message);

        impl $builder<'_> {
            /// Attaches an inline keyboard or a reply keyboard, or removes or forces a reply.
            pub fn reply_markup(mut self, markup: impl Into<$crate::types::ReplyMarkup>) -> Self {
                self.options.reply_markup = Some(markup.into());
                self
            }

            /// Sends on behalf of the business account behind this connection id.
            pub fn business_connection_id(mut self, id: impl Into<String>) -> Self {
                self.options.business_connection_id = Some(id.into());
                self
            }
        }

        impl $crate::methods::OnBehalf for $builder<'_> {
            fn business_connection(&mut self) -> &mut Option<String> {
                &mut self.options.business_connection_id
            }
        }
    };
    ($builder:ident, $output:ty) => {
        impl $builder<'_> {
            /// Replies to a message, optionally one in another chat or with a quote.
            pub fn reply_to(mut self, reply: impl Into<$crate::types::ReplyParameters>) -> Self {
                self.options.reply_to = Some(reply.into());
                self
            }

            /// Sends into a forum topic. The General topic (id 1) is sent as no topic.
            pub fn message_thread_id(mut self, thread_id: i32) -> Self {
                self.options.message_thread_id = Some(thread_id);
                self
            }

            /// Sends into the direct-messages topic that belongs to this user.
            pub fn direct_messages_topic_id(mut self, user_id: impl Into<$crate::types::PeerRef>) -> Self {
                self.options.direct_messages_topic_id = Some(user_id.into());
                self
            }

            /// Sends the message silently, so recipients get no notification sound.
            pub fn disable_notification(mut self) -> Self {
                self.options.disable_notification = true;
                self
            }

            /// Stops recipients from forwarding or saving the message.
            pub fn protect_content(mut self) -> Self {
                self.options.protect_content = true;
                self
            }

            /// Pays Stars to go over the broadcast limit of 30 messages a second.
            pub fn allow_paid_broadcast(mut self) -> Self {
                self.options.allow_paid_broadcast = true;
                self
            }

            /// Stars to pay for the message, for chats that charge for incoming messages.
            pub fn paid_message_star_count(mut self, stars: i64) -> Self {
                self.options.paid_message_star_count = Some(stars);
                self
            }

            /// Plays the message effect with this id when the message arrives.
            pub fn message_effect_id(mut self, effect_id: i64) -> Self {
                self.options.message_effect_id = Some(effect_id);
                self
            }

            /// Sends the message as a suggested post, with the price and time in `parameters`.
            pub fn suggested_post_parameters(mut self, parameters: $crate::types::SuggestedPostParameters) -> Self {
                self.options.suggested_post_parameters = Some(parameters);
                self
            }

            /// Schedules the message for this Unix timestamp instead of sending it now.
            pub fn schedule_date(mut self, date: i32) -> Self {
                self.options.schedule_date = Some(date);
                self
            }
        }

        impl $crate::methods::Routable for $builder<'_> {
            fn options(&mut self) -> &mut $crate::methods::messages::SendOptions {
                &mut self.options
            }
        }

        into_future!($builder, $output);
    };
}
pub(crate) use send_builder;

/// A send builder whose topic, direct-messages topic and business connection can be set from a message.
pub(crate) trait Routable {
    fn options(&mut self) -> &mut SendOptions;
}

macro_rules! caption_setters {
    ($builder:ident $(. $m:ident)?) => {
        impl $builder<'_> {
            /// Parses the text or caption as HTML.
            pub fn html(self) -> Self {
                self.parse_mode($crate::enums::ParseMode::Html)
            }

            /// Parses the text or caption as Markdown.
            pub fn markdown(self) -> Self {
                self.parse_mode($crate::enums::ParseMode::Markdown)
            }

            /// Sets how the text or caption is parsed. Without it the client's default parse mode applies.
            pub fn parse_mode(mut self, mode: $crate::enums::ParseMode) -> Self {
                self$(.$m)?.parse_mode = Some(mode);
                self
            }
        }
    };
}
pub(crate) use caption_setters;

macro_rules! send_media {
    ($builder:ident) => {
        impl $builder<'_> {
            async fn send(mut self) -> $crate::Result<$crate::types::Message> {
                let peer = self.client.resolve(&self.chat_id).await?.1;
                let business = self.options.business_connection_id.as_deref();
                let media = self.client.input_media(&peer, &self.media, self.progress.take(), business).await?;
                self.options.invert_media = self.media.show_caption_above_media;
                let (caption, parse_mode) = (self.media.caption, self.media.parse_mode);
                self.client.send_media(self.chat_id, media, caption, parse_mode, self.options).await
            }
        }

        send_builder!($builder);
    };
}
pub(crate) use send_media;

impl SendOptions {
    /// The forum topic to name. Per messages.sendMessage, the General topic (id 1) never is.
    pub(crate) fn thread(&self) -> Option<i32> {
        self.message_thread_id.filter(|&id| id != 1)
    }

    pub(crate) async fn input_reply_to(
        &self,
        client: &Client,
        chat_id: i64,
        thread: Option<i32>,
    ) -> Result<Option<base::InputReplyTo>> {
        let monoforum_peer_id = match &self.direct_messages_topic_id {
            Some(user) => Some(client.resolve(user).await?.1),
            None => None,
        };
        let reply = match (&self.reply_to, thread) {
            (Some(reply), _) => reply.write(client, chat_id).await?,
            (None, Some(thread)) => ReplyParameters::new(thread).write(client, chat_id).await?,
            (None, None) => {
                let Some(monoforum_peer_id) = monoforum_peer_id else { return Ok(None) };
                let reply = types::InputReplyToMonoForum { monoforum_peer_id };
                return Ok(Some(base::InputReplyTo::InputReplyToMonoForum(Box::new(reply))));
            }
        };
        // inputReplyToStory has no topic or direct-messages field, so a story reply goes out as written.
        let base::InputReplyTo::InputReplyToMessage(mut reply) = reply else { return Ok(Some(reply)) };
        // top_msg_id is set only when replying to another message in the topic.
        reply.top_msg_id = thread.filter(|&id| id != reply.reply_to_msg_id);
        reply.monoforum_peer_id = monoforum_peer_id;
        Ok(Some(base::InputReplyTo::InputReplyToMessage(reply)))
    }
}

impl Client {
    pub(crate) async fn send_media(
        &self,
        chat_id: impl Into<PeerRef>,
        media: base::InputMedia,
        caption: impl Into<Text>,
        parse_mode: Option<ParseMode>,
        options: SendOptions,
    ) -> Result<Message> {
        let (message, entities) = self.write_text(caption.into(), parse_mode).await?;
        let text = (message, (!entities.is_empty()).then_some(entities));
        self.send_parsed(chat_id, Some(media), text, None, options).await
    }

    pub(crate) async fn send_parsed(
        &self,
        chat_id: impl Into<PeerRef>,
        media: Option<base::InputMedia>,
        (message, entities): (String, Option<Vec<base::MessageEntity>>),
        rich_message: Option<base::InputRichMessage>,
        options: SendOptions,
    ) -> Result<Message> {
        let (chat_id, peer) = self.resolve(&chat_id.into()).await?;
        let in_topic = options.thread().is_some();
        let reply_to = options.input_reply_to(self, chat_id, options.thread()).await?;
        // Telegram drops a second message with the same random_id, so retries can't double-send.
        let random_id = i64::from_le_bytes(random());
        let reply_markup = ReplyMarkup::write_option(options.reply_markup.as_ref(), self).await?;
        let suggested_post = options.suggested_post_parameters.map(SuggestedPostParameters::write);
        let connection_id = options.business_connection_id;
        let me = self.0.me.lock().unwrap().id;
        // The message as the request describes it, for a short "sent" reply that carries little more than its id.
        macro_rules! sent {
            ($request:ident) => {
                types::Message {
                    silent: $request.silent,
                    noforwards: $request.noforwards,
                    invert_media: $request.invert_media,
                    reply_to: $request.reply_to.and_then(|reply| Message::reply_header(reply, me, in_topic)),
                    reply_markup: $request.reply_markup,
                    effect: $request.effect,
                    paid_message_stars: $request.allow_paid_stars,
                    ..Message::request(chat_id, $request.message, $request.entities)
                }
            };
        }
        let (updates, sent, rich_message) = match media {
            Some(media) => {
                let request = functions::messages::SendMedia {
                    silent: options.disable_notification,
                    background: false,
                    clear_draft: false,
                    noforwards: options.protect_content,
                    update_stickersets_order: false,
                    invert_media: options.invert_media,
                    allow_paid_floodskip: options.allow_paid_broadcast,
                    peer,
                    reply_to,
                    media,
                    message,
                    random_id,
                    reply_markup,
                    entities,
                    schedule_date: options.schedule_date,
                    schedule_repeat_period: None,
                    send_as: None,
                    quick_reply_shortcut: None,
                    effect: options.message_effect_id,
                    allow_paid_stars: options.paid_message_star_count,
                    suggested_post,
                };
                let (updates, request) = self.invoke_business(connection_id.as_deref(), request).await?;
                (updates, sent!(request), None)
            }
            None => {
                let request = functions::messages::SendMessage {
                    no_webpage: options.no_webpage,
                    silent: options.disable_notification,
                    background: false,
                    clear_draft: false,
                    noforwards: options.protect_content,
                    update_stickersets_order: false,
                    invert_media: options.invert_media,
                    allow_paid_floodskip: options.allow_paid_broadcast,
                    peer,
                    reply_to,
                    message,
                    random_id,
                    reply_markup,
                    entities,
                    schedule_date: options.schedule_date,
                    schedule_repeat_period: None,
                    send_as: None,
                    quick_reply_shortcut: None,
                    effect: options.message_effect_id,
                    allow_paid_stars: options.paid_message_star_count,
                    suggested_post,
                    rich_message,
                };
                let (updates, request) = self.invoke_business(connection_id.as_deref(), request).await?;
                let rich_message = request.rich_message;
                (updates, sent!(request), rich_message)
            }
        };
        let Some(rich_message) = rich_message else { return Message::from_updates(self, updates, sent) };
        // A short "sent" reply has no rich message, so it is rebuilt from the request, minus photos and documents.
        let (text, sent_rich) = RichMessage::sent(rich_message);
        let sent = types::Message { message: text, entities: None, ..sent };
        let mut message = Message::from_updates(self, updates, sent)?;
        if message.rich_message.is_none() {
            message.rich_message = sent_rich;
        }
        Ok(message)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::client::Me;
    use crate::dispatcher::Entities;
    use crate::dispatcher::cache::Caches;
    use crate::raw::Serializable;
    use crate::types::{CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Text};
    use crate::utils::get_peer;

    const GROUP: i64 = -5;

    fn message(reply: Option<base::InputReplyTo>) -> types::InputReplyToMessage {
        match reply {
            Some(base::InputReplyTo::InputReplyToMessage(m)) => *m,
            other => panic!("not a message reply: {other:?}"),
        }
    }

    async fn written(client: &Client, options: SendOptions) -> Option<base::InputReplyTo> {
        options.input_reply_to(client, GROUP, options.thread()).await.unwrap()
    }

    async fn topic(client: &Client, reply: Option<i32>, thread: Option<i32>) -> Option<(i32, Option<i32>)> {
        let reply_to = reply.map(ReplyParameters::new);
        let options = SendOptions { reply_to, message_thread_id: thread, ..Default::default() };
        let m = message(Some(written(client, options).await?));
        Some((m.reply_to_msg_id, m.top_msg_id))
    }

    #[tokio::test]
    async fn topics_follow_the_send_message_rules() {
        let client = &Client::offline();
        assert_eq!(topic(client, None, None).await, None);
        assert_eq!(topic(client, None, Some(1)).await, None);
        assert_eq!(topic(client, None, Some(7)).await, Some((7, None)));
        assert_eq!(topic(client, Some(9), Some(7)).await, Some((9, Some(7))));
        assert_eq!(topic(client, Some(7), Some(7)).await, Some((7, None)));
        assert_eq!(topic(client, Some(9), Some(1)).await, Some((9, None)));
    }

    #[tokio::test]
    async fn reply_parameters_fill_quote_task_and_other_chat() {
        let client = &Client::offline();
        let reply = ReplyParameters::new(4).chat_id(-6).quote("<b>hi</b>").quote_position(2).checklist_task_id(3);
        let m = message(written(client, SendOptions { reply_to: Some(reply), ..Default::default() }).await);
        let other_chat = base::InputPeer::InputPeerChat(types::InputPeerChat { chat_id: 6 });
        assert_eq!((m.reply_to_msg_id, m.quote_offset, m.todo_item_id), (4, Some(2), Some(3)));
        assert_eq!((m.quote_text.as_deref(), m.reply_to_peer_id), (Some("<b>hi</b>"), Some(other_chat)));

        let reply = ReplyParameters::new(4).chat_id(GROUP).quote("<b>hi</b>").quote_parse_mode(ParseMode::Html);
        let m = message(written(client, SendOptions { reply_to: Some(reply), ..Default::default() }).await);
        assert_eq!((m.quote_text.as_deref(), m.reply_to_peer_id), (Some("hi"), None));
        assert_eq!(m.quote_entities.map(|e| e.len()), Some(1));
    }

    #[tokio::test]
    async fn unset_parse_modes_use_the_client_default() {
        let client = Client::offline();
        client.set_parse_mode(ParseMode::Html);
        let (text, entities) = client.write_text("<b>hi</b>".into(), None).await.unwrap();
        assert_eq!((text.as_str(), entities.len()), ("hi", 1));
        let (text, entities) = client.write_text("<b>hi</b>".into(), Some(ParseMode::Disabled)).await.unwrap();
        assert_eq!((text.as_str(), entities.len()), ("<b>hi</b>", 0));
        let (text, entities) = client.write_text(Text::new().plain("<b>hi</b>"), None).await.unwrap();
        assert_eq!((text.as_str(), entities.len()), ("<b>hi</b>", 0));
        let (text, entities) = client.write_text(Text::from_html("&lt;b&gt;"), None).await.unwrap();
        assert_eq!((text.as_str(), entities.len()), ("<b>", 0));

        let reply = Some(ReplyParameters::new(4).quote("<b>hi</b>"));
        let m = message(written(&client, SendOptions { reply_to: reply, ..Default::default() }).await);
        assert_eq!(m.quote_text.as_deref(), Some("hi"));
    }

    #[tokio::test]
    async fn direct_messages_topics_name_the_user() {
        let client = &Client::offline();
        let user = base::InputPeer::InputPeerUser(Box::new(types::InputPeerUser { user_id: 42, access_hash: 1 }));
        client.0.peers.lock().unwrap().insert(42, user.clone());

        let options = SendOptions { direct_messages_topic_id: Some(42.into()), ..Default::default() };
        let topic = types::InputReplyToMonoForum { monoforum_peer_id: user.clone() };
        let expected = base::InputReplyTo::InputReplyToMonoForum(Box::new(topic));
        assert_eq!(written(client, options).await, Some(expected));

        let reply_to = Some(ReplyParameters::new(3));
        let options = SendOptions { reply_to, direct_messages_topic_id: Some(42.into()), ..Default::default() };
        let m = message(written(client, options).await);
        assert_eq!((m.reply_to_msg_id, m.monoforum_peer_id), (3, Some(user)));
    }

    #[tokio::test]
    async fn a_story_reply_ignores_topic_and_direct_messages() {
        let client = &Client::offline();
        let user = base::InputPeer::InputPeerUser(Box::new(types::InputPeerUser { user_id: 42, access_hash: 1 }));
        client.0.peers.lock().unwrap().insert(42, user.clone());

        let options = SendOptions {
            reply_to: Some(ReplyParameters::story(42, 8)),
            message_thread_id: Some(7),
            direct_messages_topic_id: Some(42.into()),
            ..Default::default()
        };
        let story = types::InputReplyToStory { peer: user, story_id: 8 };
        assert_eq!(written(client, options).await, Some(base::InputReplyTo::InputReplyToStory(Box::new(story))));
    }

    #[tokio::test]
    async fn a_short_sent_reply_keeps_what_the_request_carried() {
        let short = base::Updates::UpdateShortSentMessage(Box::new(types::UpdateShortSentMessage {
            out: true,
            id: 9,
            pts: 0,
            pts_count: 0,
            date: 0,
            media: None,
            entities: None,
            ttl_period: None,
        }));
        let (mut client, _rx) = Client::scripted(vec![Ok(short.to_bytes())]);
        Arc::get_mut(&mut client.0).unwrap().caches = Caches::new(10, 0);
        *client.0.me.lock().unwrap() = Me { id: 42, is_bot: true, premium: None, username: Some("bot".into()) };
        let user = base::InputPeer::InputPeerUser(Box::new(types::InputPeerUser { user_id: 7, access_hash: 1 }));
        client.0.peers.lock().unwrap().insert(7, user);

        let keyboard = InlineKeyboardMarkup::new([vec![InlineKeyboardButton::callback("Go", "go")]]);
        let sent = client
            .send_message(7, "hi")
            .reply_to(ReplyParameters::new(3).quote("hi"))
            .protect_content()
            .disable_notification()
            .message_effect_id(5)
            .reply_markup(keyboard.clone())
            .await
            .unwrap();
        let check = |m: &Message| {
            assert_eq!(m.reply_markup(), Some(ReplyMarkup::Inline(keyboard.clone())));
            assert_eq!((m.reply_to_message_id, m.quote.as_ref().map(|q| q.text.as_str())), (Some(3), Some("hi")));
            assert!(m.has_protected_content && m.silent);
            assert_eq!(m.effect_id, Some(5));
            let from = m.from_user.as_deref().unwrap();
            assert_eq!((from.id, from.is_bot, from.is_self, from.username.as_deref()), (42, true, true, Some("bot")));
        };
        check(&sent);

        // A press on the keyboard reads the message back from the cache.
        let press = types::UpdateBotCallbackQuery {
            query_id: 1,
            user_id: 7,
            peer: get_peer(7),
            msg_id: 9,
            chat_instance: 3,
            data: Some(b"go".to_vec()),
            game_short_name: None,
        };
        let query = CallbackQuery::parse(&client, &press, &Entities::default());
        check(&query.message().await.unwrap().unwrap());
    }
}