Set discord token fetching into library

This commit is contained in:
Victor Mignot 2022-11-20 18:55:20 -05:00
parent b03625443a
commit d4ef9632da
No known key found for this signature in database
GPG key ID: FFE4EF056FB5E0D0
4 changed files with 25 additions and 43 deletions

View file

@ -2,8 +2,7 @@
use crate::{database::Client as DatabaseClient, errors::ClientError, DatabaseCredentials}; use crate::{database::Client as DatabaseClient, errors::ClientError, DatabaseCredentials};
use serenity::{prelude::GatewayIntents, Client as DiscordClient}; use crate::discord::client::DiscordClient;
/// Yorokobot's client. /// Yorokobot's client.
/// Used for connecting to the Discord API and your MongoDB database /// Used for connecting to the Discord API and your MongoDB database
/// ///
@ -35,26 +34,15 @@ pub struct Client {
} }
/// Yorokobot connection credentials /// Yorokobot connection credentials
pub struct ClientCredentials<'a> { pub struct ClientCredentials {
/// Token for Discord API
pub discord_token: &'a String,
/// MongoDB connection string. /// MongoDB connection string.
pub db_credentials: DatabaseCredentials, pub db_credentials: DatabaseCredentials,
} }
impl<'a> Client { impl Client {
/// Create a Yorokobot client /// Create a Yorokobot client
pub async fn new(credentials: ClientCredentials<'a>) -> Result<Client, ClientError> { pub async fn new(credentials: ClientCredentials) -> Result<Client, ClientError> {
let discord_client = match DiscordClient::builder( let discord_client = DiscordClient::new().await;
credentials.discord_token,
GatewayIntents::empty(),
)
.await
{
Ok(c) => c,
Err(e) => return Err(ClientError::Discord(e)),
};
let database_client = DatabaseClient::new(credentials.db_credentials); let database_client = DatabaseClient::new(credentials.db_credentials);
@ -66,17 +54,14 @@ impl<'a> Client {
/// Start connection to Discord API. /// Start connection to Discord API.
/// Wrap [`serenity::client::Client`] start method. /// Wrap [`serenity::client::Client`] start method.
pub async fn connect_discord(&mut self) -> Result<(), ClientError> { pub async fn connect_discord(&mut self) {
match self.discord_client.start().await { self.discord_client.start().await;
Ok(_) => Ok(()),
Err(e) => Err(ClientError::Discord(e)),
}
} }
/// 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) -> Result<(), ClientError> {
self.database_client.connect().await?; self.database_client.connect().await?;
self.connect_discord().await?; self.connect_discord().await;
Ok(()) Ok(())
} }

View file

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

View file

@ -4,19 +4,16 @@ use crate::environment::get_env_variable;
use super::event_handler::Handler; use super::event_handler::Handler;
const INTENTS: GatewayIntents = GatewayIntents::empty(); pub struct DiscordClient {
struct DiscordClient {
serenity_client: Option<Client>, serenity_client: Option<Client>,
discord_token: String,
} }
impl DiscordClient { impl DiscordClient {
pub async fn new() -> Self { pub async fn new() -> Self {
let discord_token = get_env_variable("DISCORD_TOKEN"); 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) let serenity_client = match Client::builder(&discord_token, intents)
.event_handler(Handler) .event_handler(Handler)
.await .await
{ {
@ -25,8 +22,19 @@ impl DiscordClient {
}; };
DiscordClient { DiscordClient {
discord_token,
serenity_client: Some(serenity_client), 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}");
}
}
} }

View file

@ -8,14 +8,6 @@ async fn main() -> std::process::ExitCode {
// 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 discord_token = match env::var("DISCORD_TOKEN") {
Ok(t) => t,
Err(_) => {
error!(target: "bot_warn_errors", "Could not find DISCORD_TOKEN environment variable.");
return std::process::ExitCode::FAILURE;
}
};
let mongodb_uri = match env::var("MONGODB_URI") { let mongodb_uri = match env::var("MONGODB_URI") {
Ok(u) => u, Ok(u) => u,
Err(_) => { Err(_) => {
@ -32,10 +24,7 @@ async fn main() -> std::process::ExitCode {
} }
}; };
let credentials = ClientCredentials { let credentials = ClientCredentials { db_credentials };
discord_token: &discord_token,
db_credentials,
};
let mut client = match Client::new(credentials).await { let mut client = match Client::new(credentials).await {
Ok(c) => c, Ok(c) => c,