lib.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. pub mod telegram_types;
  2. use reqwest;
  3. use telegram_types::{TelegramKeyboardMarkup, TelegramUpdate};
  4. use std::borrow::Borrow;
  5. use serde_json::json;
  6. use redis::{self, Commands, RedisError};
  7. use serde_json;
  8. use std::env;
  9. //use shit_post_db::DatabaseConnection;
  10. pub struct TelegramBot {
  11. token: String,
  12. //db_conn: DatabaseConnection,
  13. redis_client: redis::Client,
  14. }
  15. impl TelegramBot {
  16. pub fn new(token: String, redis_client: redis::Client) -> Self {
  17. Self {
  18. token, redis_client
  19. }
  20. }
  21. fn make_url(&self, api_endpoint: &str) -> String {
  22. format!("https://api.telegram.org/bot{:}/{:}", self.token, api_endpoint)
  23. }
  24. pub async fn get_updates(&self) -> Result<Vec<TelegramUpdate>, reqwest::Error> {
  25. let responce = reqwest::get(
  26. self.make_url("getUpdates")
  27. ).await?;
  28. let mut data: telegram_types::TelegramResponce = responce
  29. //.text()
  30. .json::<telegram_types::TelegramResponce>()
  31. .await?;
  32. data.result.sort_by(|a, b| a.message.date.cmp(&b.message.date));
  33. println!("{:?}", &data.result);
  34. Ok(data.result)
  35. }
  36. pub async fn send_message(
  37. &self, chat_id: i64, text: &str, keyboard: &TelegramKeyboardMarkup
  38. ) -> Result<(), reqwest::Error> {
  39. let responce = reqwest::Client::new().post(
  40. self.make_url("sendMessage"))
  41. .json(
  42. json!({
  43. "chat_id": chat_id,
  44. "text": text,
  45. "reply_markup": keyboard
  46. }).borrow()
  47. ).send().await?;
  48. println!("Responce -> | {:?} |", responce);
  49. Ok(())
  50. }
  51. pub fn mark_as_handled(&self, update_id: i64) -> Result<(), RedisError> {
  52. let mut con = self.redis_client.get_connection()?;
  53. // throw away the result, just make sure it does not fail
  54. let _ : () = con.set(update_id, true)?;
  55. Ok(())
  56. }
  57. pub fn check_if_handled(&self, update_id: i64) -> Result<bool, RedisError> {
  58. let mut con = self.redis_client.get_connection()?;
  59. // throw away the result, just make sure it does not fail
  60. Ok(con.get(update_id)?)
  61. }
  62. pub async fn update_webhook(&self) -> Result<(), reqwest::Error> {
  63. let webhook = env::var("WEBHOOK_ADDR").expect("WEBHOOK_ADDR is not set in .env file");
  64. let _ = reqwest::Client::new().get(
  65. self.make_url("setWebhook") + &format!("?url={:}", webhook)
  66. ).send().await?;
  67. Ok(())
  68. }
  69. }