Recombined bot and service, fixed dockerfile

This commit is contained in:
Benjamin Sherriff
2023-10-05 15:38:59 -04:00
parent 5915a29dd5
commit 5dcc2a6afc
27 changed files with 64 additions and 153 deletions

View File

@@ -0,0 +1,190 @@
use std::collections::HashMap;
use std::sync::Arc;
use log::debug;
use serenity::model::application::interaction::{InteractionResponseType, application_command::ApplicationCommandInteraction};
use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User;
use serenity::prelude::*;
use songbird::{Call, Songbird};
use songbird::input::{Restartable, Input, Metadata, error::Error as SongbirdError};
pub mod pause;
pub mod play;
pub mod resume;
pub mod skip;
pub mod stop;
pub mod volume;
#[derive(Clone, Debug)]
pub struct AudioConfigs;
impl TypeMapKey for AudioConfigs {
type Value = Arc<RwLock<HashMap<GuildId, AudioConfig>>>;
}
#[derive(Clone, Debug)]
pub struct AudioConfig {
pub volume: f32
}
/// Joins a Discord voice channel.
///
/// # Arguments
/// - ctx - The context of the command.
/// - guild_id_option - The guild ID of the guild to join.
/// - user - The user that is requesting to join the voice channel.
///
/// # Returns
/// Result<(), String> - Ok if the bot successfully joined the voice channel, Err if there was an error.
pub async fn join(ctx: &Context, guild_id_option: &Option<GuildId>, user: &User) -> Result<(), String> {
let guild_id = match guild_id_option {
Some(g) => g,
None => {
return Err(format!("{}", "No guild ID set"));
}
};
let channel_id = match find_voice_channel(&ctx, &guild_id, &user) {
Ok(channel) => channel,
Err(err) => return Err(format!("{}", err))
};
debug!("<{}> Joining channel {}", guild_id.0, channel_id);
let manager = get_songbird(ctx).await;
let (_handle_lock, success) = manager.join(guild_id.to_owned(), channel_id.to_owned()).await;
match success {
Ok(s) => Ok(s),
Err(err) => Err(format!("{}", err))
}
}
/// Leaves a Discord voice channel.
///
/// # Arguments
/// - ctx - The context of the command.
/// - guild_id_option - The guild ID of the guild to leave.
///
/// # Returns
/// Result<(), String> - Ok if the bot successfully left the voice channel, Err if there was an error.
pub async fn leave(ctx: &Context, guild_id_option: &Option<GuildId>) -> Result<(), String> {
let guild_id = match guild_id_option {
Some(g) => g,
None => {
return Err(format!("{}", "No guild ID set"));
}
};
let manager = get_songbird(ctx).await;
if manager.get(*guild_id).is_some() {
debug!("<{}> Disconnecting from channel", guild_id.0);
if let Err(e) = manager.remove(*guild_id).await {
return Err(format!("{}", e))
}
}
Ok(())
}
/// Finds the voice channel that the user is in.
///
/// # Arguments
/// - ctx - The context of the command.
/// - guild_id - The guild ID of the guild to search.
/// - user - The user to search for.
///
/// # Returns
/// Result<ChannelId, String> - Ok if the user is in a voice channel, Err if the user is not in a voice channel.
fn find_voice_channel(ctx: &Context, guild_id: &GuildId, user: &User) -> Result<ChannelId, String> {
let guild = match guild_id.to_guild_cached(ctx.cache.to_owned()) {
Some(g) => g,
None => return Err(format!("Guild not found"))
};
match guild.voice_states.get(&user.id).and_then(|voice_state| voice_state.channel_id) {
Some(channel) => Ok(channel),
None => return Err(format!("User is not in a voice channel"))
}
}
/// Creates a response to an interaction.
///
/// # Arguments
/// - ctx - The context of the command.
/// - command - The command that was sent.
/// - content - The content of the response.
///
/// # Returns
/// Result<(), SerenityError> - Ok if the response was created successfully, Err if there was an error.
pub async fn create_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<(), SerenityError> {
command.create_interaction_response(&ctx.http, |response: &mut serenity::builder::CreateInteractionResponse<'_>| {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|message: &mut serenity::builder::CreateInteractionResponseData<'_>| message.content(content))
}).await
}
/// Edits a response to an interaction.
///
/// # Arguments
/// - ctx - The context of the command.
/// - command - The command that was sent.
/// - content - The content of the response.
///
/// # Returns
/// Result<Message, SerenityError> - Ok if the response was edited successfully, Err if there was an error.
pub async fn edit_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<serenity::model::channel::Message, SerenityError> {
command.edit_original_interaction_response(&ctx.http, |response: &mut serenity::builder::EditInteractionResponse| {
response.content(content)
}).await
}
/// Adds a song to the queue.
///
/// # Arguments
/// - call - The call to add the song to.
/// - url - The URL of the song to add.
/// - lazy - Whether or not to lazy load the song.
///
/// # Returns
/// Result<Metadata, SongbirdError> - Ok if the song was added successfully, Err if there was an error.
pub async fn add_song(call: Arc<Mutex<Call>>, url: &str, lazy: bool, audio_config: Option<&AudioConfig>) -> Result<Metadata, SongbirdError> {
let source = if is_valid_url(url) {
Restartable::ytdl(url.to_owned(), lazy).await?
} else {
Restartable::ytdl_search(url, lazy).await?
};
let mut handler = call.lock().await;
let track: Input = source.into();
let metadata = *track.metadata.clone();
let track_handle = handler.enqueue_source(track);
if let Some(ac) = audio_config {
let _ = track_handle.set_volume(ac.volume);
}
Ok(metadata)
}
/// Checks if a string is a valid URL.
///
/// # Arguments
/// - url - The string to check.
///
/// # Returns
/// bool - True if the string is a valid URL, false if it is not.
fn is_valid_url(url: &str) -> bool {
match url.parse::<reqwest::Url>() {
Ok(_) => return true,
Err(_) => return false
}
}
/// Gets the Songbird voice client.
///
/// # Arguments
/// - ctx - The context of the command.
///
/// # Returns
/// Arc<Songbird> - The Songbird voice client.
pub async fn get_songbird(ctx: &Context) -> Arc<Songbird> {
songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization")
}

