Skip to content

Commit

Permalink
Refactor main function and environment variable handling
Browse files Browse the repository at this point in the history
  • Loading branch information
kasugamirai committed Apr 1, 2024
1 parent 1895f6c commit c79a58e
Showing 1 changed file with 46 additions and 27 deletions.
73 changes: 46 additions & 27 deletions src/bin/bootstrap.rs
Original file line number Diff line number Diff line change
@@ -1,53 +1,72 @@
use gpt_discord_bot::ChatHandler;
use gpt_discord_bot::Handler;
use serenity::all::GatewayIntents;
use serenity::Client;
use std::env;
use std::path::Path;

use gpt_discord_bot::Handler;

#[tokio::main]
async fn main() {
// Initialize the logger
env_logger::init();
// Load environment variables from .env file
if Path::new(".env").exists() {
match dotenv::dotenv() {
Ok(_) => {}
Err(_) => println!("Failed to load .env file"),
}
}
// Get the discord token from the environment
let discord_token = match env::var("DISCORD_TOKEN") {
Ok(val) => val,
Err(_) => panic!("Expected a discord token in the environment"),
};
// Get the OpenAI API key from the environment
let gpt_api_key = match env::var("OPENAI_API_KEY") {
Ok(val) => val,
Err(_) => panic!("Expected a OPEN AI key in the environment"),
};

// Load environment variables
load_environment_variables();

// Set the intents for the bot
let intents = GatewayIntents::GUILD_MESSAGES | GatewayIntents::DIRECT_MESSAGES;

let handler_result = Handler::new(&gpt_api_key);
let handler_result = Handler::new(&get_env(
"OPENAI_API_KEY",
"Expected a OPEN AI key in the environment",
));
let handler = match handler_result {
Ok(handler) => handler,
Err(e) => panic!("Error creating handler: {}", e),
};

// Create a new client with the discord token
let mut client = match Client::builder(&discord_token, intents)
.event_handler(handler)
.await
{
Ok(client) => client,
Err(_) => panic!("Err creating client"),
};
let mut client = create_client(
&get_env(
"DISCORD_TOKEN",
"Expected a discord token in the environment",
),
intents,
handler,
)
.await;

// Start listening for events
println!("Bot is now running. Press Ctrl+C to stop.");
if let Err(why) = client.start().await {
log::error!("Client error: {:?}", why);
}
}

fn load_environment_variables() {
let path = ".env";
// Load environment variables from .env file
if Path::new(path).exists() {
match dotenv::dotenv() {
Ok(_) => {}
Err(_) => println!("Failed to load {} file", path),
}
}
}

fn get_env(key: &str, error_message: &str) -> String {
match env::var(key) {
Ok(val) => val,
Err(_) => panic!("{}", error_message),
}
}

async fn create_client(discord_token: &str, intents: GatewayIntents, handler: Handler) -> Client {
match Client::builder(discord_token, intents)
.event_handler(handler)
.await
{
Ok(client) => client,
Err(_) => panic!("Err creating client"),
}
}

0 comments on commit c79a58e

Please sign in to comment.