From e9f8bee44d107eab184cf98d91eac6795bf50ac6 Mon Sep 17 00:00:00 2001 From: Temirkhan Myrzamadi Date: Mon, 2 Sep 2019 00:23:03 +0600 Subject: [PATCH 1/2] Ignore .idea/ (.gitignore) --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 69369904..0668c27c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /target **/*.rs.bk Cargo.lock +.idea/ \ No newline at end of file From db7755d39802840383b42386a48fb81a51842687 Mon Sep 17 00:00:00 2001 From: Temirkhan Myrzamadi Date: Mon, 2 Sep 2019 01:53:18 +0600 Subject: [PATCH 2/2] Implement /getMe (core/mod.rs) --- Cargo.toml | 5 ++++ src/core/mod.rs | 64 +++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 13 +++++----- 3 files changed, 75 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b2e3e1ba..f8fa400b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" \ No newline at end of file diff --git a/src/core/mod.rs b/src/core/mod.rs index e69de29b..32bd3ec3 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -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, + }, + Send(reqwest::Error), + InvalidJson(reqwest::Error), +} + +pub type Response = Result; + +#[derive(Debug, Deserialize)] +pub struct User { + id: i64, + is_bot: bool, + first_name: String, + last_name: Option, + username: Option, + language_code: Option, +} + +pub async fn get_me(bot_token: &str) -> Response { + 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::() + .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()) +} diff --git a/src/lib.rs b/src/lib.rs index 31e1bb20..d274ca74 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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;