layer-client 0.5.0

Production-grade async Telegram 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
// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
// SPDX-License-Identifier: MIT OR Apache-2.0

// NOTE:
// The "Layer" project is no longer maintained or supported.
// Its original purpose for personal SDK/APK experimentation and learning
// has been fulfilled.
//
// Please use Ferogram instead:
// https://github.com/ankit-chaubey/ferogram
// Ferogram will receive future updates and development, although progress
// may be slower.
//
// Ferogram is an async Telegram MTProto client library written in Rust.
// Its implementation follows the behaviour of the official Telegram clients,
// particularly Telegram Desktop and TDLib, and aims to provide a clean and
// modern async interface for building Telegram clients and tools.

//! Typed wrappers over raw TL user and chat types.
//!
//! The raw TL layer has `tl::enums::User` (two variants: `Empty` / `User`) and
//! `tl::enums::Chat` (five variants: `Empty`, `Chat`, `Forbidden`,
//! `Channel`, `ChannelForbidden`).  Working with them directly requires constant
//! pattern-matching.  This module provides three thin wrappers: [`User`],
//! [`Group`], and [`Channel`]: with uniform accessor APIs.

use layer_tl_types as tl;

// User

/// Typed wrapper over `tl::enums::User`.
#[derive(Debug, Clone)]
pub struct User {
    pub raw: tl::enums::User,
}

impl User {
    /// Wrap a raw TL user.
    pub fn from_raw(raw: tl::enums::User) -> Option<Self> {
        match &raw {
            tl::enums::User::Empty(_) => None,
            tl::enums::User::User(_) => Some(Self { raw }),
        }
    }

    fn inner(&self) -> &tl::types::User {
        match &self.raw {
            tl::enums::User::User(u) => u,
            tl::enums::User::Empty(_) => unreachable!("User::Empty filtered in from_raw"),
        }
    }

    /// Telegram user ID.
    pub fn id(&self) -> i64 {
        self.inner().id
    }

    /// Access hash needed for API calls.
    pub fn access_hash(&self) -> Option<i64> {
        self.inner().access_hash
    }

    /// First name.
    pub fn first_name(&self) -> Option<&str> {
        self.inner().first_name.as_deref()
    }

    /// Last name.
    pub fn last_name(&self) -> Option<&str> {
        self.inner().last_name.as_deref()
    }

    /// Username (without `@`).
    pub fn username(&self) -> Option<&str> {
        self.inner().username.as_deref()
    }

    /// Phone number, if visible.
    pub fn phone(&self) -> Option<&str> {
        self.inner().phone.as_deref()
    }

    /// `true` if this is a verified account.
    pub fn verified(&self) -> bool {
        self.inner().verified
    }

    /// `true` if this is a bot account.
    pub fn bot(&self) -> bool {
        self.inner().bot
    }

    /// `true` if the account is deleted.
    pub fn deleted(&self) -> bool {
        self.inner().deleted
    }

    /// `true` if the current user has blocked this user.
    pub fn blocked(&self) -> bool {
        false
    }

    /// `true` if this is a premium account.
    pub fn premium(&self) -> bool {
        self.inner().premium
    }

    /// Full display name (`first_name [last_name]`).
    pub fn full_name(&self) -> String {
        match (self.first_name(), self.last_name()) {
            (Some(f), Some(l)) => format!("{f} {l}"),
            (Some(f), None) => f.to_string(),
            (None, Some(l)) => l.to_string(),
            (None, None) => String::new(),
        }
    }

    /// All active usernames (including the primary username).
    pub fn usernames(&self) -> Vec<&str> {
        let mut names = Vec::new();
        // Primary username
        if let Some(u) = self.inner().username.as_deref() {
            names.push(u);
        }
        // Additional usernames
        if let Some(extras) = &self.inner().usernames {
            for u in extras {
                let tl::enums::Username::Username(un) = u;
                if un.active {
                    names.push(un.username.as_str());
                }
            }
        }
        names
    }

