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
//! The client implementation around the API, and finalizer requests for //! configuring optional parameters. //! //! Refer to the [`Client`] struct for more information and examples. //! //! [`Client`]: struct.Client.html pub mod request; use crate::{ endpoints, error::{ChunkingText, Deserializing, InvalidHeaderValue, InvalidUrl, Result, TokenMissing}, model::*, }; use request::SearchBots; use reqwest::{ header::{HeaderValue, AUTHORIZATION}, Client as HttpClient, Url, }; use serde::de::DeserializeOwned; use snafu::{OptionExt, ResultExt}; use std::sync::Arc; #[derive(Debug)] struct ClientRef { http: Arc<HttpClient>, token: Option<String>, } /// Struct which defines the methods necessary to interact with the service. #[derive(Clone, Debug)] pub struct Client(Arc<ClientRef>); impl Client { /// Creates a new client to interact with the API. /// /// This accepts an existing reqwest Client so a single HTTP client may be /// shared across your application. /// /// This method doesn't require authentication. /// /// # Examples /// /// Create a new API client: /// /// ```no_run /// use reqwest::Client as HttpClient; /// use top_gg::Client; /// /// let http_client = HttpClient::new(); /// let client = Client::new(http_client, None); /// ``` pub fn new(http_client: impl Into<Arc<HttpClient>>, token: impl Into<Option<String>>) -> Self { Self(Arc::new(ClientRef { http: http_client.into(), token: token.into(), })) } /// Retrieves information about a bot. /// /// This method doesn't require authentication. /// /// # Examples /// /// ```no_run /// use reqwest::Client as HttpClient; /// use top_gg::Client; /// /// # #[tokio::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { /// let http_client = HttpClient::new(); /// let client = Client::new(http_client, None); /// /// let bot = client.get_bot(270198738570444801).await?; /// /// println!("Bot's name: {}", bot.username); /// # Ok(()) } /// ``` /// /// # Errors /// /// Returns [`Error::ChunkingText`] when the response body couldn't be /// chunked as a valid UTF-8 string. /// /// Returns [`Error::Deserializing`] if there was an issue deserializing the /// response body. /// /// Returns [`Error::Request`] if there was an issue building the request. /// This probably won't happen. /// /// [`Error::ChunkingText`]: ../error/enum.Error.html#variant.ChunkingText /// [`Error::Deserializing`]: ../error/enum.Error.html#variant.Deserializing /// [`Error::Request`]: ../error/enum.Error.html#variant.Request pub async fn get_bot(&self, user_id: u64) -> Result<Bot> { let url = url(endpoints::bot(user_id))?; self.get(url).await } /// Retrieves a list of bots via a search. /// /// This method doesn't require authentication. /// /// # Examples /// /// Get 500 bots, skipping the first 250 bots: /// /// ```no_run /// use reqwest::Client as HttpClient; /// use top_gg::Client; /// /// # #[tokio::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { /// let http_client = HttpClient::new(); /// let client = Client::new(http_client, None); /// /// let bots = client.get_bots().limit(500).offset(250).await?; /// /// println!("Got {} bots", bots.total); /// # Ok(()) } /// ``` /// /// # Errors /// /// Returns [`Error::ChunkingText`] when the response body couldn't be /// chunked as a valid UTF-8 string. /// /// Returns [`Error::Deserializing`] if there was an issue deserializing the /// response body. /// /// Returns [`Error::Request`] if there was an issue building the request. /// This probably won't happen. /// /// [`Error::ChunkingText`]: ../error/enum.Error.html#variant.ChunkingText /// [`Error::Deserializing`]: ../error/enum.Error.html#variant.Deserializing /// [`Error::Request`]: ../error/enum.Error.html#variant.Request pub fn get_bots(&self) -> SearchBots<'_> { SearchBots::new(self) } /// Retrieves information about a bot's specific stats. /// /// This method doesn't require authentication. /// /// # Examples /// /// ```no_run /// use reqwest::Client as HttpClient; /// use top_gg::Client; /// /// # #[tokio::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { /// let http_client = HttpClient::new(); /// let client = Client::new(http_client, None); /// /// let bot = client.get_bot_stats(270_198_738_570_444_801).await?; /// /// if let Some(server_count) = bot.server_count { /// println!("This bot is in {} servers", server_count); /// } /// # Ok(()) } /// ``` /// /// # Errors /// /// Returns [`Error::ChunkingText`] when the response body couldn't be /// chunked as a valid UTF-8 string. /// /// Returns [`Error::Deserializing`] if there was an issue deserializing the /// response body. /// /// Returns [`Error::Request`] if there was an issue building the request. /// This probably won't happen. /// /// [`Error::ChunkingText`]: ../error/enum.Error.html#variant.ChunkingText /// [`Error::Deserializing`]: ../error/enum.Error.html#variant.Deserializing /// [`Error::Request`]: ../error/enum.Error.html#variant.Request pub async fn get_bot_stats(&self, user_id: u64) -> Result<BotStats> { let url = url(endpoints::bot_stats(user_id))?; self.get(url).await } /// Retrieve whether a user has upvoted a bot in the last 24 hours. /// /// You can use this if your bot has over 1000 votes. /// /// This method requires authentication. /// /// # Examples /// /// ```no_run /// use reqwest::Client as HttpClient; /// use std::env; /// use top_gg::Client; /// /// # #[tokio::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { /// let http_client = HttpClient::new(); /// let token = env::var("TOP_GG_TOKEN")?; /// let client = Client::new(http_client, token); /// /// let voted = client.get_bot_vote_check(270_198_738_570_444_801, 114_941_315_417_899_012).await?; /// /// if voted { /// println!("This user voted"); /// } else { /// println!("This user has not voted"); /// } /// # Ok(()) } /// ``` /// /// # Errors /// /// Returns [`Error::ChunkingText`] when the response body couldn't be /// chunked as a valid UTF-8 string. /// /// Returns [`Error::Deserializing`] if there was an issue deserializing the /// response body. /// /// Returns [`Error::Request`] if there was an issue building the request. /// This probably won't happen. /// /// Returns [`Error::TokenMissing`] if a token is needed for authentication /// but it wasn't present. /// /// [`Error::ChunkingText`]: ../error/enum.Error.html#variant.ChunkingText /// [`Error::Deserializing`]: ../error/enum.Error.html#variant.Deserializing /// [`Error::Request`]: ../error/enum.Error.html#variant.Request /// [`Error::TokenMissing`]: ../error/enum.Error.html#variant.TokenMissing pub async fn get_bot_vote_check(&self, bot_id: u64, user_id: u64) -> Result<bool> { let token = self.0.token.as_ref().context(TokenMissing)?; let path = endpoints::bot_vote_check(bot_id, user_id); let user_id = user_id.to_string(); let params = [("userId", user_id.as_ref())]; let url = url_params(path, ¶ms)?; let header_value = auth(token)?; let text = self .0 .http .get(url) .header(AUTHORIZATION, header_value) .send() .await? .text() .await .context(ChunkingText)?; let body = deser::<ResponseUserVoted>(text)?; Ok(body.voted == 1) } /// Retrieves information to see who has upvoted a bot. /// /// This method does not require authentication. /// /// **Note**: If your bot has over 1000 votes per month, then this can not /// be used. Webhooks must instead be used. /// /// # Examples /// /// ```no_run /// use reqwest::Client as HttpClient; /// use top_gg::{ /// model::BotVotes, /// Client, /// }; /// /// # #[tokio::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { /// let http_client = HttpClient::new(); /// let client = Client::new(http_client, None); /// /// let votes = client.get_bot_votes(270_198_738_570_444_801).await?; /// /// match votes { /// BotVotes::Ids(ids) => println!("There are {} votes", ids.len()), /// BotVotes::Users(users) => println!("There are {} votes", users.len()), /// } /// # Ok(()) } /// ``` /// /// # Errors /// /// Returns [`Error::ChunkingText`] when the response body couldn't be /// chunked as a valid UTF-8 string. /// /// Returns [`Error::Deserializing`] if there was an issue deserializing the /// response body. /// /// Returns [`Error::Request`] if there was an issue building the request. /// This probably won't happen. /// /// [`Error::ChunkingText`]: ../error/enum.Error.html#variant.ChunkingText /// [`Error::Deserializing`]: ../error/enum.Error.html#variant.Deserializing /// [`Error::Request`]: ../error/enum.Error.html#variant.Request pub async fn get_bot_votes(&self, bot_id: u64) -> Result<BotVotes> { let url = url(endpoints::bot_votes(bot_id))?; self.get(url).await } /// Retrieves information about a user. /// /// This method doesn't require authentication. /// /// # Examples /// /// ```no_run /// use reqwest::Client as HttpClient; /// use top_gg::Client; /// /// # #[tokio::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { /// let http_client = HttpClient::new(); /// let client = Client::new(http_client, None); /// /// let user = client.get_user(114_941_315_417_899_012).await?; /// /// println!("The user's name is {}", user.username); /// # Ok(()) } /// ``` /// /// # Errors /// /// Returns [`Error::ChunkingText`] when the response body couldn't be /// chunked as a valid UTF-8 string. /// /// Returns [`Error::Deserializing`] if there was an issue deserializing the /// response body. /// /// Returns [`Error::Request`] if there was an issue building the request. /// This probably won't happen. /// /// [`Error::ChunkingText`]: ../error/enum.Error.html#variant.ChunkingText /// [`Error::Deserializing`]: ../error/enum.Error.html#variant.Deserializing /// [`Error::Request`]: ../error/enum.Error.html#variant.Request pub async fn get_user(&self, user_id: u64) -> Result<User> { let url = url(endpoints::user(user_id))?; self.get(url).await } /// Posts a bot's shard stats. /// /// This method requires authentication. /// /// # Examples /// /// ```no_run /// use reqwest::Client as HttpClient; /// use std::env; /// use top_gg::{ /// model::ShardStats, /// Client, /// }; /// /// # #[tokio::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { /// let http_client = HttpClient::new(); /// let token = env::var("TOP_GG_TOKEN")?; /// let client = Client::new(http_client, token); /// /// let shard_stats = ShardStats::Shard { /// guild_count: 1123, /// shard_count: 10, /// shard_id: 6, /// }; /// /// client.post_stats(270_198_738_570_444_801, &shard_stats).await?; /// # Ok(()) } /// ``` /// /// # Errors /// /// Returns [`Error::Request`] if there was an issue building the request. /// This probably won't happen. /// /// Returns [`Error::TokenMissing`] if a token is needed for authentication /// but it wasn't present. /// /// [`Error::Request`]: ../error/enum.Error.html#variant.Request /// [`Error::TokenMissing`]: ../error/enum.Error.html#variant.TokenMissing pub async fn post_stats<'a>(&'a self, bot_id: u64, stats: &'a ShardStats) -> Result<()> { let token = self.0.token.as_ref().context(TokenMissing)?; let url = url(endpoints::bot_stats(bot_id))?; let header_value = auth(token)?; self.0 .http .post(url) .header(AUTHORIZATION, header_value) .json(stats) .send() .await?; Ok(()) } async fn get<T: DeserializeOwned>(&self, url: Url) -> Result<T> { let text = self .0 .http .get(url) .send() .await? .text() .await .context(ChunkingText)?; deser(text) } } impl From<(Arc<HttpClient>, Option<String>)> for Client { fn from((client, token): (Arc<HttpClient>, Option<String>)) -> Self { Self::new(client, token) } } fn auth(token: &str) -> Result<HeaderValue> { HeaderValue::from_str(token).with_context(|| InvalidHeaderValue { name: AUTHORIZATION, value: token.to_owned(), }) } fn deser<T: DeserializeOwned>(text: String) -> Result<T> { serde_json::from_str(&text).with_context(|| Deserializing { text }) } fn url(uri: String) -> Result<Url> { Url::parse(&uri).with_context(|| InvalidUrl { uri }) } fn url_params<'a>(uri: String, params: &[(&'a str, &'a str)]) -> Result<Url> { Url::parse_with_params(&uri, params.iter()).with_context(|| InvalidUrl { uri }) }