tgbot 0.47.0

A Telegram Bot library
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
use std::{error::Error, fmt, time::Duration};

use bytes::Bytes;
use futures_util::stream::Stream;
use log::debug;
use reqwest::{
    Client as HttpClient,
    ClientBuilder as HttpClientBuilder,
    Error as HttpError,
    RequestBuilder as HttpRequestBuilder,
};
use serde::de::DeserializeOwned;
use tokio::time::sleep;

use super::payload::{Payload, PayloadError};
use crate::types::{Response, ResponseError};

const DEFAULT_HOST: &str = "https://api.telegram.org";
const DEFAULT_MAX_RETRIES: u8 = 2;

/// A client for interacting with the Telegram Bot API.
#[derive(Clone)]
pub struct Client {
    host: String,
    http_client: HttpClient,
    token: String,
    max_retries: u8,
    max_retry_after: Option<u64>,
}

impl Client {
    /// Creates a new Telegram Bot API client with the provided bot token.
    ///
    /// # Arguments
    ///
    /// * `token` - A token associated with your bot.
    pub fn new<T>(token: T) -> Result<Self, ClientError>
    where
        T: Into<String>,
    {
        let client = {
            #[cfg(feature = "webpki-roots")]
            {
                let root_cert_store = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

                let tls_config = rustls::ClientConfig::builder()
                    .with_root_certificates(root_cert_store)
                    .with_no_client_auth();

                HttpClientBuilder::new()
                    .tls_backend_preconfigured(tls_config)
                    .build()
                    .map_err(ClientError::BuildClient)?
            }

            #[cfg(not(feature = "webpki-roots"))]
            {
                HttpClientBuilder::new()
                    .tls_backend_rustls()
                    .build()
                    .map_err(ClientError::BuildClient)?
            }
        };
        Ok(Self::with_http_client(client, token))
    }

    /// Creates a new Telegram Bot API client with a custom HTTP client and bot token.
    ///
    /// # Arguments
    ///
    /// * `client` - An HTTP client.
    /// * `token` - A token associated with your bot.
    ///
    pub fn with_http_client<T>(http_client: HttpClient, token: T) -> Self
    where
        T: Into<String>,
    {
        Self {
            http_client,
            host: String::from(DEFAULT_HOST),
            token: token.into(),
            max_retries: DEFAULT_MAX_RETRIES,
            max_retry_after: None,
        }
    }

    /// Overrides the default API host with a custom one.
    ///
    /// # Arguments
    ///
    /// * `host` - The new API host to use.
    pub fn with_host<T>(mut self, host: T) -> Self
    where
        T: Into<String>,
    {
        self.host = host.into();
        self
    }

    /// Overrides the default number of max retries.
    ///
    /// # Arguments
    ///
    /// * `value` - The new number of max retries
    pub fn with_max_retries(mut self, value: u8) -> Self {
        self.max_retries = value;
        self
    }

    /// Sets the maximum possible value for the retry after duration.
    ///
    /// # Arguments
    ///
    /// * `value` - Duration in seconds.
    ///
    /// `None` by default.
    pub fn with_max_retry_after(mut self, value: u64) -> Self {
        self.max_retry_after = Some(value);
        self
    }

    /// Downloads a file.
    ///
    /// Use [`crate::types::GetFile`] method to get a value for the `file_path` argument.
    ///
    /// # Arguments
    ///
    /// * `file_path` - The path to the file to be downloaded.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn download_file() {
    /// use tgbot::api::Client;
    /// use futures_util::stream::StreamExt;
    /// let api = Client::new("token").unwrap();
    /// let mut stream = api.download_file("path").await.unwrap();
    /// while let Some(chunk) = stream.next().await {
    ///     let chunk = chunk.unwrap();
    ///     // write chunk to something...
    /// }
    /// # }
    /// ```
    pub async fn download_file<P>(
        &self,
        file_path: P,
    ) -> Result<impl Stream<Item = Result<Bytes, HttpError>> + use<P>, DownloadFileError>
    where
        P: AsRef<str>,
    {
        let file_path = file_path.as_ref();
        debug!("Downloading file from {file_path}");
        let payload = Payload::empty(file_path)?;
        let url = payload.build_url(&format!("{}/file", self.host), &self.token);
        let rep = self.http_client.get(&url).send().await?;
        let status = rep.status();
        if !status.is_success() {
            Err(DownloadFileError::Response {
                status: status.as_u16(),
                text: rep.text().await?,
            })
        } else {
            Ok(rep.bytes_stream())
        }
    }

    /// Executes a method.
    ///
    /// # Arguments
    ///
    /// * `method` - The method to execute.
    ///
    /// # Notes
    ///
    /// The client will not retry a request on a timeout error if the request is not cloneable
    /// (e.g. contains a stream).
    pub async fn execute<M>(&self, method: M) -> Result<M::Response, ExecuteError>
    where
        M: Method,
        M::Response: DeserializeOwned + Send + 'static,
    {
        let request = method
            .into_payload()?
            .into_http_request_builder(&self.http_client, &self.host, &self.token)?;
        let response = match send_request_retry(Box::new(request)).await? {
            RetryResponse::Ok(response) => response,
            RetryResponse::Retry {
                mut request,
                mut response,
                mut retry_after,
            } => {
                for i in 0..self.max_retries {
                    if let Some(max_retry_after) = self.max_retry_after {
                        retry_after = retry_after.min(max_retry_after);
                    }
                    debug!("Retry attempt {i}, sleeping for {retry_after} second(s)");
                    sleep(Duration::from_secs(retry_after)).await;
                    match send_request_retry(request).await? {
                        RetryResponse::Ok(new_response) => {
                            response = new_response;
                            break;
                        }
                        RetryResponse::Retry {
                            request: new_request,
                            response: new_response,
                            retry_after: new_retry_after,
                        } => {
                            request = new_request;
                            response = new_response;
                            retry_after = new_retry_after;
                        }
                    }
                }
                response
            }
        };
        Ok(response.into_result()?)
    }
}

