Implement /getMe (core/mod.rs)

This commit is contained in:
Temirkhan Myrzamadi 2019-09-02 01:53:18 +06:00
parent e9f8bee44d
commit db7755d398
3 changed files with 75 additions and 7 deletions

View file

@ -6,3 +6,8 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
futures-preview = { version = "0.3.0-alpha.14", features = ["compat"] }
reqwest = "0.9.20"
serde_json = "1.0.39"
serde = {version = "1.0.92", features = ["derive"] }
lazy_static = "1.3"

View file

@ -0,0 +1,64 @@
use futures::compat::Future01CompatExt;
use reqwest::r#async::Client;
use reqwest::StatusCode;
use serde::Deserialize;
use serde_json::Value;
lazy_static! {
static ref REQWEST_CLIENT: Client = Client::new();
}
const TELEGRAM_URL_START: &str = "https://api.telegram.org/bot";
#[derive(Debug)]
pub enum Error {
Api {
status_code: StatusCode,
description: Option<String>,
},
Send(reqwest::Error),
InvalidJson(reqwest::Error),
}
pub type Response<T> = Result<T, Error>;
#[derive(Debug, Deserialize)]
pub struct User {
id: i64,
is_bot: bool,
first_name: String,
last_name: Option<String>,
username: Option<String>,
language_code: Option<String>,
}
pub async fn get_me(bot_token: &str) -> Response<User> {
let mut response = REQWEST_CLIENT
.get(&format!(
"{}{bot_token}/getMe",
TELEGRAM_URL_START,
bot_token = bot_token
))
.send()
.compat()
.await
.map_err(Error::Send)?;
let response_json = response
.json::<Value>()
.compat()
.await
.map_err(Error::InvalidJson)?;
if response_json["ok"] == "false" {
return Err(Error::Api {
status_code: response.status(),
description: match response_json.get("description") {
None => None,
Some(description) => Some(description.to_string()),
},
});
}
Ok(serde_json::from_value(response_json["result"].clone()).unwrap())
}

View file

@ -1,7 +1,6 @@
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
#![feature(async_await)]
#[macro_use]
extern crate lazy_static;
mod core;