extract DiscordClient logic to it's own struct

This commit is contained in:
Vilmos Zsombor TANCZOS 2025-05-02 16:07:31 +02:00
parent 0488ce4b9b
commit ef3561d86b
2 changed files with 71 additions and 54 deletions

67
src/client.rs Normal file
View file

@ -0,0 +1,67 @@
use poise::PrefixFrameworkOptions;
use crate::{commands, prelude::*};
pub struct DiscordClient {
client: serenity::Client,
}
impl DiscordClient {
pub async fn new(token: &str) -> Result<Self, serenity::Error> {
let intents =
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;
let framework = poise::Framework::builder()
.options(poise::FrameworkOptions {
commands: commands::get(),
prefix_options: PrefixFrameworkOptions {
prefix: Some(",".into()),
..Default::default()
},
on_error: |error| Box::pin(on_error(error)),
..Default::default()
})
.setup(|ctx, ready, framework| {
Box::pin(async move {
info!("Logged in as {}", ready.user.name);
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(KBotData {})
})
})
.build();
let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await?;
Ok(Self { client })
}
pub async fn start(&mut self) -> Result<(), serenity::Error> {
self.client.start().await
}
}
async fn on_error(error: poise::FrameworkError<'_, KBotData, Error>) {
match error {
poise::FrameworkError::Command { error, ctx, .. } => {
let error = error;
error!("Error in command `{}`: {}", ctx.command().name, error,);
let _ = ctx.say("Failed to run command.".to_string()).await;
}
// poise::FrameworkError::ArgumentParse {
// error, input, ctx, ..
// } => {
// debug!(
// "Failed to parse argument `{:?}` for command `{}`: {}",
// input,
// ctx.command().name,
// error
// );
// }
error => {
if let Err(e) = poise::builtins::on_error(error).await {
error!("Error while handling error: {}", e);
}
}
}
}

View file

@ -1,7 +1,7 @@
use poise::PrefixFrameworkOptions;
use tracing::{error, info};
use client::DiscordClient;
mod checks;
mod client;
mod commands;
pub mod prelude {
@ -10,8 +10,8 @@ pub mod prelude {
pub type Error = Box<dyn std::error::Error + Send + Sync>;
pub type Context<'a> = poise::Context<'a, KBotData, Error>;
pub type CommandResult = Result<(), Error>;
pub use tracing::{debug, error, info, trace, warn};
}
use prelude::*;
#[tokio::main]
async fn main() {
@ -20,56 +20,6 @@ async fn main() {
dotenv::dotenv().ok();
let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
let intents =
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;
let framework = poise::Framework::builder()
.options(poise::FrameworkOptions {
commands: commands::get(),
prefix_options: PrefixFrameworkOptions {
prefix: Some(",".into()),
..Default::default()
},
on_error: |error| Box::pin(on_error(error)),
..Default::default()
})
.setup(|ctx, ready, framework| {
Box::pin(async move {
info!("Logged in as {}", ready.user.name);
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(KBotData {})
})
})
.build();
let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;
let client = DiscordClient::new(&token).await;
client.unwrap().start().await.unwrap();
}
async fn on_error(error: poise::FrameworkError<'_, KBotData, Error>) {
match error {
poise::FrameworkError::Command { error, ctx, .. } => {
let error = error;
error!("Error in command `{}`: {}", ctx.command().name, error,);
let _ = ctx.say("Failed to run command.".to_string()).await;
}
// poise::FrameworkError::ArgumentParse {
// error, input, ctx, ..
// } => {
// debug!(
// "Failed to parse argument `{:?}` for command `{}`: {}",
// input,
// ctx.command().name,
// error
// );
// }
error => {
if let Err(e) = poise::builtins::on_error(error).await {
error!("Error while handling error: {}", e);
}
}
}
}