1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- pub mod telegram_types;
- use reqwest;
- use telegram_types::{TelegramKeyboardMarkup, TelegramUpdate};
- use std::borrow::Borrow;
- use serde_json::json;
- use redis::{self, Commands, RedisError};
- use serde_json;
- use std::env;
- //use shit_post_db::DatabaseConnection;
- pub struct TelegramBot {
- token: String,
- //db_conn: DatabaseConnection,
- redis_client: redis::Client,
- }
- impl TelegramBot {
- pub fn new(token: String, redis_client: redis::Client) -> Self {
- Self {
- token, redis_client
- }
- }
- fn make_url(&self, api_endpoint: &str) -> String {
- format!("https://api.telegram.org/bot{:}/{:}", self.token, api_endpoint)
- }
- pub async fn get_updates(&self) -> Result<Vec<TelegramUpdate>, reqwest::Error> {
- let responce = reqwest::get(
- self.make_url("getUpdates")
- ).await?;
- let mut data: telegram_types::TelegramResponce = responce
- //.text()
- .json::<telegram_types::TelegramResponce>()
- .await?;
- data.result.sort_by(|a, b| a.message.date.cmp(&b.message.date));
- println!("{:?}", &data.result);
- Ok(data.result)
- }
- pub async fn send_message(
- &self, chat_id: i64, text: &str, keyboard: &TelegramKeyboardMarkup
- ) -> Result<(), reqwest::Error> {
- let responce = reqwest::Client::new().post(
- self.make_url("sendMessage"))
- .json(
- json!({
- "chat_id": chat_id,
- "text": text,
- "reply_markup": keyboard
- }).borrow()
- ).send().await?;
- println!("Responce -> | {:?} |", responce);
- Ok(())
- }
- pub fn mark_as_handled(&self, update_id: i64) -> Result<(), RedisError> {
- let mut con = self.redis_client.get_connection()?;
- // throw away the result, just make sure it does not fail
- let _ : () = con.set(update_id, true)?;
- Ok(())
- }
- pub fn check_if_handled(&self, update_id: i64) -> Result<bool, RedisError> {
- let mut con = self.redis_client.get_connection()?;
- // throw away the result, just make sure it does not fail
- Ok(con.get(update_id)?)
- }
- pub async fn update_webhook(&self) -> Result<(), reqwest::Error> {
- let webhook = env::var("WEBHOOK_ADDR").expect("WEBHOOK_ADDR is not set in .env file");
- let _ = reqwest::Client::new().get(
- self.make_url("setWebhook") + &format!("?url={:}", webhook)
- ).send().await?;
- Ok(())
- }
- }
|