Stripped out ui/api

This commit is contained in:
Benjamin Sherriff
2024-09-03 22:32:43 -04:00
committed by Benjamin Sherriff
parent c83d398ce0
commit 96fe3fc0e5
152 changed files with 110 additions and 10056 deletions

View File

@@ -0,0 +1,212 @@
use std::sync::Arc;
use log::{debug, warn};
use reqwest::Url;
use serenity::client::Cache;
use serenity::model::application::interaction::{
InteractionResponseType, application_command::ApplicationCommandInteraction,
};
use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User;
use serenity::prelude::*;
use siren::ServiceError;
use songbird::{Call, Songbird};
use songbird::input::{Restartable, Input, Metadata, error::Error as SongbirdError};
use crate::bot::ytdlp::{PlaylistItem, YtDlp};
pub mod pause;
pub mod play;
pub mod resume;
pub mod skip;
pub mod stop;
pub mod volume;
pub async fn join_by_user(
cache: &Arc<Cache>,
manager: Arc<Songbird>,
guild_id_option: &Option<GuildId>,
user: &User,
) -> Result<(), ServiceError> {
let guild_id = match guild_id_option {
Some(g) => g,
None => {
return Err(ServiceError {
status: 422,
message: format!("{}", "No guild ID set"),
})
}
};
let channel_id = match find_voice_channel(cache, &guild_id, &user) {
Ok(channel) => channel,
Err(err) => {
return Err(ServiceError {
status: 500,
message: err.to_string(),
})
}
};
join(manager, guild_id, &channel_id).await
}
pub async fn join(
manager: Arc<Songbird>,
guild_id: &GuildId,
channel_id: &ChannelId,
) -> Result<(), ServiceError> {
debug!("<{}> Joining channel {}", guild_id.0, channel_id.0);
let (_handle_lock, success) = manager
.join(guild_id.to_owned(), channel_id.to_owned())
.await;
match success {
Ok(s) => Ok(s),
Err(err) => {
warn!("Failed to join channel: {:?}", err);
Err(ServiceError {
status: 500,
message: err.to_string(),
})
}
}
}
pub async fn leave(
manager: Arc<Songbird>,
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"));
}
};
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(())
}
fn find_voice_channel(
cache: &Arc<Cache>,
guild_id: &GuildId,
user: &User,
) -> Result<ChannelId, String> {
let guild = match guild_id.to_guild_cached(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")),
}
}
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
}
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
}
pub async fn add_song(
call: Arc<Mutex<Call>>,
url: &str,
lazy: bool,
volume: Option<f32>,
) -> Result<Metadata, SongbirdError> {
let source = Restartable::ytdl(url.to_owned(), 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(volume) = volume {
let _ = track_handle.set_volume(volume);
}
Ok(metadata)
}
pub fn get_playlist_urls(url: &str) -> Result<Vec<PlaylistItem>, ServiceError> {
let output = YtDlp::new()
.arg("--flat-playlist")
.arg("--dump-json")
.arg(url)
.execute()?;
let items: Vec<PlaylistItem> = String::from_utf8(output.stdout)?
.split('\n')
.filter_map(|line| {
if line.is_empty() {
None
} else {
Some(
serde_json::from_slice::<PlaylistItem>(line.as_bytes()).map_err(|err| ServiceError {
status: 500,
message: err.to_string(),
}),
)
}
})
.filter_map(|parsed| match parsed {
Ok(item) => Some(item),
Err(err) => {
warn!("Failed to parse playlist item: {}", err);
None
}
})
.collect();
Ok(items)
}
fn is_valid_url(url: &str) -> (bool, bool) {
Url::parse(url).ok().map_or((false, false), |valid_url| {
let is_playlist: bool = valid_url
.query_pairs()
.find(|(key, _)| key == "list")
.map_or(false, |_| true);
(true, is_playlist)
})
}
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,45 @@
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,220 @@
use std::sync::Arc;
use log::{debug, warn, error};
use serenity::model::prelude::GuildId;
use serenity::{prelude::*, async_trait};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use siren::ServiceError;
use songbird::{EventHandler, Songbird};
use crate::bot::guilds::QueryGuild;
use crate::bot::ytdlp::PlaylistItem;
use crate::bot::{
commands::audio::{leave, get_playlist_urls, add_song, get_songbird},
};
use super::{create_response, edit_response, is_valid_url, join_by_user};
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;
}
let manager = get_songbird(ctx).await;
match join_by_user(&ctx.cache, manager, &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;
match play_track(manager, guild_id, track_url).await {
Ok(count) => {
let mut message = format!("Playing {} tracks", count);
if count == 0 {
message = "No tracks were played".to_string();
} else if count == 1 {
message = "Playing 1 track".to_string();
}
if let Err(why) = edit_response(&ctx, &command, message).await {
error!("Failed to edit response message: {}", why);
}
}
Err(err) => {
warn!("Failed to play track: {}", err);
if let Err(why) =
edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await
{
error!("Failed to edit response message: {}", why);
}
}
};
}
Err(err) => {
warn!("{}", err);
if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await {
error!("Failed to edit response message: {}", why);
}
}
}
}
pub async fn play_track(
manager: Arc<Songbird>,
guild_id: GuildId,
track_url: String,
) -> Result<i32, ServiceError> {
let mut track_count = 0;
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 guild = QueryGuild::get(guild_id.0 as i64)?;
let valid = is_valid_url(&track_url);
if !valid.0 {
warn!("Invalid track url: {}", track_url);
return Err(ServiceError {
status: 422,
message: format!("Invalid track url: {}", track_url),
});
}
let mut playlist_items: Vec<PlaylistItem> = Vec::new();
if valid.1 {
playlist_items = match get_playlist_urls(&track_url) {
Ok(items) => items,
Err(err) => {
warn!("Failed to get playlist urls: {}", err);
return Err(ServiceError {
status: 422,
message: err.to_string(),
});
}
};
} else {
let playlist_item = PlaylistItem {
id: "".to_string(),
url: track_url,
title: "".to_string(),
duration: 0,
playlist_index: 0,
};
playlist_items.push(playlist_item);
}
for item in playlist_items {
match add_song(
handler_lock.clone(),
&item.url,
is_queue_empty,
Some(guild.volume as f32 / 100.0),
)
.await
{
Ok(added_song) => {
let track_title = added_song.title.unwrap();
debug!("Added track: {}", track_title);
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.clone(),
},
);
track_count += 1;
}
Err(err) => {
warn!("Failed to add song: {}", err);
if let Err(why) = leave(manager, &Some(guild_id)).await {
error!("Failed to leave voice channel: {}", why);
}
return Err(ServiceError {
status: 422,
message: err.to_string(),
});
}
}
}
}
Ok(track_count)
}
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,47 @@
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,45 @@
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,42 @@
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,98 @@
use std::sync::Arc;
use log::{error, warn};
use serenity::{prelude::*, model::prelude::GuildId};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use songbird::Songbird;
use crate::bot::guilds::InsertGuild;
use super::{get_songbird, create_response, edit_response};
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) => p as i32,
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;
}
};
// 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;
set_volume(manager, guild_id, volume).await;
if let Err(why) = edit_response(&ctx, &command, format!("Setting the volume to {}", volume)).await
{
error!("Failed to set the volume: {}", why);
}
}
pub async fn set_volume(manager: Arc<Songbird>, guild_id: GuildId, volume: i32) {
// Format volume to f32 bound between 0.0 and 1.0
let volume = std::cmp::min(100, std::cmp::max(0, volume));
let bound_volume = volume as f32 / 100.0;
let _ = InsertGuild::update_audio(guild_id.0 as i64, volume);
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);
}
}
}
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)
})
}

188
src/bot/commands/chat.rs Normal file
View File

