Advanced program structure for commands

This commit is contained in:
Victor Mignot 2022-11-20 23:45:40 -05:00
parent 2146b50ab6
commit 3a437db2b6
No known key found for this signature in database
GPG key ID: FFE4EF056FB5E0D0
8 changed files with 35 additions and 90 deletions

View file

@ -1,60 +1,42 @@
//! Module containing the Yorokobot client and used structs use serenity::{prelude::GatewayIntents, Client as SerenityClient};
use crate::database::Client as DatabaseClient; use crate::{database::Client as DatabaseClient, environment::get_env_variable};
use crate::discord::event_handler::Handler;
use crate::discord::client::DiscordClient;
/// Yorokobot's client.
/// Used for connecting to the Discord API and your MongoDB database
///
/// # Example
/// ```rust,no_run
/// # async fn run() {
/// use yorokobot::{Client, ClientCredentials, DatabaseCredentials};
///
/// let discord_token = String::from("Your discord token");
/// let mongo_uri = String::from("Your Mongo URI");
///
/// let credentials = ClientCredentials {
/// discord_token: &discord_token,
/// db_credentials: DatabaseCredentials::parse(mongo_uri).await.expect("Failed parsing credentials"),
/// };
///
/// let mut client = Client::new(credentials).await.expect("Error creating client");
///
/// client.connect().await;
///
/// # }
/// ```
pub struct Client { pub struct Client {
/// The Serenity Discord Client serenity_client: SerenityClient,
discord_client: DiscordClient,
/// The database client
database_client: DatabaseClient, database_client: DatabaseClient,
} }
impl Client { impl<'a> Client {
/// Create a Yorokobot client async fn new() -> Self {
pub async fn new() -> Client { let discord_token = get_env_variable("DISCORD_TOKEN");
let discord_client = DiscordClient::new().await; let intents = GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT;
let database_client = DatabaseClient::new(); let database_client = DatabaseClient::new();
let event_handler = Handler {
database: &database_client,
};
let serenity_client = match SerenityClient::builder(discord_token, intents)
.event_handler(event_handler)
.await
{
Ok(c) => c,
Err(e) => panic!("Failed to instantiate Discord Client: {e}"),
};
Client { Client {
discord_client, serenity_client,
database_client, database_client,
} }
} }
/// Start connection to Discord API. pub async fn start(&mut self) {
/// Wrap [`serenity::client::Client`] start method.
pub async fn connect_discord(&mut self) {
self.discord_client.start().await;
}
/// Connect client to the Mongo database then to the Discord API.
pub async fn connect(&mut self) {
self.database_client.connect().await; self.database_client.connect().await;
self.connect_discord().await;
if let Err(e) = self.serenity_client.start().await {
panic!("Could not connect the bot: {e}");
}
} }
} }

View file

@ -1,2 +1 @@
pub mod client; pub mod event_handler;
mod event_handler;

View file

@ -1,40 +0,0 @@
use serenity::{prelude::GatewayIntents, Client};
use crate::environment::get_env_variable;
use super::event_handler::Handler;
pub struct DiscordClient {
serenity_client: Option<Client>,
}
impl DiscordClient {
pub async fn new() -> Self {
let discord_token = get_env_variable("DISCORD_TOKEN");
let intents = GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT;
let serenity_client = match Client::builder(&discord_token, intents)
.event_handler(Handler)
.await
{
Ok(c) => c,
Err(e) => panic!("Failed to instantiate Discord Client: {e}"),
};
DiscordClient {
serenity_client: Some(serenity_client),
}
}
pub async fn start(&mut self) {
if let Err(e) = self
.serenity_client
.as_mut()
.expect("No bot instance was created.")
.start()
.await
{
panic!("Could not connect the bot: {e}");
}
}
}

0
src/discord/commands.rs Normal file
View file

View file

View file

@ -8,12 +8,16 @@ use serenity::{
prelude::{Context, EventHandler}, prelude::{Context, EventHandler},
}; };
use crate::database::Client as DatabaseClient;
const MAX_ARGS_NUMBER: u32 = 25; const MAX_ARGS_NUMBER: u32 = 25;
pub struct Handler; pub struct Handler<'a> {
pub database: &'a DatabaseClient,
}
#[async_trait] #[async_trait]
impl EventHandler for Handler { impl EventHandler for Handler<'_> {
async fn ready(&self, ctx: Context, ready: Ready) { async fn ready(&self, ctx: Context, ready: Ready) {
println!("Successfully connected as {}", ready.user.name); println!("Successfully connected as {}", ready.user.name);

View file

@ -3,7 +3,7 @@
//! //!
//! [`Serenity`]: https://github.com/serenity-rs/serenity //! [`Serenity`]: https://github.com/serenity-rs/serenity
#![deny(missing_docs)] //#![deny(missing_docs)]
#![deny(warnings)] #![deny(warnings)]
mod client; mod client;

View file

@ -7,5 +7,5 @@ async fn main() {
let mut client = Client::new().await; let mut client = Client::new().await;
client.connect().await; client.start().await;
} }