    /// The user's current online status.
    pub fn status(&self) -> Option<&tl::enums::UserStatus> {
        self.inner().status.as_ref()
    }

    /// Profile photo, if set.
    pub fn photo(&self) -> Option<&tl::types::UserProfilePhoto> {
        match self.inner().photo.as_ref()? {
            tl::enums::UserProfilePhoto::UserProfilePhoto(p) => Some(p),
            _ => None,
        }
    }

    /// `true` if this is the currently logged-in user.
    pub fn is_self(&self) -> bool {
        self.inner().is_self
    }

    /// `true` if this user is in the logged-in user's contact list.
    pub fn contact(&self) -> bool {
        self.inner().contact
    }

    /// `true` if the logged-in user is also in this user's contact list.
    pub fn mutual_contact(&self) -> bool {
        self.inner().mutual_contact
    }

    /// `true` if this account has been flagged as a scam.
    pub fn scam(&self) -> bool {
        self.inner().scam
    }

    /// `true` if this account has been restricted (e.g. spam-banned).
    pub fn restricted(&self) -> bool {
        self.inner().restricted
    }

    /// `true` if the bot does not display in inline mode publicly.
    pub fn bot_privacy(&self) -> bool {
        self.inner().bot_nochats
    }

    /// `true` if the bot supports being added to groups.
    pub fn bot_supports_chats(&self) -> bool {
        !self.inner().bot_nochats
    }

    /// `true` if the bot can be used inline even without a location share.
    pub fn bot_inline_geo(&self) -> bool {
        self.inner().bot_inline_geo
    }

    /// `true` if this account belongs to Telegram support staff.
    pub fn support(&self) -> bool {
        self.inner().support
    }

    /// Language code reported by the user's client.
    pub fn lang_code(&self) -> Option<&str> {
        self.inner().lang_code.as_deref()
    }

    /// Restriction reasons (why this account is unavailable in certain regions).
    pub fn restriction_reason(&self) -> Vec<&tl::enums::RestrictionReason> {
        self.inner()
            .restriction_reason
            .as_deref()
            .unwrap_or(&[])
            .iter()
            .collect()
    }

    /// Bot inline placeholder text (shown in the compose bar when the user activates inline mode).
    pub fn bot_inline_placeholder(&self) -> Option<&str> {
        self.inner().bot_inline_placeholder.as_deref()
    }

    /// Convert to a `Peer` for use in API calls.
    pub fn as_peer(&self) -> tl::enums::Peer {
        tl::enums::Peer::User(tl::types::PeerUser { user_id: self.id() })
    }

    /// Convert to an `InputPeer` for API calls (requires access hash).
    pub fn as_input_peer(&self) -> tl::enums::InputPeer {
        match self.inner().access_hash {
            Some(ah) => tl::enums::InputPeer::User(tl::types::InputPeerUser {
                user_id: self.id(),
                access_hash: ah,
            }),
            None => tl::enums::InputPeer::PeerSelf,
        }
    }
}

impl std::fmt::Display for User {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = self.full_name();
        if let Some(uname) = self.username() {
            write!(f, "{name} (@{uname})")
        } else {
            write!(f, "{name} [{}]", self.id())
        }
    }
}

// Group

/// Typed wrapper over `tl::types::Chat`.
#[derive(Debug, Clone)]
pub struct Group {
    pub raw: tl::types::Chat,
}

impl Group {
    /// Wrap from a raw `tl::enums::Chat`, returning `None` if it is not a
    /// basic group (i.e. empty, forbidden, or a channel).
    pub fn from_raw(raw: tl::enums::Chat) -> Option<Self> {
        match raw {
            tl::enums::Chat::Chat(c) => Some(Self { raw: c }),
            tl::enums::Chat::Empty(_)
            | tl::enums::Chat::Forbidden(_)
            | tl::enums::Chat::Channel(_)
            | tl::enums::Chat::ChannelForbidden(_) => None,
        }
    }