View File

@@ -0,0 +1,43 @@
use log::{debug, error};
use serenity::prelude::*;
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why);
return;
}
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
error!("Failed to edit response message: {}", why);
}
return;
}
};
let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
if let Err(err) = handler.queue().pause() {
if let Err(why) = edit_response(&ctx, &command, format!("Failed to pause: {}", err)).await {
error!("Failed to edit response message: {}", why);
}
} else {
debug!("Paused the track");
if let Err(why) = edit_response(&ctx, &command, format!("Pausing the track")).await {
error!("Failed to edit response message: {}", why);
}
}
}
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("pause").description("Pause the current track")
}

View File

@@ -0,0 +1,134 @@
use log::{debug, warn, error};
use serenity::{prelude::*, async_trait};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use songbird::EventHandler;
use crate::bot::commands::audio::{join, leave, add_song, get_songbird, AudioConfigs};
use super::{create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Get the track url
let track_url = match command.data.options.get(0) {
Some(t) => match &t.value {
Some(v) => match v.as_str() {
Some(s) => s.to_owned(),
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
}
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
}
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
};
// Create the initial response
if let Err(why) = create_response(&ctx, &command, format!("Processing command...")).await {
error!("Failed to create response message: {}", why);
return;
}
match join(&ctx, &command.guild_id, &command.user).await {
Ok(_) => {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
error!("Failed to edit response message: {}", why);
}
return;
}
};
debug!("Play command executed with track: {:?}", track_url);
let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) {
let is_queue_empty = {
let call_handler = handler_lock.lock().await;
call_handler.queue().is_empty()
};
let audio_config = {
let data_read = ctx.data.read().await;
data_read.get::<AudioConfigs>().expect("Expected AudioConfigs in TypeMap.").clone()
};
let ac = audio_config.read().await;
match add_song(handler_lock.clone(), &track_url, is_queue_empty, ac.get(&guild_id)).await {
Ok(added_song) => {
let track_title = added_song.title.unwrap();
debug!("Added track: {}", track_title);
if let Err(why) = edit_response(&ctx, &command, format!("Added track to queue: {}", track_title)).await {
error!("Failed to edit response message: {}", why);
}
let mut handler = handler_lock.lock().await;
handler.remove_all_global_events();
handler.add_global_event(songbird::Event::Track(songbird::TrackEvent::End), TrackEndNotifier { guild_id, call: manager })
}
Err(why) => {
warn!("Failed to add song: {}", why);
if let Err(why) = edit_response(&ctx, &command, format!("Failed to add song: {}", why)).await {
error!("Failed to edit response message: {}", why);
}
if let Err(why) = leave(&ctx, &command.guild_id).await {
error!("Failed to leave voice channel: {}", why);
}
return;
}
};
}
},
Err(err) => {
warn!("{}", err);
if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await {
error!("Failed to edit response message: {}", why);
}
}
}
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("play").description("Plays the given track").create_option(|option| { option
.name("track")
.description("The track to be played")
.kind(serenity::model::prelude::command::CommandOptionType::String)
.required(true)
})
}
struct TrackEndNotifier {
pub call: std::sync::Arc<songbird::Songbird>,
pub guild_id: serenity::model::id::GuildId
}
#[async_trait]
impl EventHandler for TrackEndNotifier {
async fn act(&self, ctx: &songbird::events::EventContext<'_>) -> Option<songbird::events::Event> {
if let songbird::EventContext::Track(_track_list) = ctx {
if let Some(call) = self.call.get(self.guild_id) {
let mut handler = call.lock().await;
if handler.queue().is_empty() {
debug!("Queue is empty, leaving voice channel");
handler.leave().await.unwrap();
}
}
}
None
}
}