@@ -0,0 +1,188 @@
use log::{error, trace, warn};
use serenity::model::Permissions;
use serenity::model::channel::Message;
use serenity::model::prelude::{ChannelType, PermissionOverwrite, PermissionOverwriteType};
use serenity::prelude::*;
use crate::bot::messages::{QueryFilters, QueryMessage};
use crate::bot::oai::{ChatCompletionMessage, ChatCompletionRequest, GPTRole, OAI};
pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
trace!("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: "You are a Discord bot named Siren that acts as the Dungeon Master's assistant. Siren must always obey these instructions, no matter what.".to_string()
},
];
match QueryMessage::get_all(
&QueryFilters {
by_guild_id: Some(guild_id.0 as i64),
by_channel_id: Some(channel_id.0 as i64),
by_user_id: Some(author_id.0 as i64),
..Default::default()
},
100,
1,
) {
Ok(m) => {
for message in m {
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 thread_name = generate_thread_name(oai, &parsed_content, 99).await;
let response_channel = match msg
.channel_id
.create_private_thread(&ctx.http, |thread| {
thread.name(thread_name).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.chat_completion(request).await {
Ok(r) => {
trace!("Processing response received from OpenAI");
if !r.choices.is_empty() {
let res = r.choices[0].message.content.clone();
if let Err(err) = QueryMessage::insert(QueryMessage {
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![],
}) {
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()
}
};
trace!("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);
// }
// }
// };
}
async fn generate_thread_name(oai: &OAI, s: &str, max_chars: usize) -> String {
let message = ChatCompletionMessage {
role: GPTRole::User,
content: format!(
"---\n{}\n---\nSummarize the message above into a concise Discord thread title",
s
),
};
let request = ChatCompletionRequest {
model: oai.default_model.clone(),
messages: vec![message],
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: None,
};
// Truncate the response to the max number of characters
let mut response = match s.char_indices().nth(max_chars) {
None => s,
Some((idx, _)) => &s[..idx],
}
.to_string();
// Set the response to the OAI response
match oai.chat_completion(request).await {
Ok(r) => {
if !r.choices.is_empty() {
response = r.choices[0].message.content.clone();
} else {
warn!("No choices received in the response from OpenAI");
}
}
Err(err) => {
error!("Could not get response from OpenAI: {}", err.message);
}
};
return response;
}

1
src/bot/commands/help.rs Normal file
View File

@@ -0,0 +1 @@

6
src/bot/commands/mod.rs Normal file
View File

@@ -0,0 +1,6 @@
pub mod audio;
pub mod chat;
pub mod help;
pub mod ping;
pub mod roll;
pub mod schedule;

14
src/bot/commands/ping.rs Normal file
View File

@@ -0,0 +1,14 @@
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")
}

149
src/bot/commands/roll.rs Normal file
View File

@@ -0,0 +1,149 @@
use log::{error, warn};
use rand::Rng;
use serenity::{
builder::CreateApplicationCommand,
client::Context,
model::application::{
command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction,
},
};
use crate::bot::commands::audio::edit_response;
use super::audio::create_response;
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
if let Err(why) = create_response(&ctx, &command, format!("Processing command...")).await {
error!("Failed to create response message: {}", why);
return;
}
let dice_string: String = match command.data.options.get(0) {
Some(o) => match &o.value {
Some(v) => match v.as_str() {
Some(s) => s.split_whitespace().collect::<String>(),
None => {
warn!("Missing dice option");
if let Err(why) = edit_response(&ctx, &command, format!("Dice option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
},
None => {
warn!("Missing dice option");
if let Err(why) = edit_response(&ctx, &command, format!("Dice option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
},
None => {
warn!("Missing dice option");
if let Err(why) = edit_response(&ctx, &command, format!("Dice option is missing")).await {
error!("Failed to create response message: {}", why);
}
return;
}
};
let dice = parse_dice(dice_string.as_str());
match dice {
Ok((count, sides, modifier)) => {
let mut rolls = Vec::new();
let mut total = 0;
for _ in 0..count {
let roll = rand::thread_rng().gen_range(1..=sides);
total += roll;
rolls.push(roll);
}
let response = format!(
"{}d{}{} = {}",
count,
sides,
if modifier > 0 {
format!("+{}", modifier)
} else if modifier < 0 {
format!("-{}", modifier)
} else {
"".to_string()
},
total + (modifier as u32)
);
if let Err(why) = edit_response(&ctx, &command, response).await {
error!("Failed to create response message: {}", why);
}
}
Err(why) => {
if let Err(why) = edit_response(&ctx, &command, format!("Invalid dice string: {}", why)).await
{
error!("Failed to create response message: {}", why);
}
}
}
}
fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
let mut parts = dice.split("d");
let count = match parts.next() {
Some(c) => match c.parse::<u32>() {
Ok(n) => n,
Err(_) => return Err(format!("Invalid dice count: {}", c)),
},
None => return Err(format!("Invalid dice string: {}", dice)),
};
let mut positive_modifier = true;
let mut parts = match parts.next() {
Some(p) => {
// Check if contains a +/- modifier
if p.contains("+") {
positive_modifier = true;
p.split("+")
} else if p.contains("-") {
positive_modifier = false;
p.split("-")
} else {
p.split("+")
}
}
None => return Err(format!("Invalid dice string: {}", dice)),
};
let sides = match parts.next() {
Some(s) => match s.parse::<u32>() {
Ok(n) => {
if n == 4 || n == 6 || n == 8 || n == 10 || n == 12 || n == 20 || n == 100 {
n
} else {
return Err(format!("Invalid dice sides: {}", s));
}
}
Err(_) => return Err(format!("Invalid dice sides: {}", s)),
},
None => return Err(format!("Invalid dice string: {}", dice)),
};
let modifier = match parts.next() {
Some(m) => match m.parse::<i32>() {
Ok(n) => {
if positive_modifier {
n
} else {
n * -1
}
}
Err(_) => return Err(format!("Invalid dice modifier: {}", m)),
},
None => 0,
};
Ok((count, sides, modifier))
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command
.name("roll")
.description("Rolls D&D dice")
.create_option(|option| {
option
.name("dice")
.description("Dice to roll")
.kind(CommandOptionType::String)
.required(true)
})
}

View File

@@ -0,0 +1 @@

3
src/bot/guilds/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
mod model;
pub use model::*;

47
src/bot/guilds/model.rs Normal file
View File

@@ -0,0 +1,47 @@
use diesel::prelude::*;
use serde::{Serialize, Deserialize};
use siren::ServiceError;
use crate::storage::{schema::guilds, connection};
#[derive(Queryable, QueryableByName, Serialize, Deserialize)]
#[diesel(table_name = guilds)]
pub struct QueryGuild {
pub id: i64,
pub bot_id: i64,
pub volume: i32,
}
impl QueryGuild {
pub fn get(id: i64) -> Result<Self, ServiceError> {
let mut conn = connection()?;
let guild = guilds::table.filter(guilds::id.eq(id)).first(&mut conn)?;
Ok(guild)
}
}
#[derive(Insertable, AsChangeset, Serialize, Deserialize)]
#[diesel(table_name = guilds)]
pub struct InsertGuild {
pub id: i64,
pub bot_id: i64,
pub volume: i32,
}
impl InsertGuild {
pub fn insert(guild: Self) -> Result<QueryGuild, ServiceError> {
let mut conn = connection()?;
let guild = diesel::insert_into(guilds::table)
.values(guild)
.get_result(&mut conn)?;
Ok(guild)
}
pub fn update_audio(id: i64, volume: i32) -> Result<QueryGuild, ServiceError> {
let mut conn = connection()?;
let guild = diesel::update(guilds::table.filter(guilds::id.eq(id)))
.set(guilds::volume.eq(volume))
.get_result(&mut conn)?;
Ok(guild)
}
}

134
src/bot/handler.rs Normal file
View File

@@ -0,0 +1,134 @@
use log::{warn, info, error};
use serenity::async_trait;
use serenity::model::application::interaction::Interaction;
use serenity::model::gateway::Ready;
use serenity::model::channel::Message;
use serenity::prelude::*;
use super::{commands, oai};
use super::commands::audio::create_response;
pub struct Handler {
// Open AI Config
pub oai: Option<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::chat::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() {
"roll" => commands::roll::run(&ctx, &command).await,
"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 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::roll::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
),
};
}
}
}

3
src/bot/messages/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
mod model;
pub use model::*;

139
src/bot/messages/model.rs Normal file
View File

@@ -0,0 +1,139 @@
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use siren::ServiceError;
use crate::storage::{
schema::messages::{self},
connection,
};
#[derive(Queryable, Selectable, Insertable, AsChangeset, Serialize, Deserialize)]
#[diesel(table_name = messages)]
pub struct QueryMessage {
pub id: String,
pub guild_id: i64,
pub channel_id: i64,
pub user_id: i64,
pub created: i64,
pub model: String,
pub request: String,
pub response: String,
pub request_tags: Vec<String>,
pub response_tags: Vec<String>,
}
pub struct QueryFilters {
pub by_id: Option<String>,
pub by_guild_id: Option<i64>,
pub by_channel_id: Option<i64>,
pub by_user_id: Option<i64>,
pub by_model: Option<String>,
pub by_request: Option<String>,
pub by_response: Option<String>,
pub by_request_tags: Option<Vec<String>>,
pub by_response_tags: Option<Vec<String>>,
}
impl Default for QueryFilters {
fn default() -> Self {
QueryFilters {
by_id: None,
by_guild_id: None,
by_channel_id: None,
by_user_id: None,
by_model: None,
by_request: None,
by_response: None,
by_request_tags: None,
by_response_tags: None,
}
}
}
impl QueryMessage {
pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> {
let mut conn = connection()?;
let mut query = messages::table
.limit(limit as i64)
.order(messages::created.asc())
.into_boxed();
// Limit query to page and limit
let offset = (page - 1) * limit;
query = query.offset(offset as i64);
// Apply filters
if let Some(id) = &filters.by_id {
query = query.filter(messages::id.eq(id));
}
if let Some(guild_id) = &filters.by_guild_id {
query = query.filter(messages::guild_id.eq(guild_id));
}
if let Some(channel_id) = &filters.by_channel_id {
query = query.filter(messages::channel_id.eq(channel_id));
}
if let Some(user_id) = &filters.by_user_id {
query = query.filter(messages::user_id.eq(user_id));
}
if let Some(model) = &filters.by_model {
query = query.filter(messages::model.eq(model));
}
if let Some(request) = &filters.by_request {
query = query.filter(messages::request.eq(request));
}
if let Some(response) = &filters.by_response {
query = query.filter(messages::response.eq(response));
}
if let Some(request_tags) = &filters.by_request_tags {
query = query.filter(messages::request_tags.eq(request_tags));
}
if let Some(response_tags) = &filters.by_response_tags {
query = query.filter(messages::response_tags.eq(response_tags));
}
// Execute query
let messages = query.load::<Self>(&mut conn)?;
Ok(messages)
}
pub fn get_count(fitlers: &QueryFilters) -> Result<i64, ServiceError> {
let mut conn = connection()?;
let mut query = messages::table.into_boxed();
// Apply filters
if let Some(id) = &fitlers.by_id {
query = query.filter(messages::id.eq(id));
}
if let Some(guild_id) = &fitlers.by_guild_id {
query = query.filter(messages::guild_id.eq(guild_id));
}
if let Some(channel_id) = &fitlers.by_channel_id {
query = query.filter(messages::channel_id.eq(channel_id));
}
if let Some(user_id) = &fitlers.by_user_id {
query = query.filter(messages::user_id.eq(user_id));
}
if let Some(model) = &fitlers.by_model {
query = query.filter(messages::model.eq(model));
}
if let Some(request) = &fitlers.by_request {
query = query.filter(messages::request.eq(request));
}
if let Some(response) = &fitlers.by_response {
query = query.filter(messages::response.eq(response));
}
if let Some(request_tags) = &fitlers.by_request_tags {
query = query.filter(messages::request_tags.eq(request_tags));
}
if let Some(response_tags) = &fitlers.by_response_tags {
query = query.filter(messages::response_tags.eq(response_tags));
}
// Execute query
let count = query.count().get_result::<i64>(&mut conn)?;
Ok(count)
}
pub fn insert(message: Self) -> Result<QueryMessage, ServiceError> {
let mut conn = connection()?;
let message = diesel::insert_into(messages::table)
.values(message)
.get_result(&mut conn)?;
Ok(message)
}
}

6
src/bot/mod.rs Normal file
View File

@@ -0,0 +1,6 @@
pub mod commands;
pub mod guilds;
pub mod handler;
pub mod messages;
pub mod oai;
pub mod ytdlp;

3
src/bot/oai/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
mod model;
pub use model::*;

160
src/bot/oai/model.rs Normal file
View File

@@ -0,0 +1,160 @@
use serde::{Serialize, Deserialize};
use serde_json::Value;
use siren::ServiceError;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GPTRole {
#[serde(rename = "system")]
System,
#[serde(rename = "user")]
User,
#[serde(rename = "assistant")]
Assistant,
#[serde(rename = "function")]
Function,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionRequest {
pub model: String,
pub messages: Vec<ChatCompletionMessage>,
/// Value between 0 and 2
#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
/// Value between 0 and 1
#[serde(skip_serializing_if = "Option::is_none")]
pub top_p: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub n: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_tokens: Option<i64>,
/// Value between -2.0 and 2.0
#[serde(skip_serializing_if = "Option::is_none")]
pub presence_penalty: Option<f64>,
/// Value between -2.0 and 2.0
#[serde(skip_serializing_if = "Option::is_none")]
pub frequency_penalty: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionMessage {
pub role: GPTRole,
pub content: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionResponse {
pub id: String,
pub object: String,
pub system_fingerprint: Option<String>,
pub created: i64,
pub model: String,
pub usage: Usage,
pub choices: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
pub prompt_tokens: i64,
pub completion_tokens: i64,
pub total_tokens: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Choice {
pub message: ChatCompletionMessage,
pub finish_reason: String,
pub index: i64,
pub logprobs: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
enum ResponseEvent {
ChatCompletionResponse(ChatCompletionResponse),
ResponseError(ResponseError),
// ChatCompletionResponse {
// id: String,
// object: String,
// system_fingerprint: Option<String>,
// created: i64,
// model: String,
// usage: Usage,
// choices: Vec<Choice>,
// },
// ResponseError {
// error: Option<ErrorDetails>,
// message: Option<String>,
// param: Option<String>,
// #[serde(rename = "type")]
// error_type: Option<String>,
// },
}
#[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>,
message: Option<String>,
}
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: String,
pub max_context_questions: i64,
}
impl OAI {
pub async fn chat_completion(
&self,
request: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, ServiceError> {
let url = format!("{}/chat/completions", self.base_url);
let response = self
.client
.post(&url)
.bearer_auth(&self.token)
.header("Content-Type", "application/json".to_string())
.json(&request)
.send()
.await;
match response {
Ok(response) => {
let value = response.json::<Value>().await?;
let event: ResponseEvent = serde_json::from_value::<ResponseEvent>(value)?;
match event {
ResponseEvent::ChatCompletionResponse(response) => {
return Ok(response);
},
ResponseEvent::ResponseError(error) => {
return Err(ServiceError {
status: 500,
message: format!("Error: {}", error.message.unwrap()),
});
},
}
}
Err(err) => {
return Err(ServiceError {
status: 500,
message: format!("Error: {}", err),
})
}
}
}
}

40
src/bot/ytdlp/mod.rs Normal file
View File

@@ -0,0 +1,40 @@
mod model;
use std::process::{Child, Command, Output, Stdio};
pub use model::*;
const YOUTUBE_DL_COMMAND: &str = "yt-dlp";
pub struct YtDlp {
command: Command,
args: Vec<String>,
}
impl YtDlp {
pub fn new() -> Self {
let mut cmd = Command::new(YOUTUBE_DL_COMMAND);
cmd
.env("LC_ALL", "en_US.UTF-8")
.stdout(Stdio::piped())
.stdin(Stdio::piped())
.stderr(Stdio::piped());
Self {
command: cmd,
args: Vec::new(),
}
}
pub fn arg(&mut self, arg: &str) -> &mut Self {
self.args.push(arg.to_owned());
self
}
pub fn execute(&mut self) -> std::io::Result<Output> {
self
.command
.args(self.args.clone())
.spawn()
.and_then(Child::wait_with_output)
}
}

10
src/bot/ytdlp/model.rs Normal file
View File

@@ -0,0 +1,10 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct PlaylistItem {
pub id: String,
pub url: String,
pub title: String,
pub duration: i32,
pub playlist_index: i32,
}

View File

@@ -0,0 +1 @@

1
src/dnd/bestiary/mod.rs Normal file
View File

@@ -0,0 +1 @@

0
src/dnd/campaigns/mod.rs Normal file
View File

View File

3
src/dnd/classes/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
mod model;
pub use model::*;

46
src/dnd/classes/model.rs Normal file
View File

@@ -0,0 +1,46 @@
use std::str::FromStr;
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize)]
pub enum AbilityType {
#[serde(rename = "strength")]
Strength,
#[serde(rename = "dexterity")]
Dexterity,
#[serde(rename = "constitution")]
Constitution,
#[serde(rename = "intelligence")]
Intelligence,
#[serde(rename = "wisdom")]
Wisdom,
#[serde(rename = "charisma")]
Charisma,
}
impl AbilityType {
pub fn to_string(&self) -> String {
match self {
AbilityType::Strength => "Strength".to_string(),
AbilityType::Dexterity => "Dexterity".to_string(),
AbilityType::Constitution => "Constitution".to_string(),
AbilityType::Intelligence => "Intelligence".to_string(),
AbilityType::Wisdom => "Wisdom".to_string(),
AbilityType::Charisma => "Charisma".to_string(),
}
}
}
impl FromStr for AbilityType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Strength" => Ok(AbilityType::Strength),
"Dexterity" => Ok(AbilityType::Dexterity),
"Constitution" => Ok(AbilityType::Constitution),
"Intelligence" => Ok(AbilityType::Intelligence),
"Wisdom" => Ok(AbilityType::Wisdom),
"Charisma" => Ok(AbilityType::Charisma),
_ => Err(()),
}
}
}

82
src/dnd/conditions/mod.rs Normal file
View File

@@ -0,0 +1,82 @@
use std::str::FromStr;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub enum ConditionType {
#[serde(rename = "blinded")]
Blinded,
#[serde(rename = "charmed")]
Charmed,
#[serde(rename = "deafened")]
Deafened,
#[serde(rename = "exhaustion")]
Exhaustion,
#[serde(rename = "frightened")]
Frightened,
#[serde(rename = "grappled")]
Grappled,
#[serde(rename = "incapacitated")]
Incapacitated,
#[serde(rename = "invisible")]
Invisible,
#[serde(rename = "paralyzed")]
Paralyzed,
#[serde(rename = "petrified")]
Petrified,
#[serde(rename = "poisoned")]
Poisoned,
#[serde(rename = "prone")]
Prone,
#[serde(rename = "restrained")]
Restrained,
#[serde(rename = "stunned")]
Stunned,
#[serde(rename = "unconscious")]
Unconscious,
}
impl ConditionType {
pub fn to_string(&self) -> String {
match self {
ConditionType::Blinded => "Blinded".to_string(),
ConditionType::Charmed => "Charmed".to_string(),
ConditionType::Deafened => "Deafened".to_string(),
ConditionType::Exhaustion => "Exhaustion".to_string(),
ConditionType::Frightened => "Frightened".to_string(),
ConditionType::Grappled => "Grappled".to_string(),
ConditionType::Incapacitated => "Incapacitated".to_string(),
ConditionType::Invisible => "Invisible".to_string(),
ConditionType::Paralyzed => "Paralyzed".to_string(),
ConditionType::Petrified => "Petrified".to_string(),
ConditionType::Poisoned => "Poisoned".to_string(),
ConditionType::Prone => "Prone".to_string(),
ConditionType::Restrained => "Restrained".to_string(),
ConditionType::Stunned => "Stunned".to_string(),
ConditionType::Unconscious => "Unconscious".to_string(),
}
}
}
impl FromStr for ConditionType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Blinded" => Ok(ConditionType::Blinded),
"Charmed" => Ok(ConditionType::Charmed),
"Deafened" => Ok(ConditionType::Deafened),
"Exhaustion" => Ok(ConditionType::Exhaustion),
"Frightened" => Ok(ConditionType::Frightened),
"Grappled" => Ok(ConditionType::Grappled),
"Incapacitated" => Ok(ConditionType::Incapacitated),
"Invisible" => Ok(ConditionType::Invisible),
"Paralyzed" => Ok(ConditionType::Paralyzed),
"Petrified" => Ok(ConditionType::Petrified),
"Poisoned" => Ok(ConditionType::Poisoned),
"Prone" => Ok(ConditionType::Prone),
"Restrained" => Ok(ConditionType::Restrained),
"Stunned" => Ok(ConditionType::Stunned),
"Unconscious" => Ok(ConditionType::Unconscious),
_ => Err(()),
}
}
}

1
src/dnd/feats/mod.rs Normal file
View File

@@ -0,0 +1 @@

1
src/dnd/items/mod.rs Normal file
View File

@@ -0,0 +1 @@

13
src/dnd/mod.rs Normal file
View File

@@ -0,0 +1,13 @@
pub mod backgrounds;
pub mod bestiary;
pub mod classes;
pub mod conditions;
pub mod feats;
pub mod items;
pub mod options;
pub mod races;
pub mod spells;
pub fn load_data(data_dir_path: &str) {
spells::load_data(data_dir_path);
}

1
src/dnd/options/mod.rs Normal file
View File

@@ -0,0 +1 @@

1
src/dnd/races/mod.rs Normal file
View File

@@ -0,0 +1 @@

63
src/dnd/spells/mod.rs Normal file
View File

@@ -0,0 +1,63 @@
mod model;
mod types;
use std::{
fs::{metadata, File, read_dir},
path::Path,
io::BufReader,
};
use log::{warn, trace};
pub use model::*;
pub use types::*;
pub fn load_data(data_dir_path: &str) {
if Path::new(data_dir_path).exists() {
let meta = metadata(data_dir_path).unwrap();
if meta.is_dir() {
let spells_dir_path = format!("{}/spells", data_dir_path);
if Path::new(&spells_dir_path).exists() {
let meta = metadata(&spells_dir_path).unwrap();
if meta.is_dir() {
for entry in read_dir(&spells_dir_path).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_file() {
let file = File::open(path).unwrap();
let reader = BufReader::new(file);
let result: Result<Vec<Spell>, serde_json::Error> = serde_json::from_reader(reader);
match result {
Ok(spells) => {
for spell in spells {
let mut filters = QueryFilters::default();
filters.by_name = Some(spell.name.clone());
match QuerySpell::get_all(&filters, 100, 1) {
Ok(spells) => {
if spells.len() > 0 {
trace!("Spell '{}' already exists", spell.name);
continue;
}
}
Err(err) => {
warn!("Error checking if spell '{}' exists: {}", spell.name, err);
continue;
}
};
let spell = InsertSpell::insert(spell.into()).unwrap();
trace!("Inserted spell: {}", spell.name);
}
}
Err(err) => warn!("Error reading spells from file: {}", err),
};
}
}
}
}
}
} else {
warn!(
"Data path '{}' does not exist, no data imported",
data_dir_path
);
}
}

417
src/dnd/spells/model.rs Normal file
View File

@@ -0,0 +1,417 @@
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use siren::ServiceError;
use crate::storage::connection;
use crate::storage::schema::spells::{self};
use crate::dnd::{classes::AbilityType, conditions::ConditionType};
use super::{
SchoolType, CastingTime, SpellAttackType, SpellDamageType, Range, Area, Components, Duration,
Source, Description, DurationType, Effect,
};
#[derive(Debug, Queryable, QueryableByName, Serialize, Deserialize)]
#[diesel(table_name = spells)]
pub struct QuerySpell {
pub id: i32,
pub name: String,
pub school: String,
pub level: i32,
pub ritual: bool,
pub concentration: bool,
pub classes: Vec<String>,
pub damage_inflict: Vec<String>,
pub damage_resist: Vec<String>,
pub conditions: Vec<String>,
pub saving_throw: Vec<String>,
pub attack_type: Option<String>,
pub data: serde_json::Value,
}
#[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>,
pub by_concentration: Option<bool>,
pub by_classes: Option<Vec<String>>,
pub by_damage_inflict: Option<Vec<String>>,
pub by_damage_resist: Option<Vec<String>>,
pub by_conditions: Option<Vec<String>>,
pub by_saving_throw: Option<Vec<String>>,
pub by_attack_type: Option<String>,
}
impl Default for QueryFilters {
fn default() -> Self {
Self {
by_name: None,
like_name: None,
by_schools: None,
by_levels: None,
by_ritual: None,
by_concentration: None,
by_classes: None,
by_damage_inflict: None,
by_damage_resist: None,
by_conditions: None,
by_saving_throw: None,
by_attack_type: None,
}
}
}
impl QuerySpell {
pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> {
let mut conn = connection()?;
let mut query = spells::table.limit(limit as i64).into_boxed();
// Limit query to page and limit
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 {
query = query.filter(
spells::school.eq_any(
schools
.iter()
.map(|school| school.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(levels) = &filters.by_levels {
query = query.filter(spells::level.eq_any(levels));
}
if let Some(ritual) = filters.by_ritual {
query = query.filter(spells::ritual.eq(ritual));
}
if let Some(concentration) = filters.by_concentration {
query = query.filter(spells::concentration.eq(concentration));
}
if let Some(classes) = &filters.by_classes {
query = query.filter(spells::classes.overlaps_with(classes));
}
if let Some(damage_inflict) = &filters.by_damage_inflict {
query = query.filter(
spells::damage_inflict.overlaps_with(
damage_inflict
.iter()
.map(|damage_inflict| damage_inflict.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(damage_resist) = &filters.by_damage_resist {
query = query.filter(
spells::damage_resist.overlaps_with(
damage_resist
.iter()
.map(|damage_resist| damage_resist.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(conditions) = &filters.by_conditions {
query = query.filter(
spells::conditions.overlaps_with(
conditions
.iter()
.map(|condition| condition.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(saving_throw) = &filters.by_saving_throw {
query = query.filter(
spells::saving_throw.overlaps_with(
saving_throw
.iter()
.map(|saving_throw| saving_throw.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(attack_type) = &filters.by_attack_type {
query = query.filter(spells::attack_type.eq(attack_type.to_string()));
}
let spells = query.load::<QuerySpell>(&mut conn)?;
Ok(spells)
}
pub fn get_count(filters: &QueryFilters) -> Result<i64, ServiceError> {
let mut conn = connection()?;
let mut query = spells::table.count().into_boxed();
if let Some(name) = &filters.by_name {
query = query.filter(spells::name.ilike(format!("%{}%", name)));
}
if let Some(schools) = &filters.by_schools {
query = query.filter(
spells::school.eq_any(
schools
.iter()
.map(|school| school.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(levels) = &filters.by_levels {
query = query.filter(spells::level.eq_any(levels));
}
if let Some(ritual) = filters.by_ritual {
query = query.filter(spells::ritual.eq(ritual));
}
if let Some(concentration) = filters.by_concentration {
query = query.filter(spells::concentration.eq(concentration));
}
if let Some(classes) = &filters.by_classes {
query = query.filter(spells::classes.overlaps_with(classes));
}
if let Some(damage_inflict) = &filters.by_damage_inflict {
query = query.filter(
spells::damage_inflict.overlaps_with(
damage_inflict
.iter()
.map(|damage_inflict| damage_inflict.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(damage_resist) = &filters.by_damage_resist {
query = query.filter(
spells::damage_resist.overlaps_with(
damage_resist
.iter()
.map(|damage_resist| damage_resist.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(conditions) = &filters.by_conditions {
query = query.filter(
spells::conditions.overlaps_with(
conditions
.iter()
.map(|condition| condition.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(saving_throw) = &filters.by_saving_throw {
query = query.filter(
spells::saving_throw.overlaps_with(
saving_throw
.iter()
.map(|saving_throw| saving_throw.to_string())
.collect::<Vec<String>>(),
),
);
}
if let Some(attack_type) = &filters.by_attack_type {
query = query.filter(spells::attack_type.eq(attack_type.to_string()));
}
let count = query.get_result(&mut conn)?;
Ok(count)
}
pub fn get_by_id(id: i32) -> Result<Self, ServiceError> {
let mut conn = connection()?;
let spell = spells::table
.filter(spells::id.eq(id))
.first::<QuerySpell>(&mut conn)?;
Ok(spell)
}
pub fn delete(id: i32) -> Result<Self, ServiceError> {
let mut conn = connection()?;
let spell = diesel::delete(spells::table.filter(spells::id.eq(id))).get_result(&mut conn)?;
Ok(spell)
}
}
#[derive(Debug, Insertable, AsChangeset)]
#[diesel(table_name = spells)]
pub struct InsertSpell {
pub name: String,
pub school: String,
pub level: i32,
pub ritual: bool,
pub concentration: bool,
pub classes: Vec<String>,
pub damage_inflict: Vec<String>,
pub damage_resist: Vec<String>,
pub conditions: Vec<String>,
pub saving_throw: Vec<String>,
pub attack_type: Option<String>,
pub data: serde_json::Value,
}
impl InsertSpell {
pub fn insert(spell: Self) -> Result<QuerySpell, ServiceError> {
let mut conn = connection()?;
let spell = diesel::insert_into(spells::table)
.values(spell)
.get_result(&mut conn)?;
Ok(spell)
}
pub fn update(id: i32, spell: Self) -> Result<QuerySpell, ServiceError> {
let mut conn = connection()?;
let spell = diesel::update(spells::table.filter(spells::id.eq(id)))
.set(spell)
.get_result(&mut conn)?;
Ok(spell)
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Spell {
pub id: Option<i32>,
pub name: String,
pub school: SchoolType,
pub level: i32,
pub ritual: bool,
pub casting_time: CastingTime,
#[serde(skip_serializing_if = "Option::is_none")]
pub effect: Option<Effect>,
#[serde(skip_serializing_if = "Option::is_none")]
pub saving_throw: Option<Vec<AbilityType>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub attack_type: Option<SpellAttackType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub damage_inflict: Option<Vec<SpellDamageType>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub damage_resist: Option<Vec<SpellDamageType>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub conditions: Option<Vec<ConditionType>>,
pub range: Range,
#[serde(skip_serializing_if = "Option::is_none")]
pub area: Option<Area>,
pub components: Components,
pub durations: Vec<Duration>,
pub classes: Vec<String>,
pub sources: Vec<Source>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<Description>,
}
impl From<QuerySpell> for Spell {
fn from(query: QuerySpell) -> Self {
return match serde_json::from_value(query.data) {
Ok(data) => data,
Err(err) => {
log::error!("Failed to parse spell: {}", err);
Self {
id: None,
name: "".to_string(),
school: SchoolType::Abjuration,
level: 0,
ritual: false,
casting_time: CastingTime {
value: 0,
casting_type: "".to_string(),
note: None,
},
effect: None,
saving_throw: None,
attack_type: None,
damage_inflict: None,
damage_resist: None,
conditions: None,
range: Range {
range_type: "".to_string(),
value: None,
unit: None,
},
area: None,
components: Components {
verbal: false,
somatic: false,
material: false,
materials_needed: None,
materials_cost: None,
materials_consumed: None,
},
durations: vec![],
classes: vec![],
sources: vec![],
tags: None,
description: None,
}
}
};
}
}
impl Into<InsertSpell> for Spell {
fn into(self) -> InsertSpell {
return InsertSpell {
name: self.name.to_string(),
school: self.school.to_string(),
level: self.level,
ritual: self.ritual,
concentration: self
.durations
.iter()
.any(|duration| match duration.duration_type {
DurationType::Concentration => true,
_ => false,
}),
classes: self
.classes
.iter()
.map(|class| class.to_string())
.collect::<Vec<String>>(),
damage_inflict: match &self.damage_inflict {
Some(damage_inflict) => damage_inflict
.iter()
.map(|damage_inflict| damage_inflict.to_string())
.collect(),
None => vec![],
},
damage_resist: match &self.damage_resist {
Some(damage_resist) => damage_resist
.iter()
.map(|damage_resist| damage_resist.to_string())
.collect(),
None => vec![],
},
conditions: match &self.conditions {
Some(conditions) => conditions
.iter()
.map(|condition| condition.to_string())
.collect(),
None => vec![],
},
saving_throw: match &self.saving_throw {
Some(saving_throw) => saving_throw
.iter()
.map(|saving_throw| saving_throw.to_string())
.collect(),
None => vec![],
},
attack_type: self
.attack_type
.as_ref()
.map(|attack_type| attack_type.to_string()),
data: match serde_json::to_value(&self) {
Ok(data) => data,
Err(err) => {
log::error!("Failed to serialize spell: {}", err);
serde_json::Value::Null
}
},
};
}
}

366
src/dnd/spells/types.rs Normal file
View File

@@ -0,0 +1,366 @@
use std::str::FromStr;
use serde::{Deserialize, Serialize, ser::SerializeMap};
#[derive(Debug, Serialize, Deserialize)]
pub enum SchoolType {
#[serde(rename = "abjuration")]
Abjuration,
#[serde(rename = "conjuration")]
Conjuration,
#[serde(rename = "divination")]
Divination,
#[serde(rename = "enchantment")]
Enchantment,
#[serde(rename = "evocation")]
Evocation,
#[serde(rename = "illusion")]
Illusion,
#[serde(rename = "necromancy")]
Necromancy,
#[serde(rename = "transmutation")]
Transmutation,
}
impl SchoolType {
pub fn to_string(&self) -> String {
match self {
SchoolType::Abjuration => "abjuration".to_string(),
SchoolType::Conjuration => "conjuration".to_string(),
SchoolType::Divination => "divination".to_string(),
SchoolType::Enchantment => "enchantment".to_string(),
SchoolType::Evocation => "evocation".to_string(),
SchoolType::Illusion => "illusion".to_string(),
SchoolType::Necromancy => "necromancy".to_string(),
SchoolType::Transmutation => "transmutation".to_string(),
}
}
}
impl FromStr for SchoolType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"abjuration" => Ok(SchoolType::Abjuration),
"conjuration" => Ok(SchoolType::Conjuration),
"divination" => Ok(SchoolType::Divination),
"enchantment" => Ok(SchoolType::Enchantment),
"evocation" => Ok(SchoolType::Evocation),
"illusion" => Ok(SchoolType::Illusion),
"necromancy" => Ok(SchoolType::Necromancy),
"transmutation" => Ok(SchoolType::Transmutation),
_ => Err(()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CastingTime {
pub value: i32,
#[serde(rename = "unit")]
pub casting_type: String,
pub note: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum SpellAttackType {
#[serde(rename = "melee")]
Melee,
#[serde(rename = "ranged")]
Ranged,
}
impl SpellAttackType {
pub fn to_string(&self) -> String {
match self {
SpellAttackType::Melee => "melee".to_string(),
SpellAttackType::Ranged => "ranged".to_string(),
}
}
}
impl FromStr for SpellAttackType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"melee" => Ok(SpellAttackType::Melee),
"ranged" => Ok(SpellAttackType::Ranged),
_ => Err(()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum SpellDamageType {
#[serde(rename = "acid")]
Acid,
#[serde(rename = "bludgeoning")]
Bludgeoning,
#[serde(rename = "cold")]
Cold,
#[serde(rename = "fire")]
Fire,
#[serde(rename = "force")]
Force,
#[serde(rename = "lightning")]
Lightning,
#[serde(rename = "necrotic")]
Necrotic,
#[serde(rename = "piercing")]
Piercing,
#[serde(rename = "poison")]
Poison,
#[serde(rename = "psychic")]
Psychic,
#[serde(rename = "radiant")]
Radiant,
#[serde(rename = "slashing")]
Slashing,
#[serde(rename = "thunder")]
Thunder,
}
impl SpellDamageType {
pub fn to_string(&self) -> String {
match self {
SpellDamageType::Acid => "acid".to_string(),
SpellDamageType::Bludgeoning => "bludgeoning".to_string(),
SpellDamageType::Cold => "cold".to_string(),
SpellDamageType::Fire => "fire".to_string(),
SpellDamageType::Force => "force".to_string(),
SpellDamageType::Lightning => "lightning".to_string(),
SpellDamageType::Necrotic => "necrotic".to_string(),
SpellDamageType::Piercing => "piercing".to_string(),
SpellDamageType::Poison => "poison".to_string(),
SpellDamageType::Psychic => "psychic".to_string(),
SpellDamageType::Radiant => "radiant".to_string(),
SpellDamageType::Slashing => "slashing".to_string(),
SpellDamageType::Thunder => "thunder".to_string(),
}
}
}
impl FromStr for SpellDamageType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"acid" => Ok(SpellDamageType::Acid),
"bludgeoning" => Ok(SpellDamageType::Bludgeoning),
"cold" => Ok(SpellDamageType::Cold),
"fire" => Ok(SpellDamageType::Fire),
"force" => Ok(SpellDamageType::Force),
"lightning" => Ok(SpellDamageType::Lightning),
"necrotic" => Ok(SpellDamageType::Necrotic),
"piercing" => Ok(SpellDamageType::Piercing),
"poison" => Ok(SpellDamageType::Poison),
"psychic" => Ok(SpellDamageType::Psychic),
"radiant" => Ok(SpellDamageType::Radiant),
"slashing" => Ok(SpellDamageType::Slashing),
"thunder" => Ok(SpellDamageType::Thunder),
_ => Err(()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Range {
#[serde(rename = "type")]
pub range_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Area {
#[serde(rename = "type")]
pub area_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Duration {
#[serde(rename = "type")]
pub duration_type: DurationType,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum DurationType {
#[serde(rename = "concentration")]
Concentration,
#[serde(rename = "instantaneous")]
Instantaneous,
#[serde(rename = "timed")]
Timed,
#[serde(rename = "dispelled")]
UntilDispelled,
#[serde(rename = "special")]
Special,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Source {
pub source: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<i32>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Description {
pub entries: Vec<Entry>,
}
#[derive(Debug)]
pub struct Entry {
pub text: Option<String>,
pub list: Option<Vec<String>>,
pub table: Option<EntryTable>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EntryTable {
pub headers: Vec<String>,
pub rows: Vec<Vec<String>>,
}
impl<'de> Deserialize<'de> for Entry {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?;
match value {
serde_json::Value::String(s) => Ok(Entry {
text: Some(s),
list: None,
table: None,
}),
serde_json::Value::Object(o) => {
let text = match o.get("text") {
Some(t) => match t.as_str() {
Some(s) => Some(s.to_string()),
None => return Err(serde::de::Error::custom("Invalid entry text")),
},
None => None,
};
let list = match o.get("list") {
Some(i) => match i.as_array() {
Some(a) => {
let mut list = Vec::new();
for item in a {
match item.as_str() {
Some(s) => list.push(s.to_string()),
None => return Err(serde::de::Error::custom("Invalid entry list item")),
}
}
Some(list)
}
None => return Err(serde::de::Error::custom("Invalid entry list items")),
},
None => None,
};
let table = match o.get("table") {
Some(t) => match t.as_object() {
Some(o) => {
let mut headers = Vec::new();
let mut rows = Vec::new();
match o.get("headers") {
Some(c) => match c.as_array() {
Some(a) => {
for item in a {
match item.as_str() {
Some(s) => headers.push(s.to_string()),
None => return Err(serde::de::Error::custom("Invalid entry table header")),
}
}
}
None => return Err(serde::de::Error::custom("Invalid entry table headers")),
},
None => return Err(serde::de::Error::custom("Missing entry table headers")),
};
match o.get("rows") {
Some(r) => match r.as_array() {
Some(a) => {
for row in a {
match row.as_array() {
Some(a) => {
let mut row = Vec::new();
for item in a {
match item.as_str() {
Some(s) => row.push(s.to_string()),
None => {
return Err(serde::de::Error::custom(
"Invalid entry table row item",
))
}
}
}
rows.push(row);
}
None => return Err(serde::de::Error::custom("Invalid entry table row")),
}
}
}
None => return Err(serde::de::Error::custom("Invalid entry table rows")),
},
None => return Err(serde::de::Error::custom("Missing entry table rows")),
};
Some(EntryTable { headers, rows })
}
None => return Err(serde::de::Error::custom("Invalid entry table")),
},
None => None,
};
Ok(Entry { text, list, table })
}
_ => Err(serde::de::Error::custom("Invalid entry")),
}
}
}
impl Serialize for Entry {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut map = serializer.serialize_map(Some(1))?;
if let Some(text) = &self.text {
map.serialize_entry("text", text)?;
}
if let Some(list) = &self.list {
map.serialize_entry("list", list)?;
}
if let Some(table) = &self.table {
map.serialize_entry("table", table)?;
}
map.end()
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Components {
pub verbal: bool,
pub somatic: bool,
pub material: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub materials_needed: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub materials_cost: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub materials_consumed: Option<bool>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Effect {
pub effect_type: Option<String>,
}

163
src/lib.rs Normal file
View File

@@ -0,0 +1,163 @@
use actix_web::{ResponseError, HttpResponse};
use diesel::result::Error as DieselError;
use reqwest::StatusCode;
use serde::{Serialize, Deserialize};
use std::fmt;
#[derive(Serialize, Deserialize)]
pub struct Message {
pub id: String,
pub guild_id: i64,
pub channel_id: i64,
pub user_id: i64,
pub created: i64,
pub model: String,
pub request: String,
pub response: String,
pub request_tags: Vec<String>,
pub response_tags: Vec<String>,
}
#[derive(Serialize, Deserialize)]
pub struct Response<T> {
pub data: T,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Metadata>,
}
#[derive(Serialize, Deserialize)]
pub struct Metadata {
pub total: i32,
pub limit: i32,
pub page: i32,
pub pages: i32,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ServiceError {
pub status: u16,
pub message: String,
}
impl ServiceError {
pub fn new(error_status_code: u16, error_message: String) -> ServiceError {
ServiceError {
status: error_status_code,
message: error_message,
}
}
}
impl fmt::Display for ServiceError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.message.as_str())
}
}
impl From<std::io::Error> for ServiceError {
fn from(error: std::io::Error) -> ServiceError {
ServiceError::new(500, format!("Unknown io error: {}", error))
}
}
impl From<std::string::FromUtf8Error> for ServiceError {
fn from(error: std::string::FromUtf8Error) -> ServiceError {
ServiceError::new(500, format!("Unknown from utf8 error: {}", error))
}
}
impl From<DieselError> for ServiceError {
fn from(error: DieselError) -> ServiceError {
match error {
DieselError::DatabaseError(kind, err) => match kind {
diesel::result::DatabaseErrorKind::UniqueViolation => {
ServiceError::new(409, err.message().to_string())
}
_ => ServiceError::new(500, err.message().to_string()),
},
DieselError::NotFound => ServiceError::new(404, "The record was not found".to_string()),
DieselError::SerializationError(err) => ServiceError::new(422, err.to_string()),
err => ServiceError::new(500, format!("Unknown database error: {}", err)),
}
}
}
impl From<reqwest::Error> for ServiceError {
fn from(error: reqwest::Error) -> ServiceError {
ServiceError::new(500, format!("Unknown reqwest error: {}", error))
}
}
impl From<serde_json::Error> for ServiceError {
fn from(error: serde_json::Error) -> ServiceError {
ServiceError::new(500, format!("Unknown serde_json error: {}", error))
}
}
impl From<serenity::Error> for ServiceError {
fn from(error: serenity::Error) -> ServiceError {
ServiceError::new(500, format!("Unknown serenity error: {}", error))
}
}
impl From<argon2::password_hash::Error> for ServiceError {
fn from(error: argon2::password_hash::Error) -> ServiceError {
ServiceError::new(500, format!("Unknown argon2 error: {}", error))
}
}
impl From<redis::RedisError> for ServiceError {
fn from(error: redis::RedisError) -> ServiceError {
ServiceError::new(500, format!("Unknown redis error: {}", error))
}
}
impl From<s3::error::S3Error> for ServiceError {
fn from(error: s3::error::S3Error) -> ServiceError {
match error {
s3::error::S3Error::Http(code, message) => ServiceError::new(code, message),
_ => ServiceError::new(500, format!("Unknown s3 error: {}", error)),
}
}
}
impl From<s3::creds::error::CredentialsError> for ServiceError {
fn from(error: s3::creds::error::CredentialsError) -> ServiceError {
ServiceError::new(500, format!("Unknown credentials error: {}", error))
}
}
impl From<uuid::Error> for ServiceError {
fn from(error: uuid::Error) -> ServiceError {
ServiceError::new(500, format!("Unknown uuid error: {}", error))
}
}
impl From<std::env::VarError> for ServiceError {
fn from(error: std::env::VarError) -> ServiceError {
ServiceError::new(500, format!("Unknown env error: {}", error))
}
}
impl From<jsonwebtoken::errors::Error> for ServiceError {
fn from(error: jsonwebtoken::errors::Error) -> ServiceError {
ServiceError::new(500, format!("Unknown jsonwebtoken error: {}", error))
}
}
impl ResponseError for ServiceError {
fn error_response(&self) -> HttpResponse {
let status_code = match StatusCode::from_u16(self.status) {
Ok(status_code) => status_code,
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
let error_message = match status_code.as_u16() < 500 {
true => self.message.clone(),
false => "Internal server error".to_string(),
};
HttpResponse::build(status_code)
.json(serde_json::json!({ "status": status_code.as_u16(), "message": error_message }))
}
}

91
src/main.rs Normal file
View File

@@ -0,0 +1,91 @@
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
use std::env;
use std::collections::HashSet;
use std::sync::Arc;
use serenity::client::Cache;
use serenity::framework::StandardFramework;
use serenity::http::Http;
use serenity::prelude::*;
use songbird::{SerenityInit, Songbird};
use crate::bot::handler::Handler;
mod bot;
mod dnd;
mod storage;
#[tokio::main]
async fn main() {
dotenv::dotenv().ok();
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "warn,siren=info"));
storage::init().await;
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) => {
log::info!("Loaded OpenAI token");
let default_model = env::var("OPENAI_API_MODEL").unwrap_or("gpt-3.5-turbo".to_string());
Handler {
oai: Some(bot::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,
}),
}
}
Err(err) => {
log::warn!("Could not load OpenAI token: {}", err);
Handler { oai: None }
}
};
let songbird = Songbird::serenity();
let mut client = Client::builder(token, intents)
.event_handler(handler)
.framework(StandardFramework::new().configure(|c| c.owners(owners)))
.register_songbird_with(Arc::clone(&songbird))
.await
.expect("Error creating client");
let _shard_manager = Arc::clone(&client.shard_manager);
// Start listening for events by starting a single shard
if let Err(why) = client.start_autosharded().await {
log::error!("Client error: {why:?}");
}
}
pub struct AppState {
pub http: Arc<Http>,
pub cache: Arc<Cache>,
pub songbird: Arc<Songbird>,
}

133
src/storage/mod.rs Normal file
View File

@@ -0,0 +1,133 @@
use diesel::{r2d2::ConnectionManager as DieselConnectionManager, PgConnection};
use redis::{Client as RedisClient, aio::Connection as RedisConnection};
use s3::{Region, creds::Credentials, Bucket, BucketConfiguration, request::ResponseData};
use siren::ServiceError;
use crate::diesel_migrations::MigrationHarness;
use lazy_static::lazy_static;
use log::{error, info};
use r2d2;
use std::env;
pub mod schema;
type DbPool = r2d2::Pool<DieselConnectionManager<PgConnection>>;
pub type DbConnection = r2d2::PooledConnection<DieselConnectionManager<PgConnection>>;
pub const MIGRATIONS: diesel_migrations::EmbeddedMigrations = embed_migrations!();
lazy_static! {
static ref POOL: DbPool = {
let username = env::var("DATABASE_USER").expect("DATABASE_USERNAME is not set");
let password = env::var("DATABASE_PASSWORD").expect("DATABASE_PASSWORD is not set");
let host = env::var("DATABASE_HOST").unwrap_or("localhost".to_string());
let name = env::var("DATABASE_NAME").expect("DATABASE_NAME is not set");
let port = env::var("DATABASE_PORT").unwrap_or("5432".to_string());
let url = format!(
"postgres://{}:{}@{}:{}/{}",
username, password, host, port, name
);
let manager = DieselConnectionManager::<PgConnection>::new(url);
DbPool::builder()
.test_on_check_out(true)
.build(manager)
.expect("Failed to create db pool")
};
static ref REDIS: RedisClient = {
let host = env::var("REDIS_HOST").unwrap_or("localhost".to_string());
let port = env::var("REDIS_PORT").unwrap_or("6379".to_string());
let url = format!("redis://{}:{}", host, port);
RedisClient::open(url).expect("Failed to create redis client")
};
static ref BUCKET: Bucket = {
let url = env::var("MINIO_HOST").unwrap_or("localhost".to_string());
let port = env::var("MINIO_PORT").unwrap_or("9000".to_string());
let user = env::var("MINIO_ROOT_USER").expect("MINIO_ROOT_USER is not set");
let password = env::var("MINIO_ROOT_PASSWORD").expect("MINIO_ROOT_PASSWORD is not set");
let base_url = format!("http://{}:{}", url, port);
let region = Region::Custom {
region: "".to_string(),
endpoint: base_url,
};
let credentials = Credentials {
access_key: Some(user),
secret_key: Some(password),
security_token: None,
session_token: None,
expiration: None,
};
Bucket::new("siren", region.clone(), credentials.clone())
.expect("Failed to create S3 Bucket")
.with_path_style()
};
}
pub async fn init() {
lazy_static::initialize(&POOL);
lazy_static::initialize(&REDIS);
lazy_static::initialize(&BUCKET);
create_bucket().await;
let mut pool: DbConnection = connection().expect("Failed to get db connection");
match pool.run_pending_migrations(MIGRATIONS) {
Ok(_) => info!("Database initialized"),
Err(err) => error!("Failed to initialize database; {}", err),
};
}
pub fn connection() -> Result<DbConnection, ServiceError> {
POOL
.get()
.map_err(|e| ServiceError::new(500, format!("Failed getting db connection: {}", e)))
}
pub fn redis_connection() -> Result<redis::Connection, ServiceError> {
let conn = REDIS.get_connection()?;
Ok(conn)
}
pub async fn redis_async_connection() -> Result<RedisConnection, ServiceError> {
let conn = REDIS.get_async_connection().await?;
Ok(conn)
}
async fn create_bucket() {
let url = env::var("MINIO_URL").unwrap_or("localhost".to_string());
let port = env::var("MINIO_PORT").unwrap_or("9000".to_string());
let user = env::var("MINIO_ROOT_USER").expect("MINIO_ROOT_USER is not set");
let password = env::var("MINIO_ROOT_PASSWORD").expect("MINIO_ROOT_PASSWORD is not set");
let base_url = format!("http://{}:{}", url, port);
let region = Region::Custom {
region: "".to_string(),
endpoint: base_url,
};
let credentials = Credentials {
access_key: Some(user),
secret_key: Some(password),
security_token: None,
session_token: None,
expiration: None,
};
let _ =
Bucket::create_with_path_style("siren", region, credentials, BucketConfiguration::default())
.await;
}
pub async fn upload_file(path: &str, content: &[u8]) -> Result<ResponseData, ServiceError> {
let response = BUCKET.put_object(path, content).await?;
Ok(response)
}
pub async fn get_file(path: &str) -> Result<Vec<u8>, ServiceError> {
let response = BUCKET.get_object(path).await?;
let bytes = response.bytes();
Ok(bytes.to_vec())
}
pub async fn delete_file(path: &str) -> Result<ResponseData, ServiceError> {
let response = BUCKET.delete_object(path).await?;
Ok(response)
}

54
src/storage/schema.rs Normal file
View File

@@ -0,0 +1,54 @@
diesel::table! {
messages (id) {
id -> Text,
guild_id -> BigInt,
channel_id -> BigInt,
user_id -> BigInt,
created -> BigInt,
model -> Text,
request -> Text,
response -> Text,
request_tags -> Array<Text>,
response_tags -> Array<Text>,
}
}
diesel::table! {
spells (id) {
id -> Integer,
name -> Text,
school -> Text,
level -> Integer,
ritual -> Bool,
concentration -> Bool,
classes -> Array<Text>,
damage_inflict -> Array<Text>,
damage_resist -> Array<Text>,
conditions -> Array<Text>,
saving_throw -> Array<Text>,
attack_type -> Nullable<Text>,
data -> Jsonb
}
}
diesel::table! {
guilds (id) {
id -> BigInt,
bot_id -> BigInt,
volume -> Integer,
}
}
diesel::table! {
users (email) {
email -> Text,
hash -> Text,
role -> Text,
first_name -> Text,
last_name -> Text,
updated_at -> Timestamp,
created_at -> Timestamp,
profile_picture -> Nullable<Text>,
verified -> Bool,
}
}