enum RetryResponse<T> {
    Ok(Response<T>),
    Retry {
        request: Box<HttpRequestBuilder>,
        response: Response<T>,
        retry_after: u64,
    },
}

async fn send_request_retry<T>(request: Box<HttpRequestBuilder>) -> Result<RetryResponse<T>, ExecuteError>
where
    T: DeserializeOwned,
{
    Ok(match request.try_clone() {
        Some(try_request) => {
            let response = send_request(try_request).await?;
            match response.retry_after() {
                Some(retry_after) => RetryResponse::Retry {
                    request,
                    response,
                    retry_after,
                },
                None => RetryResponse::Ok(response),
            }
        }
        None => {
            debug!("Could not clone builder, sending request without retry");
            RetryResponse::Ok(send_request(*request).await?)
        }
    })
}

async fn send_request<T>(request: HttpRequestBuilder) -> Result<Response<T>, ExecuteError>
where
    T: DeserializeOwned,
{
    let response = request.send().await?;
    Ok(response.json::<Response<T>>().await?)
}

fn sanitize_http_err(mut err: HttpError) -> HttpError {
    if let Some(url) = err.url_mut()
        && let Some(segments) = url.path_segments()
    {
        let path = segments.fold(String::new(), |mut path, segment| {
            path.push('/');
            path.push_str(if segment.starts_with("bot") {
                "bot[TOKEN]"
            } else {
                segment
            });
            path
        });
        url.set_path(&path);
    }
    err
}

impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Client")
            .field("http_client", &self.http_client)
            .field("host", &self.host)
            .field("token", &format_args!("..."))
            .finish()
    }
}

/// Represents an API method that can be executed by the Telegram Bot API client.
pub trait Method {
    /// The type representing a successful result in an API response.
    type Response;

    /// Converts the method into a payload for an HTTP request.
    fn into_payload(self) -> Result<Payload, PayloadError>;
}

/// Represents general errors that can occur while working with the Telegram Bot API client.
#[derive(Debug)]
pub enum ClientError {
    /// An error indicating a failure to build an HTTP client.
    BuildClient(HttpError),
}

impl Error for ClientError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(match self {
            ClientError::BuildClient(err) => err,
        })
    }
}

impl fmt::Display for ClientError {
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ClientError::BuildClient(err) => write!(out, "can not build HTTP client: {err}"),
        }
    }
}

/// Represents errors that can occur while attempting
/// to download a file using the Telegram Bot API client.
#[derive(Debug)]
pub enum DownloadFileError {
    /// An error indicating a failure to send an HTTP request.
    Http(HttpError),
    /// An error indicating a failure to build an HTTP request payload.
    Payload(PayloadError),
    /// An error received from the server in response to the download request.
    Response {
        /// The HTTP status code received in the response.
        status: u16,
        /// The body of the response as a string.
        text: String,
    },
}

impl From<HttpError> for DownloadFileError {
    fn from(err: HttpError) -> Self {
        Self::Http(sanitize_http_err(err))
    }
}

impl From<PayloadError> for DownloadFileError {
    fn from(err: PayloadError) -> Self {
        Self::Payload(err)
    }
}

impl Error for DownloadFileError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            DownloadFileError::Http(err) => Some(err),
            _ => None,
        }
    }
}

impl fmt::Display for DownloadFileError {
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Http(err) => write!(out, "failed to download file: {err}"),
            Self::Payload(err) => write!(out, "failed to download file: {err}"),
            Self::Response { status, text } => {
                write!(out, "failed to download file: status={status} text={text}")
            }
        }
    }
}

/// Represents errors that can occur during the execution
/// of a method using the Telegram Bot API client.
#[derive(Debug, derive_more::From)]
pub enum ExecuteError {
    /// An error indicating a failure to send an HTTP request.
    #[from(skip)]
    Http(HttpError),
    /// An error indicating a failure to build an HTTP request payload.
    Payload(PayloadError),
    /// An error received from the Telegram server in response to the execution request.
    Response(ResponseError),
}

impl From<HttpError> for ExecuteError {
    fn from(err: HttpError) -> Self {
        Self::Http(sanitize_http_err(err))
    }
}

impl Error for ExecuteError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        use self::ExecuteError::*;
        Some(match self {
            Http(err) => err,
            Payload(err) => err,
            Response(err) => err,
        })
    }
}

impl fmt::Display for ExecuteError {
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        use self::ExecuteError::*;
        write!(
            out,
            "failed to execute method: {}",
            match self {
                Http(err) => err.to_string(),
                Payload(err) => err.to_string(),
                Response(err) => err.to_string(),
            }
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sanitize_http_err_without_url() {
        let err = HttpClient::new().get("invalid url").build().unwrap_err();
        assert!(err.url().is_none());

        let err = sanitize_http_err(err);
        assert!(err.url().is_none());
    }

    #[test]
    fn api() {
        let client = Client::new("token").unwrap();
        assert_eq!(client.token, "token");
        assert_eq!(client.host, DEFAULT_HOST);

        let client = Client::new("token")
            .unwrap()
            .with_host("https://example.com")
            .with_max_retries(1);
        assert_eq!(client.token, "token");
        assert_eq!(client.host, "https://example.com");
        assert_eq!(client.max_retries, 1);
    }
}