View File

@@ -0,0 +1,43 @@
use log::{debug, error};
use serenity::prelude::*;
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why);
return;
}
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
error!("Failed to edit response message: {}", why);
}
return;
}
};
let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
if let Err(err) = handler.queue().resume() {
if let Err(why) = edit_response(&ctx, &command, format!("Failed to resume: {}", err)).await {
error!("Failed to edit response message: {}", why);
}
} else {
debug!("Resumed the track");
if let Err(why) = edit_response(&ctx, &command, format!("Resuming the track")).await {
error!("Failed to edit response message: {}", why);
}
}
}
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("resume").description("Resume the current track")
}

View File

@@ -0,0 +1,43 @@
use log::{debug, error};
use serenity::prelude::*;
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why);
return;
}
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
error!("Failed to edit response message: {}", why);
}
return;
}
};
let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
if let Err(err) = handler.queue().skip() {
if let Err(why) = edit_response(&ctx, &command, format!("Failed to skip: {}", err)).await {
error!("Failed to edit response message: {}", why);
}
} else {
debug!("Skipped the track");
if let Err(why) = edit_response(&ctx, &command, format!("Skipping the track")).await {
error!("Failed to edit response message: {}", why);
}
}
}
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("skip").description("Skip the current track")
}

View File

@@ -0,0 +1,38 @@
use log::{debug, error};
use serenity::prelude::*;
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why);
return;
}
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
error!("Failed to edit response message: {}", why);
}
return;
}
};
let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
handler.queue().stop();
debug!("Stopped the track");
if let Err(why) = edit_response(&ctx, &command, format!("Stopping the tracks")).await {
error!("Failed to edit response message: {}", why);
}
}
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("stop").description("Stop the current track and clear the queue")
}

View File

@@ -0,0 +1,85 @@
use log::{error, warn};
use serenity::prelude::*;
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response, AudioConfigs, AudioConfig};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Get the volume
let volume = match command.data.options.get(0) {
Some(t) => match &t.value {
Some(v) => match v.as_i64() {
Some(p) => std::cmp::min(100, std::cmp::max(0, p)),
None => {
warn!("Unable to get volume option as a string");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
}
None => {
warn!("Missing volume option value");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
}
None => {
warn!("Missing volume option");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
};
// Format volume to f32 bound between 0.0 and 1.0
let bound_volume = volume as f32 / 100.0;
// Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why);
return;
}
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
error!("Failed to edit response message: {}", why);
}
return;
}
};
let audio_config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<AudioConfigs>().expect("Expected AudioConfigs in TypeMap.").clone()
};
{
let mut audio_configs = audio_config_lock.write().await;
*audio_configs.entry(guild_id).or_insert(AudioConfig { volume: 1.0 }) = AudioConfig { volume: bound_volume };
}
let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
for (_, track_handle) in handler.queue().current_queue().iter().enumerate() {
let _ = track_handle.set_volume(bound_volume);
}
}
if let Err(why) = edit_response(&ctx, &command, format!("Setting the volume to {}", volume)).await {
error!("Failed to set the volume: {}", why);
}
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("volume").description("Set the audio player volume").create_option(|option| { option
.name("volume")
.description("Volume between 0 and 100")
.kind(serenity::model::prelude::command::CommandOptionType::Integer)
.required(true)
})
}

