tg_flows/types/
me.rs

1use std::ops::Deref;
2
3use serde::{Deserialize, Serialize};
4
5use crate::types::User;
6
7/// Returned only in [`GetMe`].
8///
9/// [`GetMe`]: crate::payloads::GetMe
10#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
11pub struct Me {
12    #[serde(flatten)]
13    pub user: User,
14
15    /// `true`, if the bot can be invited to groups.
16    pub can_join_groups: bool,
17
18    /// `true`, if [privacy mode] is disabled for the bot.
19    ///
20    /// [privacy mode]: https://core.telegram.org/bots#privacy-mode
21    pub can_read_all_group_messages: bool,
22
23    /// `true`, if the bot supports inline queries.
24    pub supports_inline_queries: bool,
25}
26
27impl Me {
28    /// Returns the username of the bot.
29    #[must_use]
30    pub fn username(&self) -> &str {
31        self.user.username.as_deref().expect("Bots must have usernames")
32    }
33
34    /// Returns a username mention of this bot.
35    #[must_use]
36    pub fn mention(&self) -> String {
37        format!("@{}", self.username())
38    }
39
40    /// Returns an URL that links to this bot in the form of `t.me/<...>`.
41    #[must_use]
42    pub fn tme_url(&self) -> url::Url {
43        format!("https://t.me/{}", self.username()).parse().unwrap()
44    }
45}
46
47impl Deref for Me {
48    type Target = User;
49
50    fn deref(&self) -> &Self::Target {
51        &self.user
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use crate::types::{Me, User, UserId};
58
59    #[test]
60    fn convenience_methods_work() {
61        let me = Me {
62            user: User {
63                id: UserId(42),
64                is_bot: true,
65                first_name: "First".to_owned(),
66                last_name: None,
67                username: Some("SomethingSomethingBot".to_owned()),
68                language_code: None,
69                is_premium: false,
70                added_to_attachment_menu: false,
71            },
72            can_join_groups: false,
73            can_read_all_group_messages: false,
74            supports_inline_queries: false,
75        };
76
77        assert_eq!(me.username(), "SomethingSomethingBot");
78        assert_eq!(me.mention(), "@SomethingSomethingBot");
79        assert_eq!(me.tme_url(), "https://t.me/SomethingSomethingBot".parse().unwrap());
80    }
81}