    /// Group ID.
    pub fn id(&self) -> i64 {
        self.raw.id
    }

    /// Group title.
    pub fn title(&self) -> &str {
        &self.raw.title
    }

    /// Member count.
    pub fn participants_count(&self) -> i32 {
        self.raw.participants_count
    }

    /// `true` if the logged-in user is the creator.
    pub fn creator(&self) -> bool {
        self.raw.creator
    }

    /// `true` if the group has been migrated to a supergroup.
    pub fn migrated_to(&self) -> Option<&tl::enums::InputChannel> {
        self.raw.migrated_to.as_ref()
    }

    /// Convert to a `Peer`.
    pub fn as_peer(&self) -> tl::enums::Peer {
        tl::enums::Peer::Chat(tl::types::PeerChat { chat_id: self.id() })
    }

    /// Convert to an `InputPeer`.
    pub fn as_input_peer(&self) -> tl::enums::InputPeer {
        tl::enums::InputPeer::Chat(tl::types::InputPeerChat { chat_id: self.id() })
    }
}

impl std::fmt::Display for Group {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} [group {}]", self.title(), self.id())
    }
}

// Channel

/// The kind of a channel or supergroup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelKind {
    /// A broadcast channel (posts only, no member replies by default).
    Broadcast,
    /// A supergroup (all members can post).
    Megagroup,
    /// A gigagroup / broadcast group (large public broadcast supergroup).
    Gigagroup,
}

/// Typed wrapper over `tl::types::Channel`.
#[derive(Debug, Clone)]
pub struct Channel {
    pub raw: tl::types::Channel,
}

impl Channel {
    /// Wrap from a raw `tl::enums::Chat`, returning `None` if it is not a channel.
    pub fn from_raw(raw: tl::enums::Chat) -> Option<Self> {
        match raw {
            tl::enums::Chat::Channel(c) => Some(Self { raw: c }),
            _ => None,
        }
    }

    /// Channel ID.
    pub fn id(&self) -> i64 {
        self.raw.id
    }

    /// Access hash.
    pub fn access_hash(&self) -> Option<i64> {
        self.raw.access_hash
    }

    /// Channel / supergroup title.
    pub fn title(&self) -> &str {
        &self.raw.title
    }

    /// Username (without `@`), if public.
    pub fn username(&self) -> Option<&str> {
        self.raw.username.as_deref()
    }

    /// `true` if this is a supergroup (not a broadcast channel).
    pub fn megagroup(&self) -> bool {
        self.raw.megagroup
    }

    /// `true` if this is a broadcast channel.
    pub fn broadcast(&self) -> bool {
        self.raw.broadcast
    }

    /// `true` if this is a verified channel.
    pub fn verified(&self) -> bool {
        self.raw.verified
    }

    /// `true` if the channel is restricted.
    pub fn restricted(&self) -> bool {
        self.raw.restricted
    }

    /// `true` if the channel has signatures on posts.
    pub fn signatures(&self) -> bool {
        self.raw.signatures
    }

    /// Approximate member count (may be `None` for private channels).
    pub fn participants_count(&self) -> Option<i32> {
        self.raw.participants_count
    }

    /// The kind of this channel.
    ///
    /// Returns `ChannelKind::Megagroup` for supergroups, `ChannelKind::Broadcast` for
    /// broadcast channels, and `ChannelKind::Gigagroup` for large broadcast groups.
    pub fn kind(&self) -> ChannelKind {
        if self.raw.megagroup {
            ChannelKind::Megagroup
        } else if self.raw.gigagroup {
            ChannelKind::Gigagroup
        } else {
            ChannelKind::Broadcast
        }
    }

