Skip to content

Commit

Permalink
refactor: run rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
mhkafadar committed Apr 12, 2024
1 parent 65e0c94 commit d8ef8f8
Show file tree
Hide file tree
Showing 13 changed files with 112 additions and 104 deletions.
57 changes: 30 additions & 27 deletions src/bots/bot_service.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
// bot_service.rs
use crate::utils::telegram_admin::send_message_to_admin;
use notifine::{get_webhook_url_or_create, WebhookGetOrCreateInput};
use std::env;
use teloxide::{Bot, dptree, filter_command};
use teloxide::dispatching::{Dispatcher, UpdateFilterExt};
use teloxide::dispatching::dialogue::InMemStorage;
use teloxide::dispatching::{Dispatcher, UpdateFilterExt};
use teloxide::dptree::case;
use teloxide::macros::BotCommands;
use teloxide::payloads::SendMessageSetters;
use teloxide::prelude::{ChatId, ChatMemberUpdated, Message, Requester, ResponseResult, Update};
use teloxide::types::{ChatMemberKind, ParseMode};
use notifine::{get_webhook_url_or_create, WebhookGetOrCreateInput};
use crate::utils::telegram_admin::send_message_to_admin;
use teloxide::{dptree, filter_command, Bot};

#[derive(Debug, Clone)]
pub struct BotConfig {
Expand Down Expand Up @@ -44,8 +44,8 @@ pub enum State {

#[derive(BotCommands, Clone)]
#[command(
rename_rule = "lowercase",
description = "These commands are supported:"
rename_rule = "lowercase",
description = "These commands are supported:"
)]
enum Command {
#[command(description = "starts!")]
Expand Down Expand Up @@ -74,14 +74,14 @@ impl BotService {
thread_id,
inviter_username,
})
.await?;
.await?;

Ok(())
}

