ferogram 0.6.3

Production-grade async Telegram MTProto client: updates, bots, flood-wait, dialogs, messages
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
//
// ferogram: async Telegram MTProto client in Rust
// https://github.com/ankit-chaubey/ferogram
//
// Licensed under either the MIT License or the Apache License 2.0.
// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
// https://github.com/ankit-chaubey/ferogram
//
// Feel free to use, modify, and share this code.
// Please keep this notice when redistributing.

use crate::*;
#[allow(unused_imports)]
use crate::{
    InputMessage, InvocationError, PeerRef,
    dialog::{Dialog, DialogIter, MessageIter},
    inline_iter, media, participants, search, update,
};
use ferogram_tl_types::{Cursor, Deserializable};

impl Client {
    /// Delete a chat or channel. Dispatches to `channels.deleteChannel` for channels/supergroups
    /// and `messages.deleteChat` for legacy basic groups.
    ///
    /// Only the creator can delete. This action is irreversible.
    pub async fn delete_chat(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        match &input_peer {
            tl::enums::InputPeer::Channel(c) => {
                let req = tl::functions::channels::DeleteChannel {
                    channel: tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                        channel_id: c.channel_id,
                        access_hash: c.access_hash,
                    }),
                };
                self.rpc_write(&req).await
            }
            tl::enums::InputPeer::Chat(c) => {
                let req = tl::functions::messages::DeleteChat { chat_id: c.chat_id };
                self.rpc_write(&req).await
            }
            _ => Err(InvocationError::Deserialize(
                "delete_chat: peer must be a chat or channel".into(),
            )),
        }
    }

    /// Leave a channel or supergroup.
    ///
    /// For basic groups, kick yourself or use
    /// [`Client::delete_dialog`] to just hide it.
    pub async fn leave_chat(&self, peer: impl Into<PeerRef>) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let channel = match &input_peer {
            tl::enums::InputPeer::Channel(c) => {
                tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                    channel_id: c.channel_id,
                    access_hash: c.access_hash,
                })
            }
            _ => {
                return Err(InvocationError::Deserialize(
                    "leave_chat: peer must be a channel or supergroup".into(),
                ));
            }
        };
        let req = tl::functions::channels::LeaveChannel { channel };
        self.rpc_write(&req).await
    }

    /// Upgrade a legacy group to a supergroup (megagroup).
    ///
    /// Returns the new channel/supergroup peer. The original chat ID becomes
    /// invalid after migration.
    pub async fn migrate_chat(&self, chat_id: i64) -> Result<tl::enums::Chat, InvocationError> {
        let req = tl::functions::messages::MigrateChat { chat_id };
        let body: Vec<u8> = self.rpc_call_raw(&req).await?;
        let mut cur = Cursor::from_slice(&body);
        let updates = tl::enums::Updates::deserialize(&mut cur)?;
        let chats = match updates {
            tl::enums::Updates::Updates(u) => u.chats,
            tl::enums::Updates::Combined(u) => u.chats,
            _ => vec![],
        };
        // The migrated supergroup is the channel in the chats list.
        chats
            .into_iter()
            .find(|c| matches!(c, tl::enums::Chat::Channel(_)))
            .ok_or_else(|| {
                InvocationError::Deserialize("migrate_chat: no channel in response".into())
            })
    }

    #[allow(dead_code)]
    async fn set_default_banned_rights_raw(
        &self,
        peer: impl Into<PeerRef>,
        build: impl FnOnce(
            crate::participants::BannedRightsBuilder,
        ) -> crate::participants::BannedRightsBuilder,
    ) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let rights = build(crate::participants::BannedRightsBuilder::new()).into_tl();
        let req = tl::functions::messages::EditChatDefaultBannedRights {
            peer: input_peer,
            banned_rights: rights,
        };
        self.rpc_write(&req).await
    }

    #[allow(dead_code)]
    /// Get the full info for a chat - description, pinned message,
    /// slow-mode delay, and other fields the basic chat object doesn't carry.
    pub async fn get_chat_full(
        &self,
        peer: impl Into<PeerRef>,
    ) -> Result<tl::enums::messages::ChatFull, InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let body = match &input_peer {
            tl::enums::InputPeer::Channel(c) => {
                let req = tl::functions::channels::GetFullChannel {
                    channel: tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                        channel_id: c.channel_id,
                        access_hash: c.access_hash,
                    }),
                };
                self.rpc_call_raw(&req).await?
            }
            tl::enums::InputPeer::Chat(c) => {
                let req = tl::functions::messages::GetFullChat { chat_id: c.chat_id };
                self.rpc_call_raw(&req).await?
            }
            _ => {
                return Err(InvocationError::Deserialize(
                    "get_chat_full: peer must be a chat or channel".into(),
                ));
            }
        };
        // Cache users/chats from the response so subsequent calls work.
        let mut cur = Cursor::from_slice(&body);
        let full = tl::enums::messages::ChatFull::deserialize(&mut cur)?;
        let tl::enums::messages::ChatFull::ChatFull(ref f) = full;
        self.cache_users_slice(&f.users).await;
        self.cache_chats_slice(&f.chats).await;
        Ok(full)
    }

    #[allow(dead_code)]
    pub(crate) async fn add_chat_members(
        &self,
        peer: impl Into<PeerRef>,
        user_ids: &[i64],
    ) -> Result<(), InvocationError> {
        if user_ids.is_empty() {
            return Ok(());
        }
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;

        match &input_peer {
            tl::enums::InputPeer::Channel(c) => {
                let cache: tokio::sync::RwLockReadGuard<'_, PeerCache> =
                    self.inner.peer_cache.read().await;
                let users: Vec<tl::enums::InputUser> = user_ids
                    .iter()
                    .map(|&id| {
                        let hash = cache.users.get(&id).copied().unwrap_or(0);
                        tl::enums::InputUser::InputUser(tl::types::InputUser {
                            user_id: id,
                            access_hash: hash,
                        })
                    })
                    .collect();
                let req = tl::functions::channels::InviteToChannel {
                    channel: tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                        channel_id: c.channel_id,
                        access_hash: c.access_hash,
                    }),
                    users,
                };
                self.rpc_write(&req).await
            }
            tl::enums::InputPeer::Chat(c) => {
                // Legacy groups: add one at a time
                for &id in user_ids {
                    let hash = self
                        .inner
                        .peer_cache
                        .read()
                        .await
                        .users
                        .get(&id)
                        .copied()
                        .unwrap_or(0);
                    let req = tl::functions::messages::AddChatUser {
                        chat_id: c.chat_id,
                        user_id: tl::enums::InputUser::InputUser(tl::types::InputUser {
                            user_id: id,
                            access_hash: hash,
                        }),
                        fwd_limit: 0,
                    };
                    self.rpc_write(&req).await?;
                }
                Ok(())
            }
            _ => Err(InvocationError::Deserialize(
                "invite_users: peer must be a chat or channel".into(),
            )),
        }
    }

    /// Delete messages up to `max_id` from a chat's history on your side.
    /// With `revoke: true` on a group/channel you admin, it deletes for
    /// everyone instead of just you.
    pub async fn delete_chat_history(
        &self,
        peer: impl Into<PeerRef>,
        max_id: i32,
        revoke: bool,
    ) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        match &input_peer {
            tl::enums::InputPeer::Channel(c) => {
                let req = tl::functions::channels::DeleteHistory {
                    for_everyone: revoke,
                    channel: tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                        channel_id: c.channel_id,
                        access_hash: c.access_hash,
                    }),
                    max_id,
                };
                self.rpc_write(&req).await
            }
            _ => {
                // For regular chats the server may return an offset != 0, indicating
                // that more messages remain and we must call again.
                loop {
                    let req = tl::functions::messages::DeleteHistory {
                        just_clear: false,
                        revoke,
                        peer: input_peer.clone(),
                        max_id,
                        min_date: None,
                        max_date: None,
                    };
                    let body = self.rpc_call_raw(&req).await?;
                    let mut cur = Cursor::from_slice(&body);
                    let tl::enums::messages::AffectedHistory::AffectedHistory(result) =
                        tl::enums::messages::AffectedHistory::deserialize(&mut cur)?;
                    if result.offset == 0 {
                        break;
                    }
                }
                Ok(())
            }
        }
    }

    /// Create a basic group chat with `title` and the given members. This is
    /// the small, old-style group with a low member cap - use
    /// [`Self::create_channel`] for a supergroup if you need more room or
    /// admin tooling.
    pub async fn create_group(
        &self,
        title: impl Into<String>,
        user_ids: Vec<i64>,
    ) -> Result<tl::enums::Chat, InvocationError> {
        let cache = self.inner.peer_cache.read().await;
        let users: Vec<tl::enums::InputUser> = user_ids
            .into_iter()
            .map(|id| {
                let hash = cache.users.get(&id).copied().unwrap_or(0);
                tl::enums::InputUser::InputUser(tl::types::InputUser {
                    user_id: id,
                    access_hash: hash,
                })
            })
            .collect();

        let req = tl::functions::messages::CreateChat {
            users,
            title: title.into(),
            ttl_period: None,
        };
        let body = self.rpc_call_raw(&req).await?;
        let mut cur = Cursor::from_slice(&body);
        let updates = tl::enums::Updates::deserialize(&mut cur)?;
        // Extract the chat from updates
        let chats = match updates {
            tl::enums::Updates::Updates(u) => u.chats,
            tl::enums::Updates::Combined(u) => u.chats,
            _ => vec![],
        };
        chats
            .into_iter()
            .next()
            .ok_or_else(|| InvocationError::Deserialize("create_group: no chat in response".into()))
    }

    /// Create a channel or supergroup. `broadcast: true` makes a broadcast
    /// channel (only admins post); `false` makes a supergroup (everyone can,
    /// by default).
    pub async fn create_channel(
        &self,
        title: impl Into<String>,
        about: impl Into<String>,
        broadcast: bool,
    ) -> Result<tl::enums::Chat, InvocationError> {
        let req = tl::functions::channels::CreateChannel {
            broadcast,
            megagroup: !broadcast,
            for_import: false,
            forum: false,
            title: title.into(),
            about: about.into(),
            geo_point: None,
            address: None,
            ttl_period: None,
        };
        let body = self.rpc_call_raw(&req).await?;
        let mut cur = Cursor::from_slice(&body);
        let updates = tl::enums::Updates::deserialize(&mut cur)?;
        let chats = match updates {
            tl::enums::Updates::Updates(u) => u.chats,
            tl::enums::Updates::Combined(u) => u.chats,
            _ => vec![],
        };
        chats.into_iter().next().ok_or_else(|| {
            InvocationError::Deserialize("create_channel: no chat in response".into())
        })
    }

    /// Set the default permissions for non-admin members of a chat, using a
    /// builder closure over [`crate::participants::BannedRightsBuilder`].
    pub async fn edit_chat_default_banned_rights(
        &self,
        peer: impl Into<PeerRef>,
        build: impl FnOnce(
            crate::participants::BannedRightsBuilder,
        ) -> crate::participants::BannedRightsBuilder,
    ) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let rights = build(crate::participants::BannedRightsBuilder::new()).into_tl();
        let req = tl::functions::messages::EditChatDefaultBannedRights {
            peer: input_peer,
            banned_rights: rights,
        };
        self.rpc_write(&req).await
    }

    /// Add one or more users to a chat by user ID.
    pub async fn invite_users(
        &self,
        peer: impl Into<PeerRef>,
        user_ids: &[i64],
    ) -> Result<(), InvocationError> {
        if user_ids.is_empty() {
            return Ok(());
        }
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;

        match &input_peer {
            tl::enums::InputPeer::Channel(c) => {
                let cache = self.inner.peer_cache.read().await;
                let users: Vec<tl::enums::InputUser> = user_ids
                    .iter()
                    .map(|&id| {
                        let hash = cache.users.get(&id).copied().unwrap_or(0);
                        tl::enums::InputUser::InputUser(tl::types::InputUser {
                            user_id: id,
                            access_hash: hash,
                        })
                    })
                    .collect();
                let req = tl::functions::channels::InviteToChannel {
                    channel: tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                        channel_id: c.channel_id,
                        access_hash: c.access_hash,
                    }),
                    users,
                };
                self.rpc_write(&req).await
            }
            tl::enums::InputPeer::Chat(c) => {
                // Legacy groups: add one at a time
                for &id in user_ids {
                    let hash = self
                        .inner
                        .peer_cache
                        .read()
                        .await
                        .users
                        .get(&id)
                        .copied()
                        .unwrap_or(0);
                    let req = tl::functions::messages::AddChatUser {
                        chat_id: c.chat_id,
                        user_id: tl::enums::InputUser::InputUser(tl::types::InputUser {
                            user_id: id,
                            access_hash: hash,
                        }),
                        fwd_limit: 0,
                    };
                    self.rpc_write(&req).await?;
                }
                Ok(())
            }
            _ => Err(InvocationError::Deserialize(
                "invite_users: peer must be a chat or channel".into(),
            )),
        }
    }

    /// Set the auto-delete timer for new messages in a chat, in seconds.
    /// Pass `0` to turn it off.
    pub async fn set_history_ttl(
        &self,
        peer: impl Into<PeerRef>,
        period: i32,
    ) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let req = tl::functions::messages::SetHistoryTtl {
            peer: input_peer,
            period,
        };
        self.rpc_write(&req).await
    }

    /// List the group chats you have in common with a user. `max_id`/`limit`
    /// page through results if there are a lot.
    pub async fn get_common_chats(
        &self,
        user_id: i64,
        max_id: i64,
        limit: i32,
    ) -> Result<Vec<tl::enums::Chat>, InvocationError> {
        let hash = self
            .inner
            .peer_cache
            .read()
            .await
            .users
            .get(&user_id)
            .copied()
            .unwrap_or(0);
        let req = tl::functions::messages::GetCommonChats {
            user_id: tl::enums::InputUser::InputUser(tl::types::InputUser {
                user_id,
                access_hash: hash,
            }),
            max_id,
            limit,
        };
        let body = self.rpc_call_raw(&req).await?;
        let mut cur = Cursor::from_slice(&body);
        let chats = tl::enums::messages::Chats::deserialize(&mut cur)?;
        Ok(match chats {
            tl::enums::messages::Chats::Chats(c) => c.chats,
            tl::enums::messages::Chats::Slice(c) => c.chats,
        })
    }

    /// List the admins of a chat.
    pub async fn get_chat_administrators(
        &self,
        peer: impl Into<PeerRef>,
    ) -> Result<Vec<crate::participants::Participant>, InvocationError> {
        use ferogram_tl_types::{Cursor, Deserializable};
        let peer = peer.into().resolve(self).await?;
        match &peer {
            tl::enums::Peer::Channel(c) => {
                let access_hash = self
                    .inner
                    .peer_cache
                    .read()
                    .await
                    .channels
                    .get(&c.channel_id)
                    .map(|&(hash, _)| hash)
                    .unwrap_or(0);
                let req = tl::functions::channels::GetParticipants {
                    channel: tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                        channel_id: c.channel_id,
                        access_hash,
                    }),
                    filter: tl::enums::ChannelParticipantsFilter::ChannelParticipantsAdmins,
                    offset: 0,
                    limit: 200,
                    hash: 0,
                };
                let body = self.rpc_call_raw(&req).await?;
                let mut cur = Cursor::from_slice(&body);
                let raw = match tl::enums::channels::ChannelParticipants::deserialize(&mut cur)? {
                    tl::enums::channels::ChannelParticipants::ChannelParticipants(p) => p,
                    tl::enums::channels::ChannelParticipants::NotModified => return Ok(vec![]),
                };
                let user_map: std::collections::HashMap<i64, tl::types::User> = raw
                    .users
                    .into_iter()
                    .filter_map(|u| match u {
                        tl::enums::User::User(u) => Some((u.id, u)),
                        _ => None,
                    })
                    .collect();
                Ok(raw
                    .participants
                    .into_iter()
                    .filter_map(|p| {
                        crate::participants::Participant::from_channel_participant(p, &user_map)
                    })
                    .collect())
            }
            tl::enums::Peer::Chat(_) => {
                // For basic groups return all members; callers check is_admin flag.
                self.get_participants(peer, 0).await
            }
            _ => Err(InvocationError::Deserialize(
                "get_chat_administrators: peer must be a chat or channel".into(),
            )),
        }
    }

    /// Transfer ownership of a channel or supergroup to another user. You'll
    /// need their confirmation on Telegram's end too - this just starts the
    /// transfer. `password` is your 2FA password, required by Telegram for
    /// this regardless of whether you'd normally need it to log in.
    pub async fn transfer_chat_ownership(
        &self,
        peer: impl Into<PeerRef>,
        new_owner_id: i64,
        password: tl::enums::InputCheckPasswordSrp,
    ) -> Result<(), InvocationError> {
        use ferogram_tl_types as tl;
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;

        // Resolve the new owner to InputUser
        let owner_peer = tl::enums::Peer::User(tl::types::PeerUser {
            user_id: new_owner_id,
        });
        let owner_input = self
            .inner
            .peer_cache
            .read()
            .await
            .peer_to_input(&owner_peer)?;
        let user_id = match owner_input {
            tl::enums::InputPeer::User(u) => {
                tl::enums::InputUser::InputUser(tl::types::InputUser {
                    user_id: u.user_id,
                    access_hash: u.access_hash,
                })
            }
            _ => {
                return Err(InvocationError::Deserialize(
                    "transfer_chat_ownership: new owner must be a user".into(),
                ));
            }
        };

        let req = tl::functions::messages::EditChatCreator {
            peer: input_peer,
            user_id,
            password,
        };
        self.rpc_call_raw(&req).await?;
        Ok(())
    }

    /// Get the ID of the discussion group linked to a broadcast channel, or
    /// `None` if it doesn't have one.
    pub async fn get_linked_channel(
        &self,
        peer: impl Into<PeerRef>,
    ) -> Result<Option<i64>, InvocationError> {
        use ferogram_tl_types as tl;
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let channel = match &input_peer {
            tl::enums::InputPeer::Channel(c) => {
                tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                    channel_id: c.channel_id,
                    access_hash: c.access_hash,
                })
            }
            _ => {
                return Err(InvocationError::Deserialize(
                    "get_linked_channel: peer must be a channel or supergroup".into(),
                ));
            }
        };
        let req = tl::functions::channels::GetFullChannel { channel };
        let body = self.rpc_call_raw(&req).await?;
        let mut cur = Cursor::from_slice(&body);
        let full = tl::enums::messages::ChatFull::deserialize(&mut cur)?;
        let linked = match full {
            tl::enums::messages::ChatFull::ChatFull(f) => match f.full_chat {
                tl::enums::ChatFull::ChannelFull(cf) => cf.linked_chat_id,
                _ => None,
            },
        };
        Ok(linked)
    }

    /// Read the admin action log for a supergroup or channel: who banned
    /// who, what got deleted, title changes, and so on. You need to be an
    /// admin of `peer` to call this. `query` filters by text, and
    /// `max_id`/`min_id` page through results - pass `0` for both to start
    /// from the most recent event.
    pub async fn get_admin_log(
        &self,
        peer: impl Into<PeerRef>,
        query: impl Into<String>,
        limit: i32,
        max_id: i64,
        min_id: i64,
    ) -> Result<Vec<tl::types::ChannelAdminLogEvent>, InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let channel = match &input_peer {
            tl::enums::InputPeer::Channel(c) => {
                tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                    channel_id: c.channel_id,
                    access_hash: c.access_hash,
                })
            }
            _ => {
                return Err(InvocationError::Deserialize(
                    "get_admin_log: peer must be a channel or supergroup".into(),
                ));
            }
        };
        let req = tl::functions::channels::GetAdminLog {
            channel,
            q: query.into(),
            events_filter: None,
            admins: None,
            max_id,
            min_id,
            limit,
        };
        let body = self.rpc_call_raw(&req).await?;
        let mut cur = Cursor::from_slice(&body);
        let tl::enums::channels::AdminLogResults::AdminLogResults(result) =
            tl::enums::channels::AdminLogResults::deserialize(&mut cur)?;
        self.cache_users_slice(&result.users).await;
        self.cache_chats_slice(&result.chats).await;
        Ok(result
            .events
            .into_iter()
            .map(|e| match e {
                tl::enums::ChannelAdminLogEvent::ChannelAdminLogEvent(ev) => ev,
            })
            .collect())
    }

    /// Turn content protection on or off for a chat - when enabled, members
    /// can't forward or save media from it.
    pub async fn toggle_no_forwards(
        &self,
        peer: impl Into<PeerRef>,
        enabled: bool,
    ) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let req = tl::functions::messages::ToggleNoForwards {
            peer: input_peer,
            enabled,
            request_msg_id: None,
        };
        self.rpc_write(&req).await
    }

    /// Set the emoji theme for a chat. `emoticon` must be one of the emoji
    /// Telegram's official clients offer in the chat theme picker, not
    /// arbitrary text.
    pub async fn set_chat_theme(
        &self,
        peer: impl Into<PeerRef>,
        emoticon: impl Into<String>,
    ) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let req = tl::functions::messages::SetChatTheme {
            peer: input_peer,
            theme: tl::enums::InputChatTheme::InputChatTheme(tl::types::InputChatTheme {
                emoticon: emoticon.into(),
            }),
        };
        self.rpc_write(&req).await
    }

    /// Set which reactions are allowed in a chat - all of them, none, or a
    /// specific list.
    pub async fn set_chat_reactions(
        &self,
        peer: impl Into<PeerRef>,
        reactions: tl::enums::ChatReactions,
    ) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let req = tl::functions::messages::SetChatAvailableReactions {
            peer: input_peer,
            available_reactions: reactions,
            reactions_limit: None,
            paid_enabled: None,
        };
        self.rpc_write(&req).await
    }

    /// List the identities you can post as in a chat - your own account, or
    /// any channel you admin that's linked to it.
    pub async fn get_send_as_peers(
        &self,
        peer: impl Into<PeerRef>,
    ) -> Result<Vec<tl::enums::Peer>, InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let req = tl::functions::channels::GetSendAs {
            for_paid_reactions: false,
            for_live_stories: false,
            peer: input_peer,
        };
        let body = self.rpc_call_raw(&req).await?;
        let mut cur = Cursor::from_slice(&body);
        let tl::enums::channels::SendAsPeers::SendAsPeers(result) =
            tl::enums::channels::SendAsPeers::deserialize(&mut cur)?;
        self.cache_users_slice(&result.users).await;
        self.cache_chats_slice(&result.chats).await;
        Ok(result
            .peers
            .into_iter()
            .map(|p| match p {
                tl::enums::SendAsPeer::SendAsPeer(sp) => sp.peer,
            })
            .collect())
    }

    /// Set which identity you post as in a chat by default, from the options
    /// [`Self::get_send_as_peers`] returns.
    pub async fn set_default_send_as(
        &self,
        peer: impl Into<PeerRef>,
        send_as_peer: impl Into<PeerRef>,
    ) -> Result<(), InvocationError> {
        let peer = peer.into().resolve(self).await?;
        let input_peer = self.inner.peer_cache.read().await.peer_to_input(&peer)?;
        let send_as = send_as_peer.into().resolve(self).await?;
        let send_as_input = self.inner.peer_cache.read().await.peer_to_input(&send_as)?;
        let req = tl::functions::messages::SaveDefaultSendAs {
            peer: input_peer,
            send_as: send_as_input,
        };
        self.rpc_write(&req).await
    }
}