Simplify bot structure

This commit is contained in:
Victor Mignot 2022-11-20 19:16:45 -05:00
parent d4ef9632da
commit 1e35753d1f
No known key found for this signature in database
GPG key ID: FFE4EF056FB5E0D0
7 changed files with 20 additions and 92 deletions

View file

@ -2,7 +2,7 @@
DISCORD_TOKEN="Enter your Discord secret token" DISCORD_TOKEN="Enter your Discord secret token"
# MongoDB connection string # MongoDB connection string
MONGO_URI="Enter your Mongo connection string" MONGODB_URI="Enter your Mongo connection string"
# YorokoBot database name (if not set in Mongo URI) # YorokoBot database name (if not set in Mongo URI)
MONGO_DEFAULT_DB="Enter the MongoDB database name" MONGODB_DATABASE="Enter the MongoDB database name"

View file

@ -1,6 +1,6 @@
//! Module containing the Yorokobot client and used structs //! Module containing the Yorokobot client and used structs
use crate::{database::Client as DatabaseClient, errors::ClientError, DatabaseCredentials}; use crate::database::Client as DatabaseClient;
use crate::discord::client::DiscordClient; use crate::discord::client::DiscordClient;
/// Yorokobot's client. /// Yorokobot's client.
@ -33,23 +33,17 @@ pub struct Client {
database_client: DatabaseClient, database_client: DatabaseClient,
} }
/// Yorokobot connection credentials
pub struct ClientCredentials {
/// MongoDB connection string.
pub db_credentials: DatabaseCredentials,
}
impl Client { impl Client {
/// Create a Yorokobot client /// Create a Yorokobot client
pub async fn new(credentials: ClientCredentials) -> Result<Client, ClientError> { pub async fn new() -> Client {
let discord_client = DiscordClient::new().await; let discord_client = DiscordClient::new().await;
let database_client = DatabaseClient::new(credentials.db_credentials); let database_client = DatabaseClient::new();
Ok(Client { Client {
discord_client, discord_client,
database_client, database_client,
}) }
} }
/// Start connection to Discord API. /// Start connection to Discord API.
@ -59,10 +53,8 @@ impl Client {
} }
/// Connect client to the Mongo database then to the Discord API. /// Connect client to the Mongo database then to the Discord API.
pub async fn connect(&mut self) -> Result<(), ClientError> { pub async fn connect(&mut self) {
self.database_client.connect().await?; self.database_client.connect().await;
self.connect_discord().await; self.connect_discord().await;
Ok(())
} }
} }

View file

@ -3,4 +3,4 @@
pub mod client; pub mod client;
mod models; mod models;
pub use {client::Client, mongodb::options::ClientOptions as DatabaseCredentials}; pub use client::Client;

View file

@ -8,8 +8,6 @@ use mongodb::{
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::environment::get_env_variable; use crate::environment::get_env_variable;
use crate::errors::ClientError;
use crate::DatabaseCredentials;
use super::models::{YorokobotModel, COLLECTIONS_NAMES}; use super::models::{YorokobotModel, COLLECTIONS_NAMES};
@ -17,31 +15,29 @@ use super::models::{YorokobotModel, COLLECTIONS_NAMES};
pub struct Client { pub struct Client {
mongo_client: Option<MongoClient>, mongo_client: Option<MongoClient>,
database: Option<Database>, database: Option<Database>,
credentials: DatabaseCredentials,
} }
impl Client { impl Client {
/// Create a new database client /// Create a new database client
pub fn new(credentials: DatabaseCredentials) -> Client { pub fn new() -> Client {
Client { Client {
credentials,
mongo_client: None, mongo_client: None,
database: None, database: None,
} }
} }
/// Connect the client /// Connect the client
pub async fn connect(&mut self) -> Result<(), ClientError> { pub async fn connect(&mut self) {
self.mongo_client = match MongoClient::with_options(self.credentials.to_owned()) { self.mongo_client = match MongoClient::with_uri_str(get_env_variable("MONGODB_URI")).await {
Ok(c) => Some(c), Ok(c) => Some(c),
Err(e) => return Err(ClientError::Database(e)), Err(e) => panic!("Failed to connect to Mongo database: {e}"),
}; };
self.database = Some( self.database = Some(
self.mongo_client self.mongo_client
.as_ref() .as_ref()
.unwrap() .unwrap()
.database(get_env_variable("MONGO_DEFAULT_DB").as_str()), .database(get_env_variable("MONGODB_DATABASE").as_str()),
); );
// TODO: // TODO:
@ -49,8 +45,6 @@ impl Client {
// Ex: DatabaseConnection // Ex: DatabaseConnection
self.check_init_error().await; self.check_init_error().await;
Ok(())
} }
async fn check_init_error(&mut self) { async fn check_init_error(&mut self) {

View file

@ -1,14 +0,0 @@
//! Common Yorokobot errors
pub use mongodb::error::Error as DatabaseError;
pub use serenity::prelude::SerenityError as DiscordError;
/// The kind of errors that can be returned by Client::new
#[derive(Debug)]
pub enum ClientError {
/// Serenity error while building client
Discord(DiscordError),
///Mongo error while parsing options
Database(DatabaseError),
}

View file

@ -10,9 +10,5 @@ mod client;
mod database; mod database;
mod discord; mod discord;
mod environment; mod environment;
pub mod errors;
pub use crate::{ pub use crate::client::Client;
client::{Client, ClientCredentials},
database::DatabaseCredentials,
};

View file

@ -1,51 +1,11 @@
use log::error; use yorokobot::Client;
use std::env;
use yorokobot::{errors::ClientError, Client, ClientCredentials, DatabaseCredentials};
#[tokio::main] #[tokio::main]
async fn main() -> std::process::ExitCode { async fn main() {
// Start the logger // Start the logger
log4rs::init_file("log4rs_config.yaml", Default::default()).unwrap(); log4rs::init_file("log4rs_config.yaml", Default::default()).unwrap();
let mongodb_uri = match env::var("MONGODB_URI") { let mut client = Client::new().await;
Ok(u) => u,
Err(_) => {
error!(target: "bot_warn_errors", "Could not find MONGODB_URI environment variable.");
return std::process::ExitCode::FAILURE;
}
};
let db_credentials = match DatabaseCredentials::parse(mongodb_uri).await { client.connect().await;
Ok(c) => c,
Err(_) => {
error!(target: "bot_warn_errors", "Could not parse database credentials.");
return std::process::ExitCode::FAILURE;
}
};
let credentials = ClientCredentials { db_credentials };
let mut client = match Client::new(credentials).await {
Ok(c) => c,
Err(_) => {
error!(target: "bot_warn_errors", "Could not instantiate the bot client.");
return std::process::ExitCode::FAILURE;
}
};
if let Err(error) = client.connect().await {
match error {
ClientError::Database(e) => {
error!(target: "bot_warn_errors", "Could not connect to database: {:?}", e)
}
ClientError::Discord(e) => {
error!(target: "bot_warn_errors", "Could not connect to Discord: {:?}", e)
}
};
return std::process::ExitCode::FAILURE;
}
std::process::ExitCode::SUCCESS
} }