async fn handle_new_chat_and_start_command(
&self,
start_command: StartCommand
start_command: StartCommand,
) -> ResponseResult<()> {
// get bot name from config
let StartCommand {
Expand All @@ -96,7 +96,7 @@ impl BotService {
let thread_id_ref = thread_id_str.as_ref().map(String::as_str);

// let webhook_info = get_webhook_url_or_create(chat_id);
let webhook_info = get_webhook_url_or_create(WebhookGetOrCreateInput{
let webhook_info = get_webhook_url_or_create(WebhookGetOrCreateInput {
telegram_chat_id: chat_id.to_string().as_str(),
telegram_thread_id: thread_id_ref,
});
Expand Down Expand Up @@ -132,11 +132,12 @@ impl BotService {
)
};

self.send_telegram_message(TelegramMessage {
self.send_telegram_message(TelegramMessage {
chat_id,
thread_id,
message,
}).await?;
})
.await?;

if webhook_info.is_new {
let inviter_username = inviter_username.unwrap_or_else(|| "unknown".to_string());
Expand All @@ -146,7 +147,7 @@ impl BotService {
&self.bot,
format!("New {bot_name} webhook added: {chat_id} by @{inviter_username}"),
)
.await?;
.await?;
}

Ok(())
Expand All @@ -171,20 +172,26 @@ impl BotService {
thread_id: None,
inviter_username: update.from.username,
})
.await?
.await?
}

Ok(())
}

pub async fn send_telegram_message(&self, message: TelegramMessage) -> ResponseResult<()> {
let TelegramMessage { chat_id, thread_id, message } = message;
let TelegramMessage {
chat_id,
thread_id,
message,
} = message;

log::info!("Sending message to {}: {}", chat_id, message);
let bot = &self.bot;
let chat_id = ChatId(chat_id);

let mut request = bot.send_message(chat_id, &message).parse_mode(ParseMode::Html);
let mut request = bot
.send_message(chat_id, &message)
.parse_mode(ParseMode::Html);

if let Some(tid) = thread_id {
request = request.message_thread_id(tid);
Expand All @@ -202,21 +209,18 @@ impl BotService {
let command_handler_self = self.clone();
let chat_member_handler_self = self.clone();

let command_handler = filter_command::<Command, _>().branch(case![Command::Start].endpoint({
move |msg: Message| {
let bot_service = command_handler_self.clone(); // Use the pre-cloned `self`
async move {
bot_service.handle_start_command(msg).await
let command_handler =
filter_command::<Command, _>().branch(case![Command::Start].endpoint({
move |msg: Message| {
let bot_service = command_handler_self.clone(); // Use the pre-cloned `self`
async move { bot_service.handle_start_command(msg).await }
}
}
}));
}));

let chat_member_handler = {
move |update: ChatMemberUpdated| {
let bot_service = chat_member_handler_self.clone(); // Use the pre-cloned `self`
async move {
bot_service.handle_my_chat_member_update(update).await
}
let bot_service = chat_member_handler_self.clone(); // Use the pre-cloned `self`
async move { bot_service.handle_my_chat_member_update(update).await }
}
};

Expand All @@ -233,5 +237,4 @@ impl BotService {

log::info!("Closing bot... Goodbye!");
}

}
2 changes: 1 addition & 1 deletion src/bots/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub mod beep_bot;
pub mod bot_service;
pub mod github_bot;
pub mod gitlab_bot;
pub mod trello_bot;
pub mod bot_service;
2 changes: 1 addition & 1 deletion src/http_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub async fn run_http_server() -> std::io::Result<()> {
.service(handle_gitlab_webhook)
.service(handle_github_webhook)
.service(handle_beep_webhook)
// .service(handle_trello_callback)
// .service(handle_trello_callback)
})
.bind(("0.0.0.0", 8080))?
.run()
Expand Down
22 changes: 13 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ pub fn get_webhook_url_or_create(input: WebhookGetOrCreateInput) -> WebhookInfo
} else {
let random_string = create_random_string();
let name = "new_chat";
let new_chat = create_chat(CreateChatInput{
let new_chat = create_chat(CreateChatInput {
telegram_chat_id: &telegram_chat_id,
name,
webhook_url: &random_string,
telegram_thread_id
telegram_thread_id,
});
// let new_chat = create_chat(&chat_id.to_string(), name, &random_string);
let new_webhook = create_webhook(&random_string, name, new_chat.id);
Expand All @@ -108,15 +108,20 @@ pub fn show_webhooks() -> Vec<Webhook> {

pub struct CreateChatInput<'a> {
pub telegram_chat_id: &'a str,
pub name: &'a str,
pub webhook_url: &'a str,
pub telegram_thread_id: Option< &'a str>,
pub name: &'a str,
pub webhook_url: &'a str,
pub telegram_thread_id: Option<&'a str>,
}

pub fn create_chat(create_chat_input: CreateChatInput ) -> Chat {
let CreateChatInput { telegram_chat_id, name, webhook_url, telegram_thread_id } = create_chat_input;
pub fn create_chat(create_chat_input: CreateChatInput) -> Chat {
let CreateChatInput {
telegram_chat_id,
name,
webhook_url,
telegram_thread_id,
} = create_chat_input;

use self::schema::chats::{table};
use self::schema::chats::table;

let conn = &mut establish_connection();

Expand All @@ -127,7 +132,6 @@ pub fn create_chat(create_chat_input: CreateChatInput ) -> Chat {
thread_id: telegram_thread_id,
};


diesel::insert_into(table)
.values(&new_chat)
.get_result(conn)
Expand Down
33 changes: 19 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ pub mod http_server;
pub mod utils;
pub mod webhooks;

use crate::bots::bot_service::{BotConfig, BotService};
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use diesel::PgConnection;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use crate::bots::bot_service::{BotConfig, BotService};

pub type PgPool = Pool<ConnectionManager<PgConnection>>;
pub type PgPooledConnection = PooledConnection<ConnectionManager<PgConnection>>;
Expand All @@ -30,27 +30,32 @@ async fn main() {
let manager = ConnectionManager::<PgConnection>::new(database_url);
let pool = diesel::r2d2::Pool::new(manager).unwrap();
let mut connection = pool.get().unwrap();
connection.run_pending_migrations(MIGRATIONS).expect("Migrations failed");
connection
.run_pending_migrations(MIGRATIONS)
.expect("Migrations failed");

// task::spawn(run_gitlab_bot());
task::spawn(BotService::new(
BotConfig {
task::spawn(
BotService::new(BotConfig {
bot_name: "Gitlab".to_string(),
token: env::var("GITLAB_TELOXIDE_TOKEN").expect("GITLAB_TELOXIDE_TOKEN must be set"),
}
).run_bot());
task::spawn(BotService::new(
BotConfig {
})
.run_bot(),
);
task::spawn(
BotService::new(BotConfig {
bot_name: "Github".to_string(),
token: env::var("GITHUB_TELOXIDE_TOKEN").expect("GITHUB_TELOXIDE_TOKEN must be set"),
}
).run_bot());
task::spawn(BotService::new(
BotConfig {
})
.run_bot(),
);
task::spawn(
BotService::new(BotConfig {
bot_name: "Beep".to_string(),
token: env::var("BEEP_TELOXIDE_TOKEN").expect("BEEP_TELOXIDE_TOKEN must be set"),
}
).run_bot());
})
.run_bot(),
);
// task::spawn(run_github_bot());
// task::spawn(run_beep_bot());
// task::spawn(run_trello_bot());
Expand Down
6 changes: 1 addition & 5 deletions src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,4 @@ diesel::table! {

diesel::joinable!(webhooks -> chats (chat_id));

diesel::allow_tables_to_appear_in_same_query!(
chats,
trello_tokens,
webhooks,
);
diesel::allow_tables_to_appear_in_same_query!(chats, trello_tokens, webhooks,);
28 changes: 14 additions & 14 deletions src/webhooks/beep/http_server.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::bots::bot_service::{BotConfig, BotService, TelegramMessage};
use crate::utils::telegram_admin::send_message_to_admin;
use actix_web::{post, web, HttpResponse, Responder};
use notifine::{find_chat_by_id, find_webhook_by_webhook_url};
use std::env;
use crate::bots::bot_service::{BotConfig, BotService, TelegramMessage};

#[post("/beep/{webhook_url}")]
pub async fn handle_beep_webhook(
Expand Down Expand Up @@ -42,12 +42,10 @@ pub async fn handle_beep_webhook(
}
let chat = chat.unwrap();

let beep_bot = BotService::new(
BotConfig {
bot_name: "Beep".to_string(),
token: env::var("BEEP_TELOXIDE_TOKEN").expect("BEEP_TELOXIDE_TOKEN must be set"),
}
);
let beep_bot = BotService::new(BotConfig {
bot_name: "Beep".to_string(),
token: env::var("BEEP_TELOXIDE_TOKEN").expect("BEEP_TELOXIDE_TOKEN must be set"),
});

log::info!("Sending message to chat_id: {}", chat_id);
log::info!("Message: {}", message);
Expand All @@ -56,13 +54,15 @@ pub async fn handle_beep_webhook(

let thread_id = chat.thread_id.map(|tid| tid.parse::<i32>().ok()).flatten();

let result = beep_bot.send_telegram_message(
TelegramMessage {
chat_id: chat.telegram_id.parse::<i64>().expect("CHAT_ID must be an integer"),
let result = beep_bot
.send_telegram_message(TelegramMessage {
chat_id: chat
.telegram_id
.parse::<i64>()
.expect("CHAT_ID must be an integer"),
thread_id,
message,
},
)
})
.await;

if let Err(e) = result {
Expand All @@ -74,8 +74,8 @@ pub async fn handle_beep_webhook(
&beep_bot.bot,
format!("Event: {event_name:?}, Chat id: {chat_id}"),
)
.await
.unwrap();
.await
.unwrap();

HttpResponse::Ok()
}
28 changes: 14 additions & 14 deletions src/webhooks/github/http_server.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::bots::bot_service::{BotConfig, BotService, TelegramMessage};
use crate::utils::telegram_admin::send_message_to_admin;
use crate::webhooks::github::webhook_handlers::{ping::handle_ping_event, push::handle_push_event};
use actix_web::{post, web, HttpRequest, HttpResponse, Responder};
use notifine::{find_chat_by_id, find_webhook_by_webhook_url};
use std::env;
use crate::bots::bot_service::{BotConfig, BotService, TelegramMessage};

#[post("/github/{webhook_url}")]
pub async fn handle_github_webhook(
Expand Down Expand Up @@ -48,12 +48,10 @@ pub async fn handle_github_webhook(
}
let chat = chat.unwrap();

let github_bot = BotService::new(
BotConfig {
bot_name: "Github".to_string(),
token: env::var("GITHUB_TELOXIDE_TOKEN").expect("GITHUB_TELOXIDE_TOKEN must be set"),
}
);
let github_bot = BotService::new(BotConfig {
bot_name: "Github".to_string(),
token: env::var("GITHUB_TELOXIDE_TOKEN").expect("GITHUB_TELOXIDE_TOKEN must be set"),
});

log::info!("Sending message to chat_id: {}", chat_id);
log::info!("Message: {}", message);
Expand All @@ -62,13 +60,15 @@ pub async fn handle_github_webhook(

let thread_id = chat.thread_id.map(|tid| tid.parse::<i32>().ok()).flatten();

let result = github_bot.send_telegram_message(
TelegramMessage {
chat_id: chat.telegram_id.parse::<i64>().expect("CHAT_ID must be an integer"),
let result = github_bot
.send_telegram_message(TelegramMessage {
chat_id: chat
.telegram_id
.parse::<i64>()
.expect("CHAT_ID must be an integer"),
thread_id,
message,
},
)
})
.await;

if let Err(e) = result {
Expand All @@ -80,8 +80,8 @@ pub async fn handle_github_webhook(
&github_bot.bot,
format!("Event: {event_name:?}, Chat id: {chat_id}"),
)
.await
.unwrap();
.await
.unwrap();

HttpResponse::Ok()
} else {
Expand Down
Loading

0 comments on commit d8ef8f8

Please sign in to comment.