teloxide_core/bot.rs
1use std::{fmt, future::Future, sync::Arc};
2
3use reqwest::Client;
4use serde::{de::DeserializeOwned, Serialize};
5
6use crate::{
7 net,
8 requests::{MultipartPayload, Payload, ResponseResult},
9 serde_multipart,
10};
11
12mod api;
13mod download;
14
15const TELOXIDE_TOKEN: &str = "TELOXIDE_TOKEN";
16const TELOXIDE_API_URL: &str = "TELOXIDE_API_URL";
17
18/// A requests sender.
19///
20/// This is the main type of the library, it allows to send requests to the
21/// [Telegram Bot API] and download files.
22///
23/// ## TBA methods
24///
25/// All TBA methods are located in the [`Requester`] [`impl for Bot`]. This
26/// allows for opt-in behaviours using requester [adaptors].
27///
28/// ```
29/// # async {
30/// use teloxide_core::prelude::*;
31///
32/// let bot = Bot::new("TOKEN");
33/// dbg!(bot.get_me().await?);
34/// # Ok::<_, teloxide_core::RequestError>(()) };
35/// ```
36///
37/// [`Requester`]: crate::requests::Requester
38/// [`impl for Bot`]: Bot#impl-Requester
39/// [adaptors]: crate::adaptors
40///
41/// ## File download
42///
43/// In the similar way as with TBA methods, file downloading methods are located
44/// in a trait — [`Download<'_>`]. See its documentation for more.
45///
46/// [`Download<'_>`]: crate::net::Download
47///
48/// ## Clone cost
49///
50/// `Bot::clone` is relatively cheap, so if you need to share `Bot`, it's
51/// recommended to clone it, instead of wrapping it in [`Arc<_>`].
52///
53/// [`Arc`]: std::sync::Arc
54/// [Telegram Bot API]: https://core.telegram.org/bots/api
55#[must_use]
56#[derive(Clone)]
57pub struct Bot {
58 token: Arc<str>,
59 api_url: Arc<reqwest::Url>,
60 client: Client,
61}
62
63impl fmt::Debug for Bot {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 f.debug_struct("Bot").field("token", &"[redacted]").finish_non_exhaustive()
66 }
67}
68
69/// Constructors
70impl Bot {
71 /// Creates a new `Bot` with the specified token and the default
72 /// [http-client](reqwest::Client).
73 ///
74 /// # Panics
75 ///
76 /// If it cannot create [`reqwest::Client`].
77 pub fn new<S>(token: S) -> Self
78 where
79 S: Into<String>,
80 {
81 let client = net::default_reqwest_settings().build().expect("Client creation failed");
82
83 Self::with_client(token, client)
84 }
85
86 /// Creates a new `Bot` with the specified token and your
87 /// [`reqwest::Client`].
88 ///
89 /// # Caution
90 ///
91 /// Your custom client might not be configured correctly to be able to work
92 /// in long time durations, see [issue 223].
93 ///
94 /// [`reqwest::Client`]: https://docs.rs/reqwest/latest/reqwest/struct.Client.html
95 /// [issue 223]: https://github.com/teloxide/teloxide/issues/223
96 pub fn with_client<S>(token: S, client: Client) -> Self
97 where
98 S: Into<String>,
99 {
100 let token = Into::<String>::into(token).into();
101 let api_url = Arc::new(
102 reqwest::Url::parse(net::TELEGRAM_API_URL)
103 .expect("Failed to parse the default TBA URL"),
104 );
105
106 Self { token, api_url, client }
107 }
108
109 /// Creates a new `Bot` with the `TELOXIDE_TOKEN` & `TELOXIDE_API_URL` &
110 /// `TELOXIDE_PROXY` environmental variables (the bot's token & the bot's
111 /// API URL & the proxy) and the default [`reqwest::Client`].
112 ///
113 /// If `TELOXIDE_API_URL` doesn't exist, returns to the default TBA URL.
114 ///
115 /// This function passes the value of `TELOXIDE_PROXY` into
116 /// [`reqwest::Proxy::all`], if it exists, otherwise returns the default
117 /// client.
118 ///
119 /// # Panics
120 /// - If cannot get the `TELOXIDE_TOKEN` environmental variable.
121 /// - If `TELOXIDE_API_URL` exists, but isn't a correct URL.
122 /// - If it cannot create [`reqwest::Client`].
123 ///
124 /// [`reqwest::Client`]: https://docs.rs/reqwest/0.10.1/reqwest/struct.Client.html
125 /// [`reqwest::Proxy::all`]: https://docs.rs/reqwest/latest/reqwest/struct.Proxy.html#method.all
126 pub fn from_env() -> Self {
127 Self::from_env_with_client(crate::net::client_from_env())
128 }
129
130 /// Creates a new `Bot` with the `TELOXIDE_TOKEN` environmental variable
131 /// (the bot's token), `TELOXIDE_API_URL` environmental variable (the bot's
132 /// API URL) and your [`reqwest::Client`].
133 ///
134 /// If `TELOXIDE_API_URL` doesn't exist, returns to the default TBA URL.
135 ///
136 /// # Panics
137 /// - If cannot get the `TELOXIDE_TOKEN` environmental variable.
138 /// - If `TELOXIDE_API_URL` exists, but isn't a correct URL.
139 ///
140 /// # Caution
141 /// Your custom client might not be configured correctly to be able to work
142 /// in long time durations, see [issue 223].
143 ///
144 /// [`reqwest::Client`]: https://docs.rs/reqwest/0.10.1/reqwest/struct.Client.html
145 /// [issue 223]: https://github.com/teloxide/teloxide/issues/223
146 pub fn from_env_with_client(client: Client) -> Self {
147 let bot = Self::with_client(get_env(TELOXIDE_TOKEN), client);
148
149 match std::env::var(TELOXIDE_API_URL) {
150 Ok(env_api_url) => {
151 // Remove the trailing slash if it exists
152 let env_api_url = if env_api_url.ends_with('/') {
153 env_api_url.trim_end_matches('/')
154 } else {
155 &env_api_url
156 };
157 let api_url = reqwest::Url::parse(env_api_url)
158 .expect("Failed to parse the `TELOXIDE_API_URL` env variable");
159 bot.set_api_url(api_url)
160 }
161 Err(_) => bot,
162 }
163 }
164
165 /// Sets a custom API URL.
166 ///
167 /// For example, you can run your own [TBA server][tbas] and set its URL
168 /// using this method.
169 ///
170 /// [tbas]: https://github.com/tdlib/telegram-bot-api
171 ///
172 /// ## Examples
173 ///
174 /// ```
175 /// use teloxide_core::{
176 /// requests::{Request, Requester},
177 /// Bot,
178 /// };
179 ///
180 /// # async {
181 /// let url = reqwest::Url::parse("https://localhost/tbas").unwrap();
182 /// let bot = Bot::new("TOKEN").set_api_url(url);
183 /// // From now all methods will use "https://localhost/tbas" as an API URL.
184 /// bot.get_me().await
185 /// # };
186 /// ```
187 ///
188 /// ## Multi-instance behaviour
189 ///
190 /// This method only sets the URL for one bot instace, older clones are
191 /// unaffected.
192 ///
193 /// ```
194 /// use teloxide_core::Bot;
195 ///
196 /// let bot = Bot::new("TOKEN");
197 /// let bot2 = bot.clone();
198 /// let bot = bot.set_api_url(reqwest::Url::parse("https://example.com/").unwrap());
199 ///
200 /// assert_eq!(bot.api_url().as_str(), "https://example.com/");
201 /// assert_eq!(bot.clone().api_url().as_str(), "https://example.com/");
202 /// assert_ne!(bot2.api_url().as_str(), "https://example.com/");
203 /// ```
204 pub fn set_api_url(mut self, url: reqwest::Url) -> Self {
205 self.api_url = Arc::new(url);
206 self
207 }
208}
209
210/// Getters
211impl Bot {
212 /// Returns currently used token.
213 #[must_use]
214 pub fn token(&self) -> &str {
215 &self.token
216 }
217
218 /// Returns currently used http-client.
219 #[must_use]
220 pub fn client(&self) -> &Client {
221 &self.client
222 }
223
224 /// Returns currently used token API URL.
225 #[must_use]
226 pub fn api_url(&self) -> reqwest::Url {
227 reqwest::Url::clone(&*self.api_url)
228 }
229}
230
231impl Bot {
232 pub(crate) fn execute_json<P>(
233 &self,
234 payload: &P,
235 ) -> impl Future<Output = ResponseResult<P::Output>> + 'static
236 where
237 P: Payload + Serialize,
238 P::Output: DeserializeOwned + 'static,
239 {
240 let client = self.client.clone();
241 let token = Arc::clone(&self.token);
242 let api_url = Arc::clone(&self.api_url);
243
244 let timeout_hint = payload.timeout_hint();
245 let params = stacker::maybe_grow(256 * 1024, 1024 * 1024, || serde_json::to_vec(payload))
246 // this `expect` should be ok since we don't write request those may trigger error here
247 .expect("serialization of request to be infallible");
248
249 // async move to capture client&token&api_url¶ms
250 async move {
251 net::request_json(
252 &client,
253 token.as_ref(),
254 reqwest::Url::clone(&*api_url),
255 P::TELEGRAM_METHOD,
256 params,
257 timeout_hint,
258 )
259 .await
260 }
261 }
262
263 pub(crate) fn execute_multipart<P>(
264 &self,
265 payload: &mut P,
266 ) -> impl Future<Output = ResponseResult<P::Output>>
267 where
268 P: MultipartPayload + Serialize,
269 P::Output: DeserializeOwned + 'static,
270 {
271 let client = self.client.clone();
272 let token = Arc::clone(&self.token);
273 let api_url = Arc::clone(&self.api_url);
274
275 let timeout_hint = payload.timeout_hint();
276 let params = serde_multipart::to_form(payload);
277
278 // async move to capture client&token&api_url¶ms
279 async move {
280 let params = params?.await?;
281 net::request_multipart(
282 &client,
283 token.as_ref(),
284 reqwest::Url::clone(&*api_url),
285 P::TELEGRAM_METHOD,
286 params,
287 timeout_hint,
288 )
289 .await
290 }
291 }
292
293 pub(crate) fn execute_multipart_ref<P>(
294 &self,
295 payload: &P,
296 ) -> impl Future<Output = ResponseResult<P::Output>>
297 where
298 P: MultipartPayload + Serialize,
299 P::Output: DeserializeOwned + 'static,
300 {
301 let client = self.client.clone();
302 let token = Arc::clone(&self.token);
303 let api_url = self.api_url.clone();
304
305 let timeout_hint = payload.timeout_hint();
306 let params = serde_multipart::to_form_ref(payload);
307
308 // async move to capture client&token&api_url¶ms
309 async move {
310 let params = params?.await?;
311 net::request_multipart(
312 &client,
313 token.as_ref(),
314 reqwest::Url::clone(&*api_url),
315 P::TELEGRAM_METHOD,
316 params,
317 timeout_hint,
318 )
319 .await
320 }
321 }
322}
323
324fn get_env(env: &'static str) -> String {
325 std::env::var(env).unwrap_or_else(|_| panic!("Cannot get the {env} env variable"))
326}
327
328#[cfg(test)]
329mod debug_tests {
330 #[test]
331 fn bot_debug_redacts_token() {
332 let bot = super::Bot::new("my-secret-token");
333 assert!(!format!("{bot:?} {bot:#?}").contains(bot.token()));
334 }
335}