View File

View File

@@ -0,0 +1,5 @@
pub mod audio;
pub mod help;
pub mod oai;
pub mod ping;
pub mod schedule;

View File

@@ -0,0 +1,326 @@
use log::{error, debug, trace, warn};
use serde::{Serialize, Deserialize};
use serde_json::Value;
use serenity::model::Permissions;
use serenity::model::channel::Message;
use serenity::model::prelude::{ChannelType, PermissionOverwrite, PermissionOverwriteType};
use serenity::prelude::*;
use siren::{GetResponse, ServiceError};
pub struct OAI {
pub client: reqwest::Client,
pub base_url: String,
pub service_url: String,
pub max_attempts: i64,
pub token: String,
pub max_tokens: i64,
pub default_model: GPTModel,
pub max_context_questions: i64
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ChatCompletionRequest {
model: GPTModel,
messages: Vec<ChatCompletionMessage>,
/// Value between 0 and 2
#[serde(skip_serializing_if = "Option::is_none")]
temperature: Option<f64>,
/// Value between 0 and 1
#[serde(skip_serializing_if = "Option::is_none")]
top_p: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
n: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
max_tokens: Option<i64>,
/// Value between -2.0 and 2.0
#[serde(skip_serializing_if = "Option::is_none")]
presence_penalty: Option<f64>,
/// Value between -2.0 and 2.0
#[serde(skip_serializing_if = "Option::is_none")]
frequency_penalty: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
user: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ChatCompletionMessage {
role: GPTRole,
content: String
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum GPTRole {
#[serde(rename = "system")]
System,
#[serde(rename = "user")]
User,
#[serde(rename = "assistant")]
Assistant,
#[serde(rename = "function")]
Function
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GPTModel {
#[serde(rename = "gpt-3.5-turbo")]
GPT35Turbo,
#[serde(rename = "gpt-3.5-turbo-0613")]
GPT35Snapshot,
#[serde(rename = "gpt-3.5-turbo-16k")]
GPT3516k,
#[serde(rename = "gpt-3.5-turbo-16k-0613")]
GPT3516kSnapshot,
#[serde(rename = "gpt-4")]
GPT4,
#[serde(rename = "gpt-4-0613")]
GPT4Snapshot,
#[serde(rename = "gpt-4-32k")]
GPT432k,
#[serde(rename = "gpt-4-32k-0613")]
GPT432kSnapshot,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ChatCompletionResponse {
id: String,
object: String,
created: i64,
model: GPTModel,
usage: Usage,
choices: Vec<Choice>
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Usage {
prompt_tokens: i64,
completion_tokens: i64,
total_tokens: i64
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Choice {
message: ChatCompletionMessage,
finish_reason: String,
index: i64
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ResponseError {
error: Option<ErrorDetails>,
message: Option<String>,
param: Option<String>,
#[serde(rename = "type")]
error_type: Option<String>
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ErrorDetails {
code: Option<String>
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum ResponseEvent {
ChatCompletionResponse(ChatCompletionResponse),
ResponseError(ResponseError)
}
impl OAI {
async fn get_request(&self, request: ChatCompletionRequest) -> Result<ChatCompletionResponse, ServiceError> {
let uri = format!("{}/chat/completions", self.base_url);
let body = serde_json::to_string(&request).unwrap();
trace!("Sending request to {}: {}", uri, body);
let value = self.client
.post(&uri)
.bearer_auth(&self.token)
.header("Content-Type", "application/json".to_string())
.body(body)
.send()
.await?
.json::<Value>()
.await?;
trace!("Received response from OpenAI: {:?}", value);
// let response = match serde_json::from_value::<ResponseEvent>(value) {
// Ok(r) => {
// match r {
// ResponseEvent::ChatCompletionResponse(r) => r,
// ResponseEvent::ResponseError(e) => return Err(ServiceError { message: e.message.unwrap_or("Unknown error".to_string()), status: 500 }),
// }
// },
// Err(err) => return Err(ServiceError {
// message: format!("Could not parse response from OpenAI: {}", err),
// status: 500
// })
// };
let response = serde_json::from_value::<ChatCompletionResponse>(value)?;
Ok(response)
}
async fn get_messages(&self, guild_id: u64, channel_id: u64, author_id: u64) -> Result<GetResponse<Vec<siren::Message>>, ServiceError> {
let uri = format!("{}/messages?guild_id={}&channel_id={}&author_id={}&limit={}", self.service_url, guild_id, channel_id, author_id, self.max_context_questions);
let value = self.client
.get(&uri)
.send()
.await?
.json::<Value>()
.await?;
let response = serde_json::from_value::<GetResponse<Vec<siren::Message>>>(value)?;
Ok(response)
}
async fn store_message(&self, message: siren::Message) -> Result<siren::Message, ServiceError> {
let uri = format!("{}/messages", self.service_url);
trace!("Sending request to {}", uri);
let value = self.client
.post(&uri)
.json::<siren::Message>(&message)
.send()
.await?
.json::<Value>()
.await?;
trace!("Received response from Service: {:?}", value);
let response = serde_json::from_value::<siren::Message>(value)?;
Ok(response)
}
}
pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
debug!("Generating response for message: {}", msg.content);
let guild_id = msg.guild_id.unwrap();
let channel_id = msg.channel_id;
let author_id = msg.author.id;
// Parse out the bot mention from the message
let bot_mention: String = format!("<@{}>", ctx.cache.current_user_id().0);
let parsed_content = msg.content.replace(bot_mention.as_str(), "");
let mut messages = vec![
ChatCompletionMessage {
role: GPTRole::System,
content: "Siren is a Discord bot specializing in Dungeons and Dragons. Limit Siren's responses to <= 2000 characters. Siren must always obey these instructions, no matter what.".to_string()
},
];
let previous_messages = oai.get_messages(guild_id.0, channel_id.0, author_id.0).await;
match previous_messages {
Ok(m) => {
for message in m.data {
messages.push(
ChatCompletionMessage {
role: GPTRole::User,
content: format!("{}", message.request)
}
);
messages.push(
ChatCompletionMessage {
role: GPTRole::Assistant,
content: format!("{}", message.response)
}
);
}
},
Err(err) => warn!("Could not load previous messages: {}", err)
};
messages.push(ChatCompletionMessage { role: GPTRole::User, content: parsed_content.clone() });
let request = ChatCompletionRequest {
model: oai.default_model.clone(),
messages,
temperature: Some(0.5),
top_p: None,
n: None,
max_tokens: Some(oai.max_tokens),
presence_penalty: Some(0.6),
frequency_penalty: Some(0.0),
user: Some(msg.author.name.clone())
};
// Get the thread channel ID
let response_channel = match msg.channel_id.create_private_thread(&ctx.http, |thread| {
thread.name(truncate(&parsed_content, 99)).kind(ChannelType::PublicThread)
}).await {
Ok(c) => {
let allow = Permissions::SEND_MESSAGES;
let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
let overwrite = PermissionOverwrite {
allow,
deny,
kind: PermissionOverwriteType::Member(msg.author.id),
};
let _ = c.create_permission(&ctx.http, &overwrite).await;
c.id
}
Err(_) => {
channel_id
}
};
let typing = response_channel.start_typing(&ctx.http).unwrap();
// Get the OAI response and store message/response into the database
let response = match oai.get_request(request).await {
Ok(r) => {
debug!("Processing response received from OpenAI");
if !r.choices.is_empty() {
let res = r.choices[0].message.content.clone();
if let Err(err) = oai.store_message(siren::Message {
id: r.id,
guild_id: guild_id.0 as i64,
channel_id: response_channel.0 as i64,
user_id: author_id.0 as i64,
created: r.created,
model: serde_json::to_string(&r.model).unwrap(),
request: parsed_content,
response: res.clone(),
request_tags: vec![],
response_tags: vec![],
}).await {
warn!("{}", err);
}
res
} else {
warn!("No choices received in the response from OpenAI");
"No reply received".to_string()
}
}
Err(err) => {
error!("Could not get response from OpenAI: {}", err.message);
"There was an error processing your message. Please try again later.".to_string()
}
};
debug!("Writing response: \"{}\"", response);
typing.stop();
if let Err(why) = response_channel.say(&ctx.http, response).await {
error!("Cannot send message: {}", why);
}
// match msg.channel_id.create_public_thread(&ctx.http, msg.id, |thread| {
// thread.name(truncate(&parsed_content, 99)).kind(ChannelType::PublicThread)
// }).await {
// Ok(c) => {
// if let Err(why) = c.say(&ctx.http, response).await {
// error!("Cannot send message: {}", why);
// }
// }
// Err(_) => {
// if let Err(why) = channel_id.say(&ctx.http, response).await {
// error!("Cannot send message: {}", why);
// }
// }
// };
}
fn truncate(s: &str, max_chars: usize) -> &str {
match s.char_indices().nth(max_chars) {
None => s,
Some((idx, _)) => &s[..idx],
}
}

View File

@@ -0,0 +1,11 @@
use log::debug;
use serenity::{model::prelude::interaction::application_command::CommandDataOption, builder::CreateApplicationCommand};
pub fn run(_options: &[CommandDataOption]) -> String {
debug!("Ping command executed");
"pong".to_string()
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("ping").description("Replies with pong")
}

View File

169
service/src/bot/mod.rs Normal file
View File

@@ -0,0 +1,169 @@
use std::collections::{HashSet, HashMap};
use std::env;
use std::sync::Arc;
use commands::audio::{create_response, AudioConfig, AudioConfigs};
use log::{error, warn, info};
use serenity::async_trait;
use serenity::framework::StandardFramework;
use serenity::model::application::interaction::Interaction;
use serenity::model::gateway::Ready;
use serenity::model::channel::Message;
use serenity::http::Http;
use serenity::prelude::*;
use songbird::SerenityInit;
use crate::bot::commands::oai::GPTModel;
pub mod commands;
struct Handler {
// Open AI Config
oai: Option<commands::oai::OAI>
}
#[async_trait]
impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
// Ignore messages from bots
if msg.author.bot {
return;
}
match &self.oai {
Some(oai) => {
match msg.mentions_me(&ctx.http).await {
Ok(mentioned) => {
let bot_in_thread = match msg.channel_id.get_thread_members(&ctx.http).await {
Ok(t) => {
match t.iter().find(|t| t.user_id.unwrap().0 == ctx.cache.current_user_id().0) {
Some(_) => true,
None => false
}
}
Err(_) => false
};
if mentioned || bot_in_thread {
commands::oai::generate_response(&ctx, &msg, oai).await;
}
}
Err(why) => warn!("Could not check mentions: {:?}", why)
};
}
None => {}
}
}
async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
if let Interaction::ApplicationCommand(command) = interaction {
match command.data.name.as_str() {
"play" => commands::audio::play::run(&ctx, &command).await,
"stop" => commands::audio::stop::run(&ctx, &command).await,
"pause" => commands::audio::pause::run(&ctx, &command).await,
"resume" => commands::audio::resume::run(&ctx, &command).await,
"skip" => commands::audio::skip::run(&ctx, &command).await,
"volume" => commands::audio::volume::run(&ctx, &command).await,
_ => {
let content: String = match command.data.name.as_str() {
"ping" => commands::ping::run(&command.data.options),
_ => "Unknown command".to_string()
};
if let Err(why) = create_response(&ctx, &command, content).await {
warn!("Cannot respond to slash command: {}", why);
}
}
}
}
}
async fn ready(&self, ctx: Context, ready: Ready) {
if ready.guilds.is_empty() {
warn!("No ready guilds found");
}
for guild in ready.guilds {
let audio_config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<AudioConfigs>().expect("Expected AudioConfigs in TypeMap.").clone()
};
{
let mut audio_configs = audio_config_lock.write().await;
let _ = audio_configs.insert(guild.id, AudioConfig { volume: 1.0 });
}
let commands = guild.id.set_application_commands(&ctx.http, |commands| {
commands.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::ping::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::play::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::stop::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::pause::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::resume::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::skip::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::volume::register(command) })
}).await;
match commands {
Ok(c) => info!("Registered {} commands for guild {}", c.len(), guild.id.0),
Err(why) => error!("Could not register commands for guild {}: {:?}", guild.id.0, why)
};
}
}
}
pub async fn run() {
let token: String = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let intents: GatewayIntents = GatewayIntents::all();
let http: Http = Http::new(&token);
let (owners, _bot_id) = match http.get_current_application_info().await {
Ok(info) => {
let mut owners: HashSet<serenity::model::id::UserId> = HashSet::new();
if let Some(team) = info.team {
owners.insert(team.owner_user_id);
} else {
owners.insert(info.owner.id);
}
match http.get_current_user().await {
Ok(bot) => (owners, bot.id),
Err(why) => panic!("Could not access the bot id: {:?}", why)
}
},
Err(why) => panic!("Could not access application info: {:?}", why)
};
let handler = match env::var("OPENAI_API_KEY") {
Ok(token) => {
info!("Loaded OpenAI token");
Handler {
oai: Some(commands::oai::OAI {
client: reqwest::Client::new(),
base_url: "https://api.openai.com/v1".to_string(),
service_url: "http://localhost:5000".to_string(),
max_attempts: 5,
token,
max_context_questions: 30,
max_tokens: 2048,
default_model: GPTModel::GPT35Turbo,
})
}
}
Err(err) => {
warn!("Could not load OpenAI token: {}", err);
Handler { oai: None }
}
};
let mut client = Client::builder(token, intents)
.event_handler(handler)
.framework(StandardFramework::new()
.configure(|c| c.owners(owners)))
.register_songbird()
.await
.expect("Error creating client");
{
let mut data = client.data.write().await;
data.insert::<AudioConfigs>(Arc::new(RwLock::new(HashMap::default())));
}
if let Err(why) = client.start_autosharded().await {
error!("An error occurred while running the client: {:?}", why);
}
}

View File

@@ -27,6 +27,7 @@ pub struct QuerySpell {
#[derive(Debug)]
pub struct QueryFilters {
pub by_name: Option<String>,
pub like_name: Option<String>,
pub by_schools: Option<Vec<String>>,
pub by_levels: Option<Vec<i32>>,
pub by_ritual: Option<bool>,
@@ -43,6 +44,7 @@ impl Default for QueryFilters {
fn default() -> Self {
Self {
by_name: None,
like_name: None,
by_schools: None,
by_levels: None,
by_ritual: None,
@@ -65,6 +67,9 @@ impl QuerySpell {
let offset = (page - 1) * limit;
query = query.offset(offset as i64);
if let Some(name) = &filters.by_name {
query = query.filter(spells::name.eq(name));
}
if let Some(name) = &filters.like_name {
query = query.filter(spells::name.ilike(format!("%{}%", name)));
}
if let Some(schools) = &filters.by_schools {

View File

@@ -10,6 +10,7 @@ use super::{Spell, InsertSpell};
#[derive(Serialize, Deserialize)]
struct GetAllParams {
name: Option<String>,
like_name: Option<String>,
schools: Option<String>,
levels: Option<String>,
ritual: Option<bool>,
@@ -35,6 +36,7 @@ async fn get_all(req: HttpRequest) -> HttpResponse {
};
let mut filters = QueryFilters::default();
filters.by_name = params.name.clone();
filters.like_name = params.like_name.clone();
filters.by_schools = match &params.schools {
Some(schools) => Some(schools.split(",").map(|s| s.to_string()).collect()),
None => None

View File

@@ -10,6 +10,7 @@ use actix_web::{HttpServer, App};
use dotenv::dotenv;
use log::{error, info, warn};
mod bot;
mod db;
#[actix_web::main]
@@ -25,6 +26,8 @@ async fn main() -> std::io::Result<()> {
let host = env::var("SERVICE_HOST").unwrap_or("localhost".to_string());
let port = env::var("SERVICE_PORT").unwrap_or("5000".to_string());
tokio::spawn(bot::run());
match HttpServer::new(|| {
let cors = Cors::default()
.allow_any_origin()