    /// All active usernames (including the primary username).
    pub fn usernames(&self) -> Vec<&str> {
        let mut names = Vec::new();
        if let Some(u) = self.raw.username.as_deref() {
            names.push(u);
        }
        if let Some(extras) = &self.raw.usernames {
            for u in extras {
                let tl::enums::Username::Username(un) = u;
                if un.active {
                    names.push(un.username.as_str());
                }
            }
        }
        names
    }

    /// Profile photo, if set.
    pub fn photo(&self) -> Option<&tl::types::ChatPhoto> {
        match &self.raw.photo {
            tl::enums::ChatPhoto::ChatPhoto(p) => Some(p),
            _ => None,
        }
    }

    /// Admin rights granted to the logged-in user in this channel, if any.
    pub fn admin_rights(&self) -> Option<&tl::types::ChatAdminRights> {
        match self.raw.admin_rights.as_ref()? {
            tl::enums::ChatAdminRights::ChatAdminRights(r) => Some(r),
        }
    }

    /// Restriction reasons (why this channel is unavailable in certain regions).
    pub fn restriction_reason(&self) -> Vec<&tl::enums::RestrictionReason> {
        self.raw
            .restriction_reason
            .as_deref()
            .unwrap_or(&[])
            .iter()
            .collect()
    }

    /// Convert to a `Peer`.
    pub fn as_peer(&self) -> tl::enums::Peer {
        tl::enums::Peer::Channel(tl::types::PeerChannel {
            channel_id: self.id(),
        })
    }

    /// Convert to an `InputPeer` (requires access hash).
    pub fn as_input_peer(&self) -> tl::enums::InputPeer {
        match self.raw.access_hash {
            Some(ah) => tl::enums::InputPeer::Channel(tl::types::InputPeerChannel {
                channel_id: self.id(),
                access_hash: ah,
            }),
            None => tl::enums::InputPeer::Empty,
        }
    }

    /// Convert to an `InputChannel` for channel-specific RPCs.
    pub fn as_input_channel(&self) -> tl::enums::InputChannel {
        match self.raw.access_hash {
            Some(ah) => tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                channel_id: self.id(),
                access_hash: ah,
            }),
            None => tl::enums::InputChannel::Empty,
        }
    }
}

impl std::fmt::Display for Channel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(uname) = self.username() {
            write!(f, "{} (@{uname})", self.title())
        } else {
            write!(f, "{} [channel {}]", self.title(), self.id())
        }
    }
}

// Chat enum (unified)

/// A unified chat type: either a basic [`Group`] or a [`Channel`]/supergroup.
#[derive(Debug, Clone)]
pub enum Chat {
    Group(Group),
    Channel(Box<Channel>),
}

impl Chat {
    /// Attempt to construct from a raw `tl::enums::Chat`.
    pub fn from_raw(raw: tl::enums::Chat) -> Option<Self> {
        match &raw {
            tl::enums::Chat::Chat(_) => Group::from_raw(raw).map(Chat::Group),
            tl::enums::Chat::Channel(_) => {
                Channel::from_raw(raw).map(|c| Chat::Channel(Box::new(c)))
            }
            _ => None,
        }
    }

    /// Common ID regardless of variant.
    pub fn id(&self) -> i64 {
        match self {
            Chat::Group(g) => g.id(),
            Chat::Channel(c) => c.id(),
        }
    }

    /// Common title regardless of variant.
    pub fn title(&self) -> &str {
        match self {
            Chat::Group(g) => g.title(),
            Chat::Channel(c) => c.title(),
        }
    }

    /// Convert to a `Peer`.
    pub fn as_peer(&self) -> tl::enums::Peer {
        match self {
            Chat::Group(g) => g.as_peer(),
            Chat::Channel(c) => c.as_peer(),
        }
    }

    /// Convert to an `InputPeer`.
    pub fn as_input_peer(&self) -> tl::enums::InputPeer {
        match self {
            Chat::Group(g) => g.as_input_peer(),
            Chat::Channel(c) => c.as_input_peer(),
        }
    }
}