Skip to content

Commit

Permalink
Refactor Handler implementations and improve API key usage
Browse files Browse the repository at this point in the history
Implemented `ChatHandler` trait for chat message handling in the discord bot. The `process_message` method now takes in a reference instead of a cloned `Message` object, improving performance. The `new` method in `Handler` implementation also takes a reference to the `String` API key now, enhancing memory safety and efficiency.
  • Loading branch information
kasugamirai committed Feb 28, 2024
1 parent ab86b7b commit e7365dd
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 10 deletions.
5 changes: 3 additions & 2 deletions src/bin/bootstrap.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use gpt_discord_bot::ChatHandler;
use serenity::prelude::*;
use std::env;
use std::path::Path;
Expand All @@ -23,9 +24,9 @@ async fn main() {

// Create a new client with the discord token
let mut client = Client::builder(&discord_token, intents)
.event_handler(Handler::new(&gpt_api_key).await.unwrap())
.event_handler(Handler::new(&gpt_api_key))
.await
.expect("Error creating client");
.expect("Err creating client");

// Start listening for events
println!("Bot is now running. Press Ctrl+C to stop.");
Expand Down
18 changes: 10 additions & 8 deletions src/discord/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,25 @@ use tokio::select;
use tokio::time::interval;

// Define a trait representing handler behavior
#[async_trait]
pub trait ChatHandler {
// Create a new instance of the handler
fn new(api_key: String) -> Result<Self>
fn new(api_key: &String) -> Self
where
Self: Sized;

// Process an incoming message and return a response
fn process_message(&self, msg: Message) -> Option<String>;
async fn process_message(&self, msg: &Message) -> Option<String>;
}

// Handler struct implementing the ChatHandler trait
pub struct Handler {
pub gpt_client: ChatGPT,
}

impl Handler {
pub async fn new(api_key: &String) -> Result<Self> {
#[async_trait]
impl ChatHandler for Handler {
fn new(api_key: &String) -> Self {
let config: ModelConfiguration = ModelConfigurationBuilder::default()
.engine(ChatGPTEngine::Gpt4)
.timeout(Duration::from_secs(50))
Expand All @@ -32,11 +34,11 @@ impl Handler {
log::error!("Failed to build ModelConfiguration: {}", e);
ModelConfiguration::default()
});
let gpt_client = ChatGPT::new_with_config(api_key, config)?;
Ok(Self { gpt_client })
let gpt_client = ChatGPT::new_with_config(api_key, config).unwrap();
Self { gpt_client }
}

async fn process_message(&self, msg: Message) -> Option<String> {
async fn process_message(&self, msg: &Message) -> Option<String> {
if msg.author.bot || !msg.content.starts_with(".") {
return None;
}
Expand Down Expand Up @@ -69,7 +71,7 @@ impl Handler {
#[async_trait]
impl SerenityEventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
if let Some(result) = self.process_message(msg.clone()).await {
if let Some(result) = self.process_message(&msg).await {
let processing_future = msg.channel_id.say(&ctx.http, "Processing...");

match processing_future.await {
Expand Down
1 change: 1 addition & 0 deletions src/discord/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
mod bot;
pub use bot::ChatHandler;
pub use bot::Handler;
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
mod discord;
pub use crate::discord::ChatHandler;
pub use crate::discord::Handler;

0 comments on commit e7365dd

Please sign in to comment.