Skip to content

Commit

Permalink
Refactor discord bot code and improve API key handling
Browse files Browse the repository at this point in the history
Introduced a `ChatHandler` trait to manage message processing in the discord bot. Updated `process_message` function to exclude unused `Context` parameter. Also, made a change to accept a reference to `String` when creating a new `Handler`, enhancing safety and efficiency while using the API key.
  • Loading branch information
kasugamirai committed Feb 27, 2024
1 parent 0cdee5c commit ab86b7b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
7 changes: 2 additions & 5 deletions src/bin/bootstrap.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use serenity::{client::Client, prelude::*};
use serenity::prelude::*;
use std::env;
use std::path::Path;
use tokio;

use dotenv;

use gpt_discord_bot::Handler;

Expand All @@ -26,7 +23,7 @@ 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.unwrap())
.await
.expect("Error creating client");

Expand Down
18 changes: 15 additions & 3 deletions src/discord/bot.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
use chatgpt::prelude::*;
use futures::StreamExt;
use serenity::client::{Context, EventHandler};
use serenity::client::{Context, EventHandler as SerenityEventHandler};
use serenity::{async_trait, builder::EditMessage, model::channel::Message};
use std::time::Duration;
use tokio::select;
use tokio::time::interval;

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

// Process an incoming message and return a response
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> {
pub async fn new(api_key: &String) -> Result<Self> {
let config: ModelConfiguration = ModelConfigurationBuilder::default()
.engine(ChatGPTEngine::Gpt4)
.timeout(Duration::from_secs(50))
Expand Down Expand Up @@ -55,7 +67,7 @@ impl Handler {
}

#[async_trait]
impl EventHandler for Handler {
impl SerenityEventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
if let Some(result) = self.process_message(msg.clone()).await {
let processing_future = msg.channel_id.say(&ctx.http, "Processing...");
Expand Down

0 comments on commit ab86b7b

Please sign in to comment.