Move more settings into Bot

This commit is contained in:
Temirkhan Myrzamadi 2020-07-16 21:04:11 +06:00
parent 9eeb23ce4b
commit 9dbff2b522
3 changed files with 24 additions and 10 deletions

View file

@ -1,5 +1,8 @@
use reqwest::Client;
use std::sync::Arc;
use reqwest::{
header::{HeaderMap, CONNECTION},
Client, ClientBuilder,
};
use std::{sync::Arc, time::Duration};
mod api;
mod download;
@ -20,7 +23,7 @@ impl Bot {
///
/// [`reqwest::Client`]: https://docs.rs/reqwest/0.10.1/reqwest/struct.Client.html
pub fn from_env() -> Arc<Self> {
Self::from_env_with_client(Client::new())
Self::from_env_with_client(sound_bot())
}
/// Creates a new `Bot` with the `TELOXIDE_TOKEN` environmental variable (a
@ -46,7 +49,7 @@ impl Bot {
where
S: Into<String>,
{
Self::with_client(token, Client::new())
Self::with_client(token, sound_bot())
}
/// Creates a new `Bot` with the specified token and your
@ -61,6 +64,23 @@ impl Bot {
}
}
// See https://github.com/teloxide/teloxide/issues/223.
fn sound_bot() -> Client {
let mut headers = HeaderMap::new();
headers.insert(CONNECTION, "keep-alive".parse().unwrap());
let connect_timeout = Duration::from_secs(5);
let timeout = 10;
ClientBuilder::new()
.connect_timeout(connect_timeout)
.timeout(Duration::from_secs(connect_timeout.as_secs() + timeout + 2))
.tcp_nodelay_(true)
.default_headers(headers)
.build()
.expect("Cannot build reqwest::Client")
}
impl Bot {
// TODO: const fn
pub fn token(&self) -> &str {

View file

@ -4,7 +4,6 @@ use tokio::io::{AsyncWrite, AsyncWriteExt};
use crate::errors::DownloadError;
use super::TELEGRAM_API_URL;
use reqwest::header::CONNECTION;
pub async fn download_file<D>(
client: &Client,
@ -17,7 +16,6 @@ where
{
let mut res = client
.get(&super::file_url(TELEGRAM_API_URL, token, path))
.header(CONNECTION, "keep-alive")
.send()
.await?
.error_for_status()?;
@ -37,7 +35,6 @@ pub async fn download_file_stream(
) -> Result<impl Stream<Item = reqwest::Result<Bytes>>, reqwest::Error> {
let res = client
.get(&super::file_url(TELEGRAM_API_URL, token, path))
.header(CONNECTION, "keep-alive")
.send()
.await?
.error_for_status()?;

View file

@ -4,7 +4,6 @@ use serde::{de::DeserializeOwned, Serialize};
use crate::{requests::ResponseResult, RequestError};
use super::{TelegramResponse, TELEGRAM_API_URL};
use reqwest::header::CONNECTION;
use std::time::Duration;
const DELAY_ON_SERVER_ERROR: Duration = Duration::from_secs(10);
@ -20,7 +19,6 @@ where
{
let response = client
.post(&super::method_url(TELEGRAM_API_URL, token, method_name))
.header(CONNECTION, "keep-alive")
.multipart(params)
.send()
.await
@ -41,7 +39,6 @@ where
{
let response = client
.post(&super::method_url(TELEGRAM_API_URL, token, method_name))
.header(CONNECTION, "keep-alive")
.json(params)
.send()
.await