Skip to main content

twapi_v2/api/
get_2_dm_events.rs

1use crate::fields::{
2    dm_event_fields::DmEventFields, media_fields::MediaFields, tweet_fields::TweetFields,
3    user_fields::UserFields,
4};
5use crate::responses::{dm_events::DmEvents, errors::Errors, includes::Includes, meta::Meta};
6use crate::{
7    api::{Authentication, TwapiOptions, execute_twitter, make_url},
8    error::Error,
9    headers::Headers,
10};
11use itertools::Itertools;
12use reqwest::RequestBuilder;
13use serde::{Deserialize, Serialize};
14use std::collections::HashSet;
15
16const URL: &str = "/2/dm_events";
17
18#[derive(Serialize, Deserialize, Debug, Eq, Hash, PartialEq, Clone)]
19#[derive(Default)]
20pub enum EventTypes {
21    #[serde(rename = "MessageCreate")]
22    #[default]
23    Messagecreate,
24    #[serde(rename = "ParticipantsJoin")]
25    Participantsjoin,
26    #[serde(rename = "ParticipantsLeave")]
27    Participantsleave,
28}
29
30impl std::fmt::Display for EventTypes {
31    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
32        match self {
33            Self::Messagecreate => write!(f, "MessageCreate"),
34            Self::Participantsjoin => write!(f, "ParticipantsJoin"),
35            Self::Participantsleave => write!(f, "ParticipantsLeave"),
36        }
37    }
38}
39
40
41#[derive(Serialize, Deserialize, Debug, Eq, Hash, PartialEq, Clone)]
42#[derive(Default)]
43pub enum Expansions {
44    #[serde(rename = "attachments.media_keys")]
45    #[default]
46    AttachmentsMediaKeys,
47    #[serde(rename = "referenced_tweets.id")]
48    ReferencedTweetsId,
49    #[serde(rename = "sender_id")]
50    SenderId,
51    #[serde(rename = "participant_ids")]
52    ParticipantIds,
53}
54
55impl Expansions {
56    pub fn all() -> HashSet<Self> {
57        let mut result = HashSet::new();
58        result.insert(Self::AttachmentsMediaKeys);
59        result.insert(Self::ReferencedTweetsId);
60        result.insert(Self::SenderId);
61        result.insert(Self::ParticipantIds);
62        result
63    }
64}
65
66impl std::fmt::Display for Expansions {
67    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
68        match self {
69            Self::AttachmentsMediaKeys => write!(f, "attachments.media_keys"),
70            Self::ReferencedTweetsId => write!(f, "referenced_tweets.id"),
71            Self::SenderId => write!(f, "sender_id"),
72            Self::ParticipantIds => write!(f, "participant_ids"),
73        }
74    }
75}
76
77
78#[derive(Debug, Clone, Default)]
79pub struct Api {
80    dm_event_fields: Option<HashSet<DmEventFields>>,
81    event_types: Option<EventTypes>,
82    expansions: Option<HashSet<Expansions>>,
83    max_results: Option<usize>,
84    media_fields: Option<HashSet<MediaFields>>,
85    pagination_token: Option<String>,
86    tweet_fields: Option<HashSet<TweetFields>>,
87    user_fields: Option<HashSet<UserFields>>,
88    twapi_options: Option<TwapiOptions>,
89}
90
91impl Api {
92    pub fn new() -> Self {
93        Self {
94            ..Default::default()
95        }
96    }
97
98    pub fn all() -> Self {
99        Self {
100            dm_event_fields: Some(DmEventFields::all()),
101            expansions: Some(Expansions::all()),
102            media_fields: Some(MediaFields::all()),
103            tweet_fields: Some(TweetFields::organic()),
104            user_fields: Some(UserFields::all()),
105            max_results: Some(100),
106            ..Default::default()
107        }
108    }
109
110    pub fn open() -> Self {
111        Self {
112            dm_event_fields: Some(DmEventFields::all()),
113            expansions: Some(Expansions::all()),
114            media_fields: Some(MediaFields::open()),
115            tweet_fields: Some(TweetFields::open()),
116            user_fields: Some(UserFields::all()),
117            max_results: Some(100),
118            ..Default::default()
119        }
120    }
121
122    pub fn dm_event_fields(mut self, value: HashSet<DmEventFields>) -> Self {
123        self.dm_event_fields = Some(value);
124        self
125    }
126
127    pub fn event_types(mut self, value: EventTypes) -> Self {
128        self.event_types = Some(value);
129        self
130    }
131
132    pub fn expansions(mut self, value: HashSet<Expansions>) -> Self {
133        self.expansions = Some(value);
134        self
135    }
136
137    pub fn max_results(mut self, value: usize) -> Self {
138        self.max_results = Some(value);
139        self
140    }
141
142    pub fn media_fields(mut self, value: HashSet<MediaFields>) -> Self {
143        self.media_fields = Some(value);
144        self
145    }
146
147    pub fn pagination_token(mut self, value: &str) -> Self {
148        self.pagination_token = Some(value.to_owned());
149        self
150    }
151
152    pub fn tweet_fields(mut self, value: HashSet<TweetFields>) -> Self {
153        self.tweet_fields = Some(value);
154        self
155    }
156
157    pub fn user_fields(mut self, value: HashSet<UserFields>) -> Self {
158        self.user_fields = Some(value);
159        self
160    }
161
162    pub fn twapi_options(mut self, value: TwapiOptions) -> Self {
163        self.twapi_options = Some(value);
164        self
165    }
166
167    pub fn build(&self, authentication: &impl Authentication) -> RequestBuilder {
168        let mut query_parameters = vec![];
169        if let Some(dm_event_fields) = self.dm_event_fields.as_ref() {
170            query_parameters.push(("dm_event.fields", dm_event_fields.iter().join(",")));
171        }
172        if let Some(event_types) = self.event_types.as_ref() {
173            query_parameters.push(("event_types", event_types.to_string()));
174        }
175        if let Some(expansions) = self.expansions.as_ref() {
176            query_parameters.push(("expansions", expansions.iter().join(",")));
177        }
178        if let Some(max_results) = self.max_results.as_ref() {
179            query_parameters.push(("max_results", max_results.to_string()));
180        }
181        if let Some(media_fields) = self.media_fields.as_ref() {
182            query_parameters.push(("media.fields", media_fields.iter().join(",")));
183        }
184        if let Some(pagination_token) = self.pagination_token.as_ref() {
185            query_parameters.push(("pagination_token", pagination_token.to_string()));
186        }
187        if let Some(tweet_fields) = self.tweet_fields.as_ref() {
188            query_parameters.push(("tweet.fields", tweet_fields.iter().join(",")));
189        }
190        if let Some(user_fields) = self.user_fields.as_ref() {
191            query_parameters.push(("user.fields", user_fields.iter().join(",")));
192        }
193        let client = reqwest::Client::new();
194        let url = make_url(&self.twapi_options, URL);
195        let builder = client.get(&url).query(&query_parameters);
196        authentication.execute(
197            builder,
198            "GET",
199            &url,
200            &query_parameters
201                .iter()
202                .map(|it| (it.0, it.1.as_str()))
203                .collect::<Vec<_>>(),
204        )
205    }
206
207    pub async fn execute(
208        &self,
209        authentication: &impl Authentication,
210    ) -> Result<(Response, Headers), Error> {
211        execute_twitter(|| self.build(authentication), &self.twapi_options).await
212    }
213}
214
215#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
216pub struct Response {
217    #[serde(skip_serializing_if = "Option::is_none")]
218    pub data: Option<Vec<DmEvents>>,
219    #[serde(skip_serializing_if = "Option::is_none")]
220    pub errors: Option<Vec<Errors>>,
221    #[serde(skip_serializing_if = "Option::is_none")]
222    pub includes: Option<Includes>,
223    #[serde(skip_serializing_if = "Option::is_none")]
224    pub meta: Option<Meta>,
225    #[serde(flatten)]
226    pub extra: std::collections::HashMap<String, serde_json::Value>,
227}
228
229impl Response {
230    pub fn is_empty_extra(&self) -> bool {
231        let res = self.extra.is_empty()
232            && self
233                .data
234                .as_ref()
235                .map(|it| it.iter().all(|item| item.is_empty_extra()))
236                .unwrap_or(true)
237            && self
238                .errors
239                .as_ref()
240                .map(|it| it.iter().all(|item| item.is_empty_extra()))
241                .unwrap_or(true)
242            && self
243                .includes
244                .as_ref()
245                .map(|it| it.is_empty_extra())
246                .unwrap_or(true)
247            && self
248                .meta
249                .as_ref()
250                .map(|it| it.is_empty_extra())
251                .unwrap_or(true);
252        if !res {
253            println!("Response {:?}", self.extra);
254        }
255        res
256    }
257}