tg_flows/types/
recipient.rs

1use derive_more::{Display, From};
2use serde::{Deserialize, Serialize};
3
4use crate::types::{ChatId, UserId};
5
6/// A unique identifier for the target chat or username of the target channel
7/// (in the format `@channelusername`).
8#[derive(Clone, PartialEq, Eq, Hash)]
9#[derive(Debug, Display, From)]
10#[derive(Serialize, Deserialize)]
11#[serde(untagged)]
12pub enum Recipient {
13    /// A chat identifier.
14    #[display(fmt = "{_0}")]
15    Id(ChatId),
16
17    /// A channel username (in the format @channelusername).
18    #[display(fmt = "{_0}")]
19    ChannelUsername(String),
20}
21
22impl From<UserId> for Recipient {
23    fn from(id: UserId) -> Self {
24        Self::Id(id.into())
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    fn chat_id_id_serialization() {
34        let expected_json = String::from(r#"123456"#);
35        let actual_json = serde_json::to_string(&Recipient::Id(ChatId(123_456))).unwrap();
36
37        assert_eq!(expected_json, actual_json)
38    }
39
40    #[test]
41    fn chat_id_channel_username_serialization() {
42        let expected_json = String::from(r#""@username""#);
43        let actual_json =
44            serde_json::to_string(&Recipient::ChannelUsername(String::from("@username"))).unwrap();
45
46        assert_eq!(expected_json, actual_json)
47    }
48}