From 9c0b011ef2e9b3b57b0e2beb5b2c205ed5fa8fa9 Mon Sep 17 00:00:00 2001 From: max Date: Sun, 11 Feb 2024 19:59:11 +0000 Subject: [PATCH] feat: mise en place d'un process pour stop l'app (qui dois etre temporaire car trop sale ) --- src/bot/init.rs | 24 ++++++++++++++++++++++-- src/main.rs | 12 ++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/bot/init.rs b/src/bot/init.rs index f336e7c..cbd2322 100644 --- a/src/bot/init.rs +++ b/src/bot/init.rs @@ -12,13 +12,14 @@ use serenity::{ }; use std::collections::HashSet; use std::fs; +use tokio::sync::oneshot; use tokio::task::spawn_blocking; #[group] #[commands(ping)] struct General; -pub fn start_bot(config: Config) { +pub fn start_bot(config: Config, rx: oneshot::Receiver<()>) { if config.token != "" { spawn_blocking(move || { let rt = tokio::runtime::Handle::current(); @@ -93,9 +94,28 @@ pub fn start_bot(config: Config) { data.insert::(config_parsed.clone()); data.insert::(config.clone()); } - if let Err(why) = client.start().await { + + let shard_manager = client.shard_manager.clone(); + let client_start = client.start_autosharded(); + tokio::spawn(async move { + match rx.await { + Ok(_) => { + println!("Received shutdown signal"); + shard_manager.shutdown_all().await; + println!("Shutting down bot"); + } + Err(_) => { + println!("Channel dropped signal"); + shard_manager.shutdown_all().await; + println!("Shutting down bot"); + } + } + }); + + if let Err(why) = client_start.await { println!("Client error: {why:?}"); } + println!("Bot stopped."); }) .await; }) diff --git a/src/main.rs b/src/main.rs index a4a7a8e..571f4f2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,10 +3,13 @@ mod config; mod db; mod img; +use std::{process, time::Duration}; + use actix_cors::Cors; use actix_web::{App, HttpServer}; use bot::init::start_bot; use config::parse_local_config; +use tokio::{sync::oneshot, time::sleep}; #[tokio::main] // or #[actix_web::main] async fn main() -> std::io::Result<()> { @@ -19,7 +22,8 @@ async fn main() -> std::io::Result<()> { return Ok(()); } } - start_bot(config.clone()); + let (tx, rx) = oneshot::channel(); + start_bot(config.clone(), rx); HttpServer::new(|| { let cors = Cors::default() .allow_any_header() @@ -30,5 +34,9 @@ async fn main() -> std::io::Result<()> { .bind(("0.0.0.0", port))? .run() .await?; - Ok(()) + println!("API Server stopped."); + tx.send(()).unwrap(); + println!("Signal sent to bot."); + sleep(Duration::from_secs(2)).await; + process::exit(1); // This is a workaround to stop the bot, it should be replaced by a better solution }