Fixed play command

This commit is contained in:
2024-09-05 11:01:08 -04:00
parent fce4a0a4a2
commit bce363db7e
23 changed files with 410 additions and 552 deletions

4
.env
View File

@@ -1,4 +1,4 @@
RUST_LOG=warn,service=debug RUST_LOG=warn,siren=info
DATABASE_USER=siren DATABASE_USER=siren
DATABASE_PASSWORD=CHANGEME # Change this to a secure password DATABASE_PASSWORD=CHANGEME # Change this to a secure password
@@ -21,6 +21,6 @@ SERVICE_HOST=localhost
SERVICE_PORT=5000 SERVICE_PORT=5000
DATA_DIR_PATH= # OPTIONAL DATA_DIR_PATH= # OPTIONAL
DISCORD_TOKEN= # OPTIONAL DISCORD_TOKEN=
OPENAI_API_KEY= # OPTIONAL OPENAI_API_KEY= # OPTIONAL
OPENAI_API_MODEL=gpt-3.5-turbo OPENAI_API_MODEL=gpt-3.5-turbo

View File

@@ -1 +1 @@
SIREN_VERSION=0.2.7 SIREN_VERSION=0.2.8

View File

@@ -1,29 +1,27 @@
[package] [package]
name = "service" name = "siren"
version = "0.2.8" version = "0.2.8"
edition = "2021" edition = "2021"
authors = ["Ben Sherriff <hello@bensherriff.com>"] authors = ["Ben Sherriff <hello@bensherriff.com>"]
description = "A Discord bot for playing music"
repository = "https://github.com/bensherriff/siren" repository = "https://github.com/bensherriff/siren"
readme = "README.md" readme = "README.md"
license = "GPL-3.0-or-later" license = "GPL-3.0-or-later"
[lib]
name = "siren"
path = "src/lib.rs"
[dependencies] [dependencies]
dotenv = "0.15.0" dotenv = "0.15.0"
log = "0.4.22" log = "0.4.22"
env_logger = "0.11.5" env_logger = "0.11.5"
serde = { version = "1.0.209", features = ["derive"] } serde = { version = "1.0.209", features = ["derive"] }
serde_json = "1.0.127" serde_json = "1.0.127"
serenity = { version = "0.11.6", default-features = false, features = ["client", "gateway", "rustls_backend", "model", "voice", "cache", "framework", "standard_framework"] } serenity = { version = "0.12.2", default-features = false, features = ["client", "gateway", "rustls_backend", "model", "voice", "cache", "framework", "standard_framework"] }
songbird = { version = "0.3.2", features = ["builtin-queue", "yt-dlp"] } songbird = { version = "0.4.3", features = ["builtin-queue"] }
symphonia = { version = "0.5.4", features = ["all"] }
diesel = { version = "2.1.5", default-features = false, features = ["postgres", "chrono", "r2d2", "32-column-tables", "serde_json", "with-deprecated"] } diesel = { version = "2.1.5", default-features = false, features = ["postgres", "chrono", "r2d2", "32-column-tables", "serde_json", "with-deprecated"] }
diesel_migrations = { version = "2.1.0", features = ["postgres"] } diesel_migrations = { version = "2.1.0", features = ["postgres"] }
r2d2 = "0.8.10" r2d2 = "0.8.10"
chrono = { version = "0.4.38", features = ["serde"] } chrono = { version = "0.4.38", features = ["serde"] }
reqwest = { version = "0.12.7", default-features = false, features = ["json"] } reqwest = { version = "0.11", default-features = false, features = ["json"] }
lazy_static = "1.5.0" lazy_static = "1.5.0"
uuid = { version = "1.10.0", features = ["serde", "v4"] } uuid = { version = "1.10.0", features = ["serde", "v4"] }
redis = { version = "0.26.1", features = ["tokio-comp", "connection-manager", "r2d2"] } redis = { version = "0.26.1", features = ["tokio-comp", "connection-manager", "r2d2"] }

View File

@@ -47,4 +47,7 @@ docker-clean: ## Stop the docker containers and remove volumes
@docker compose --profile backend --profile siren down -v @docker compose --profile backend --profile siren down -v
@echo "Docker container stopped and volumes removed" @echo "Docker container stopped and volumes removed"
docker-refresh: docker-clean backend-up ## Refresh the docker containers docker-refresh: docker-clean backend-up ## Refresh the docker containers
psql: ## Connect to the database
@docker exec -it siren-db psql -U ${DATABASE_USER} -P pager=off

View File

@@ -1,20 +1,14 @@
use std::sync::Arc; use std::sync::Arc;
use log::{debug, warn};
use reqwest::Url; use reqwest::Url;
use serenity::all::{CommandInteraction, CreateInteractionResponse, CreateInteractionResponseMessage, EditInteractionResponse};
use serenity::client::Cache; use serenity::client::Cache;
use serenity::model::application::interaction::{
InteractionResponseType, application_command::ApplicationCommandInteraction,
};
use serenity::model::prelude::{GuildId, ChannelId}; use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User; use serenity::model::user::User;
use serenity::prelude::*; use serenity::prelude::*;
use siren::ServiceError; use songbird::Songbird;
use songbird::{Call, Songbird};
use songbird::input::{Restartable, Input, Metadata, error::Error as SongbirdError};
use crate::bot::ytdlp::{PlaylistItem, YtDlp}; use crate::error::{SirenResult, Error as SirenError};
pub mod pause; pub mod pause;
pub mod play; pub mod play;
@@ -23,57 +17,41 @@ pub mod skip;
pub mod stop; pub mod stop;
pub mod volume; pub mod volume;
/**
* Finds a voice channel that the user is currently in, and attempts to join it.
*/
pub async fn join_by_user( pub async fn join_by_user(
cache: &Arc<Cache>, cache: &Arc<Cache>,
manager: Arc<Songbird>, manager: &Arc<Songbird>,
guild_id_option: &Option<GuildId>, guild_id: &GuildId,
user: &User, user: &User,
) -> Result<(), ServiceError> { ) -> SirenResult<ChannelId> {
let guild_id = match guild_id_option { let channel_id = match find_voice_channel(cache, guild_id, user) {
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, Ok(channel) => channel,
Err(err) => { Err(err) => return Err(SirenError::new(500, err.to_string()))
return Err(ServiceError {
status: 500,
message: err.to_string(),
})
}
}; };
join(manager, guild_id, &channel_id).await join_voice_channel(manager, guild_id, &channel_id).await?;
Ok(channel_id)
} }
pub async fn join( /**
manager: Arc<Songbird>, * Joins a voice channel.
*/
async fn join_voice_channel(
manager: &Arc<Songbird>,
guild_id: &GuildId, guild_id: &GuildId,
channel_id: &ChannelId, channel_id: &ChannelId,
) -> Result<(), ServiceError> { ) -> SirenResult<()> {
debug!("<{}> Joining channel {}", guild_id.0, channel_id.0); log::debug!("<{}> Joining channel {}", guild_id.get(), channel_id.get());
let (_handle_lock, success) = manager manager.join(guild_id.to_owned(), channel_id.to_owned()).await?;
.join(guild_id.to_owned(), channel_id.to_owned()) Ok(())
.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( /**
* Leaves a voice channel.
*/
pub async fn leave_voice_channel(
manager: Arc<Songbird>, manager: Arc<Songbird>,
guild_id_option: &Option<GuildId>, guild_id_option: &Option<GuildId>,
) -> Result<(), String> { ) -> Result<(), String> {
@@ -85,7 +63,7 @@ pub async fn leave(
}; };
if manager.get(*guild_id).is_some() { if manager.get(*guild_id).is_some() {
debug!("<{}> Disconnecting from channel", guild_id.0); log::debug!("<{}> Disconnecting from channel", guild_id.get());
if let Err(e) = manager.remove(*guild_id).await { if let Err(e) = manager.remove(*guild_id).await {
return Err(format!("{}", e)); return Err(format!("{}", e));
} }
@@ -93,12 +71,15 @@ pub async fn leave(
Ok(()) Ok(())
} }
/**
* Finds a voice channel that the user is currently in.
*/
fn find_voice_channel( fn find_voice_channel(
cache: &Arc<Cache>, cache: &Arc<Cache>,
guild_id: &GuildId, guild_id: &GuildId,
user: &User, user: &User,
) -> Result<ChannelId, String> { ) -> Result<ChannelId, String> {
let guild = match guild_id.to_guild_cached(cache.to_owned()) { let guild = match guild_id.to_guild_cached(cache) {
Some(g) => g, Some(g) => g,
None => return Err(format!("Guild not found")), None => return Err(format!("Guild not found")),
}; };
@@ -115,86 +96,29 @@ fn find_voice_channel(
pub async fn create_response( pub async fn create_response(
ctx: &Context, ctx: &Context,
command: &ApplicationCommandInteraction, command: &CommandInteraction,
content: String, content: String,
) -> Result<(), SerenityError> { ) -> Result<(), SerenityError> {
command let data = CreateInteractionResponseMessage::new().content(content);
.create_interaction_response( let builder = CreateInteractionResponse::Message(data);
&ctx.http, command.create_response(&ctx.http, builder).await?;
|response: &mut serenity::builder::CreateInteractionResponse<'_>| { Ok(())
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(
|message: &mut serenity::builder::CreateInteractionResponseData<'_>| {
message.content(content)
},
)
},
)
.await
} }
pub async fn edit_response( pub async fn edit_response(
ctx: &Context, ctx: &Context,
command: &ApplicationCommandInteraction, command: &CommandInteraction,
content: String, content: String,
) -> Result<serenity::model::channel::Message, SerenityError> { ) -> Result<serenity::model::channel::Message, SerenityError> {
command let builder = EditInteractionResponse::new().content(content);
.edit_original_interaction_response( command.edit_response(&ctx.http, builder).await
&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)
} }
/**
* Checks if a URL is valid and if it is a playlist.
* 1st tuple value is if the URL is valid.
* 2nd tuple value is if the URL is a playlist.
*/
fn is_valid_url(url: &str) -> (bool, bool) { fn is_valid_url(url: &str) -> (bool, bool) {
Url::parse(url).ok().map_or((false, false), |valid_url| { Url::parse(url).ok().map_or((false, false), |valid_url| {
let is_playlist: bool = valid_url let is_playlist: bool = valid_url

View File

@@ -1,12 +1,10 @@
use log::{debug, error}; use log::{debug, error};
use serenity::prelude::*; use serenity::{all::{CommandInteraction, CreateCommand}, prelude::*};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response}; use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) { pub async fn run(ctx: &Context, command: &CommandInteraction) {
// Create the initial response // Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await { if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
@@ -40,6 +38,6 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register() -> CreateCommand {
command.name("pause").description("Pause the current track") CreateCommand::new("pause").description("Pause the current track")
} }

View File

@@ -1,51 +1,39 @@
use std::sync::Arc; use std::sync::Arc;
use log::{debug, warn, error}; use serenity::all::{CommandInteraction, CommandOptionType, CreateCommand, CreateCommandOption};
use serenity::model::prelude::GuildId; use serenity::model::prelude::GuildId;
use serenity::{prelude::*, async_trait}; use serenity::{prelude::*, async_trait};
use serenity::builder::CreateApplicationCommand; use songbird::input::{AuxMetadata, Input, YoutubeDl};
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction; use songbird::tracks::TrackHandle;
use siren::ServiceError; use songbird::{Call, EventHandler, Songbird};
use songbird::{EventHandler, Songbird};
use crate::bot::guilds::QueryGuild; use crate::bot::guilds::GuildCache;
use crate::bot::ytdlp::PlaylistItem; use crate::bot::ytdlp::{PlaylistItem, YtDlp};
use crate::bot::{ use crate::bot::commands::audio::{create_response, edit_response, leave_voice_channel};
commands::audio::{leave, get_playlist_urls, add_song, get_songbird}, use crate::error::{SirenResult, Error as SirenError};
}; use crate::HttpKey;
use super::{create_response, edit_response, is_valid_url, join_by_user}; use super::{get_songbird, is_valid_url, join_by_user};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) { pub async fn run(ctx: &Context, command: &CommandInteraction) {
// Get the track url // Get the track url
let track_url = match command.data.options.get(0) { let track_url = match command.data.options.get(0) {
Some(t) => match &t.value { Some(o) => match &o.value.as_str() {
Some(v) => match v.as_str() {
Some(s) => s.to_owned(), Some(s) => s.to_owned(),
None => { None => {
warn!("Missing track option"); log::warn!("Missing track option");
if let Err(why) = if let Err(why) =
create_response(&ctx, &command, format!("Track option is missing")).await create_response(&ctx, &command, format!("Track option is missing")).await
{ {
error!("Failed to create response message: {}", why); log::error!("Failed to create response message: {}", why);
} }
return; 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 => { None => {
warn!("Missing track option"); log::warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await { if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
error!("Failed to create response message: {}", why); log::error!("Failed to create response message: {}", why);
} }
return; return;
} }
@@ -53,27 +41,29 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Create the initial response // Create the initial response
if let Err(why) = create_response(&ctx, &command, format!("Processing command...")).await { if let Err(why) = create_response(&ctx, &command, format!("Processing command...")).await {
error!("Failed to create response message: {}", why); log::error!("Failed to create response message: {}", why);
return; return;
} }
let manager = get_songbird(ctx).await; let manager = get_songbird(ctx).await;
match join_by_user(&ctx.cache, manager, &command.guild_id, &command.user).await { // Extract the guild ID
let guild_id = match &command.guild_id {
Some(guild_id) => guild_id,
None => {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
log::error!("Failed to edit response message: {}", why);
}
return;
}
};
// Join the user's voice channel
match join_by_user(&ctx.cache, &manager, guild_id, &command.user).await {
Ok(_) => { Ok(_) => {
let guild_id = match command.guild_id { log::debug!("Play command executed with track: {:?}", track_url);
Some(g) => g, // Handle the track url
None => { match play_track(ctx, manager, guild_id.to_owned(), track_url).await {
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) => { Ok(count) => {
let mut message = format!("Playing {} tracks", count); let mut message = format!("Playing {} tracks", count);
if count == 0 { if count == 0 {
@@ -82,72 +72,71 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
message = "Playing 1 track".to_string(); message = "Playing 1 track".to_string();
} }
if let Err(why) = edit_response(&ctx, &command, message).await { if let Err(why) = edit_response(&ctx, &command, message).await {
error!("Failed to edit response message: {}", why); log::error!("Failed to edit response message: {}", why);
} }
} }
Err(err) => { Err(err) => {
warn!("Failed to play track: {}", err); log::warn!("Failed to play track: {}", err);
if let Err(why) = if let Err(why) =
edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await
{ {
error!("Failed to edit response message: {}", why); log::error!("Failed to edit response message: {}", why);
} }
} }
}; };
} }
Err(err) => { Err(err) => {
warn!("{}", err); log::warn!("{}", err);
if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await { if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await {
error!("Failed to edit response message: {}", why); log::error!("Failed to edit response message: {}", why);
} }
} }
} }
} }
pub async fn play_track( pub async fn play_track(
ctx: &Context,
manager: Arc<Songbird>, manager: Arc<Songbird>,
guild_id: GuildId, guild_id: GuildId,
track_url: String, track_url: &str,
) -> Result<i32, ServiceError> { ) -> SirenResult<i32> {
let mut track_count = 0; let mut track_count = 0;
if let Some(handler_lock) = manager.get(guild_id) { if let Some(handler_lock) = manager.get(guild_id) {
let is_queue_empty = { let is_queue_empty = {
let call_handler = handler_lock.lock().await; let call_handler = handler_lock.lock().await;
call_handler.queue().is_empty() call_handler.queue().is_empty()
}; };
let guild = QueryGuild::get(guild_id.0 as i64)?; let guild = GuildCache::get(guild_id.get() as i64)?;
let valid = is_valid_url(&track_url); let valid = is_valid_url(&track_url);
// Check if the URL is valid
if !valid.0 { if !valid.0 {
warn!("Invalid track url: {}", track_url); log::warn!("Invalid track url: {}", track_url);
return Err(ServiceError { return Err(SirenError::new(422, format!("Invalid track url: {}", track_url)));
status: 422,
message: format!("Invalid track url: {}", track_url),
});
} }
let mut playlist_items: Vec<PlaylistItem> = Vec::new(); let mut playlist_items: Vec<PlaylistItem> = Vec::new();
// Check if the URL is a playlist or a single track
if valid.1 { if valid.1 {
playlist_items = match get_playlist_urls(&track_url) { playlist_items = match get_playlist_urls(&track_url) {
Ok(items) => items, Ok(items) => items,
Err(err) => { Err(err) => {
warn!("Failed to get playlist urls: {}", err); log::warn!("Failed to get playlist urls: {}", err);
return Err(ServiceError { return Err(SirenError::new(422,err.to_string()));
status: 422,
message: err.to_string(),
});
} }
}; };
} else { } else {
let playlist_item = PlaylistItem { let playlist_item = PlaylistItem {
id: "".to_string(), id: "".to_string(),
url: track_url, url: track_url.to_string(),
title: "".to_string(), title: "".to_string(),
duration: 0, duration: 0,
playlist_index: 0, playlist_index: 0,
}; };
playlist_items.push(playlist_item); playlist_items.push(playlist_item);
} }
// Add each track to the queue
for item in playlist_items { for item in playlist_items {
match add_song( match add_song(
ctx,
handler_lock.clone(), handler_lock.clone(),
&item.url, &item.url,
is_queue_empty, is_queue_empty,
@@ -157,7 +146,7 @@ pub async fn play_track(
{ {
Ok(added_song) => { Ok(added_song) => {
let track_title = added_song.title.unwrap(); let track_title = added_song.title.unwrap();
debug!("Added track: {}", track_title); log::debug!("Added track: {}", track_title);
let mut handler = handler_lock.lock().await; let mut handler = handler_lock.lock().await;
handler.remove_all_global_events(); handler.remove_all_global_events();
handler.add_global_event( handler.add_global_event(
@@ -170,14 +159,11 @@ pub async fn play_track(
track_count += 1; track_count += 1;
} }
Err(err) => { Err(err) => {
warn!("Failed to add song: {}", err); log::warn!("Failed to add song: {}", err);
if let Err(why) = leave(manager, &Some(guild_id)).await { if let Err(why) = leave_voice_channel(manager, &Some(guild_id)).await {
error!("Failed to leave voice channel: {}", why); log::error!("Failed to leave voice channel: {}", why);
} }
return Err(ServiceError { return Err(SirenError::new(422, err.to_string()));
status: 422,
message: err.to_string(),
});
} }
} }
} }
@@ -185,17 +171,68 @@ pub async fn play_track(
Ok(track_count) Ok(track_count)
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { async fn add_song(
command ctx: &Context,
.name("play") call: Arc<Mutex<Call>>,
.description("Plays the given track") url: &str,
.create_option(|option| { lazy: bool,
option volume: Option<f32>,
.name("track") ) -> SirenResult<AuxMetadata> {
.description("The track to be played") // let source = Restartable::ytdl(url.to_owned(), lazy).await?;
.kind(serenity::model::prelude::command::CommandOptionType::String) let http_client = {
.required(true) let data = ctx.data.read().await;
data.get::<HttpKey>()
.cloned()
.expect("Guaranteed to exist in the typemap.")
};
let source = YoutubeDl::new(http_client, url.to_owned());
let mut handler = call.lock().await;
let mut track: Input = source.into();
let metadata = track.aux_metadata().await.unwrap();
let track_handle: TrackHandle;
if lazy {
track_handle = handler.play_input(track);
} else {
track_handle = handler.enqueue_input(track).await;
}
if let Some(volume) = volume {
let _ = track_handle.set_volume(volume);
}
Ok(metadata)
}
pub fn get_playlist_urls(url: &str) -> SirenResult<Vec<PlaylistItem>> {
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| SirenError::new(500, err.to_string())),
)
}
}) })
.filter_map(|parsed| match parsed {
Ok(item) => Some(item),
Err(err) => {
log::warn!("Failed to parse playlist item: {}", err);
None
}
})
.collect();
Ok(items)
}
pub fn register() -> CreateCommand {
CreateCommand::new("play")
.description("Plays the given track")
.add_option(CreateCommandOption::new(CommandOptionType::String, "track", "The track to be played").required(true))
} }
struct TrackEndNotifier { struct TrackEndNotifier {
@@ -210,7 +247,7 @@ impl EventHandler for TrackEndNotifier {
if let Some(call) = self.call.get(self.guild_id) { if let Some(call) = self.call.get(self.guild_id) {
let mut handler = call.lock().await; let mut handler = call.lock().await;
if handler.queue().is_empty() { if handler.queue().is_empty() {
debug!("Queue is empty, leaving voice channel"); log::debug!("Queue is empty, leaving voice channel");
handler.leave().await.unwrap(); handler.leave().await.unwrap();
} }
} }

View File

@@ -1,12 +1,10 @@
use log::{debug, error}; use log::{debug, error};
use serenity::prelude::*; use serenity::{all::{CommandInteraction, CreateCommand}, prelude::*};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response}; use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) { pub async fn run(ctx: &Context, command: &CommandInteraction) {
// Create the initial response // Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await { if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
@@ -40,8 +38,6 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register() -> CreateCommand {
command CreateCommand::new("resume").description("Resume the current track")
.name("resume")
.description("Resume the current track")
} }

View File

@@ -1,12 +1,10 @@
use log::{debug, error}; use log::{debug, error};
use serenity::prelude::*; use serenity::{all::{CommandInteraction, CreateCommand}, prelude::*};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response}; use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) { pub async fn run(ctx: &Context, command: &CommandInteraction) {
// Create the initial response // Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await { if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
@@ -40,6 +38,6 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register() -> CreateCommand {
command.name("skip").description("Skip the current track") CreateCommand::new("skip").description("Skip the current track")
} }

View File

@@ -1,12 +1,10 @@
use log::{debug, error}; use log::{debug, error};
use serenity::prelude::*; use serenity::{all::{CommandInteraction, CreateCommand}, prelude::*};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response}; use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) { pub async fn run(ctx: &Context, command: &CommandInteraction) {
// Create the initial response // Create the initial response
if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await { if let Err(why) = create_response(&ctx, &command, "Processing command...".to_string()).await {
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
@@ -35,8 +33,6 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register() -> CreateCommand {
command CreateCommand::new("stop").description("Stop the current track and clear the queue")
.name("stop")
.description("Stop the current track and clear the queue")
} }

View File

@@ -2,34 +2,22 @@ use std::sync::Arc;
use log::{error, warn}; use log::{error, warn};
use serenity::{prelude::*, model::prelude::GuildId}; use serenity::{all::{CommandInteraction, CommandOptionType, CreateCommand, CreateCommandOption}, model::prelude::GuildId, prelude::*};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use songbird::Songbird; use songbird::Songbird;
use crate::bot::guilds::InsertGuild; use crate::bot::guilds::GuildCache;
use super::{get_songbird, create_response, edit_response}; use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) { pub async fn run(ctx: &Context, command: &CommandInteraction) {
// Get the volume // Get the volume
let volume = match command.data.options.get(0) { let volume = match command.data.options.get(0) {
Some(t) => match &t.value { Some(o) => match o.value.as_i64() {
Some(v) => match v.as_i64() { Some(p) => p as i32,
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 => { None => {
warn!("Missing volume option value"); warn!("Unable to get volume option as a string");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await if let Err(why) =
create_response(&ctx, &command, format!("Volume option is missing")).await
{ {
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
} }
@@ -74,7 +62,7 @@ pub async fn set_volume(manager: Arc<Songbird>, guild_id: GuildId, volume: i32)
// Format volume to f32 bound between 0.0 and 1.0 // Format volume to f32 bound between 0.0 and 1.0
let volume = std::cmp::min(100, std::cmp::max(0, volume)); let volume = std::cmp::min(100, std::cmp::max(0, volume));
let bound_volume = volume as f32 / 100.0; let bound_volume = volume as f32 / 100.0;
let _ = InsertGuild::update_audio(guild_id.0 as i64, volume); let _ = GuildCache::update_audio(guild_id.get() as i64, volume);
if let Some(handler_lock) = manager.get(guild_id) { if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await; let handler = handler_lock.lock().await;
@@ -84,15 +72,8 @@ pub async fn set_volume(manager: Arc<Songbird>, guild_id: GuildId, volume: i32)
} }
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register() -> CreateCommand {
command CreateCommand::new("volume")
.name("volume")
.description("Set the audio player volume") .description("Set the audio player volume")
.create_option(|option| { .add_option(CreateCommandOption::new(CommandOptionType::Integer, "volume", "Volume between 0 and 100").required(true))
option
.name("volume")
.description("Volume between 0 and 100")
.kind(serenity::model::prelude::command::CommandOptionType::Integer)
.required(true)
})
} }

View File

@@ -1,5 +1,6 @@
use log::{error, trace, warn}; use log::{error, trace, warn};
use serenity::all::CreateThread;
use serenity::model::Permissions; use serenity::model::Permissions;
use serenity::model::channel::Message; use serenity::model::channel::Message;
use serenity::model::prelude::{ChannelType, PermissionOverwrite, PermissionOverwriteType}; use serenity::model::prelude::{ChannelType, PermissionOverwrite, PermissionOverwriteType};
@@ -16,7 +17,7 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
let author_id = msg.author.id; let author_id = msg.author.id;
// Parse out the bot mention from the message // Parse out the bot mention from the message
let bot_mention: String = format!("<@{}>", ctx.cache.current_user_id().0); let bot_mention: String = format!("<@{}>", ctx.cache.current_user().id);
let parsed_content = msg.content.replace(bot_mention.as_str(), ""); let parsed_content = msg.content.replace(bot_mention.as_str(), "");
let mut messages = vec![ let mut messages = vec![
@@ -28,9 +29,9 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
match QueryMessage::get_all( match QueryMessage::get_all(
&QueryFilters { &QueryFilters {
by_guild_id: Some(guild_id.0 as i64), by_guild_id: Some(guild_id.get() as i64),
by_channel_id: Some(channel_id.0 as i64), by_channel_id: Some(channel_id.get() as i64),
by_user_id: Some(author_id.0 as i64), by_user_id: Some(author_id.get() as i64),
..Default::default() ..Default::default()
}, },
100, 100,
@@ -71,9 +72,8 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
let thread_name = generate_thread_name(oai, &parsed_content, 99).await; let thread_name = generate_thread_name(oai, &parsed_content, 99).await;
let response_channel = match msg let response_channel = match msg
.channel_id .channel_id
.create_private_thread(&ctx.http, |thread| { .create_thread(&ctx.http, CreateThread::new(thread_name).kind(ChannelType::PublicThread)
thread.name(thread_name).kind(ChannelType::PublicThread) )
})
.await .await
{ {
Ok(c) => { Ok(c) => {
@@ -84,13 +84,13 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
deny, deny,
kind: PermissionOverwriteType::Member(msg.author.id), kind: PermissionOverwriteType::Member(msg.author.id),
}; };
let _ = c.create_permission(&ctx.http, &overwrite).await; let _ = c.create_permission(&ctx.http, overwrite).await;
c.id c.id
} }
Err(_) => channel_id, Err(_) => channel_id,
}; };
let typing = response_channel.start_typing(&ctx.http).unwrap(); let typing = response_channel.start_typing(&ctx.http);
// Get the OAI response and store message/response into the database // Get the OAI response and store message/response into the database
let response = match oai.chat_completion(request).await { let response = match oai.chat_completion(request).await {
@@ -100,9 +100,9 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
let res = r.choices[0].message.content.clone(); let res = r.choices[0].message.content.clone();
if let Err(err) = QueryMessage::insert(QueryMessage { if let Err(err) = QueryMessage::insert(QueryMessage {
id: r.id, id: r.id,
guild_id: guild_id.0 as i64, guild_id: guild_id.get() as i64,
channel_id: response_channel.0 as i64, channel_id: response_channel.get() as i64,
user_id: author_id.0 as i64, user_id: author_id.get() as i64,
created: r.created, created: r.created,
model: serde_json::to_string(&r.model).unwrap(), model: serde_json::to_string(&r.model).unwrap(),
request: parsed_content, request: parsed_content,

View File

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

View File

@@ -1,25 +1,19 @@
use log::{error, warn}; use log::{error, warn};
use rand::Rng; use rand::Rng;
use serenity::{ use serenity::all::{CommandInteraction, CommandOptionType, Context, CreateCommand, CreateCommandOption};
builder::CreateApplicationCommand,
client::Context,
model::application::{
command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction,
},
};
use crate::bot::commands::audio::edit_response; use crate::bot::commands::audio::edit_response;
use super::audio::create_response; use super::audio::create_response;
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) { pub async fn run(ctx: &Context, command: &CommandInteraction) {
if let Err(why) = create_response(&ctx, &command, format!("Processing command...")).await { if let Err(why) = create_response(&ctx, &command, format!("Processing command...")).await {
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
return; return;
} }
let dice_string: String = match command.data.options.get(0) { let dice_string = match command.data.options.get(0) {
Some(o) => match &o.value { Some(o) => {
Some(v) => match v.as_str() { match o.value.as_str() {
Some(s) => s.split_whitespace().collect::<String>(), Some(s) => s.split_whitespace().collect::<String>(),
None => { None => {
warn!("Missing dice option"); warn!("Missing dice option");
@@ -28,21 +22,14 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
return; 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 => { None => {
warn!("Missing dice option"); warn!("Missing dice option");
if let Err(why) = edit_response(&ctx, &command, format!("Dice option is missing")).await { if let Err(why) = edit_response(&ctx, &command, format!("Dice option is missing")).await {
error!("Failed to create response message: {}", why); error!("Failed to create response message: {}", why);
} }
return; return;
} }
}; };
let dice = parse_dice(dice_string.as_str()); let dice = parse_dice(dice_string.as_str());
@@ -135,15 +122,8 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
Ok((count, sides, modifier)) Ok((count, sides, modifier))
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register() -> CreateCommand {
command CreateCommand::new("roll")
.name("roll")
.description("Rolls D&D dice") .description("Rolls D&D dice")
.create_option(|option| { .add_option(CreateCommandOption::new(CommandOptionType::String, "dice", "Dice to roll").required(true))
option
.name("dice")
.description("Dice to roll")
.kind(CommandOptionType::String)
.required(true)
})
} }

View File

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

View File

@@ -1,10 +1,11 @@
use log::{warn, info, error}; use log::{warn, info, error};
use serenity::all::Interaction;
use serenity::async_trait; use serenity::async_trait;
use serenity::model::application::interaction::Interaction;
use serenity::model::gateway::Ready; use serenity::model::gateway::Ready;
use serenity::model::channel::Message; use serenity::model::channel::Message;
use serenity::prelude::*; use serenity::prelude::*;
use super::guilds::GuildCache;
use super::{commands, oai}; use super::{commands, oai};
use super::commands::audio::create_response; use super::commands::audio::create_response;
@@ -28,7 +29,7 @@ impl EventHandler for Handler {
Ok(t) => { Ok(t) => {
match t match t
.iter() .iter()
.find(|t| t.user_id.unwrap().0 == ctx.cache.current_user_id().0) .find(|t| t.user_id == ctx.cache.current_user().id)
{ {
Some(_) => true, Some(_) => true,
None => false, None => false,
@@ -48,8 +49,10 @@ impl EventHandler for Handler {
} }
async fn interaction_create(&self, ctx: Context, interaction: Interaction) { async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
if let Interaction::ApplicationCommand(command) = interaction { if let Interaction::Command(command) = interaction {
log::trace!("Received command interaction: {command:#?}");
match command.data.name.as_str() { match command.data.name.as_str() {
// Match commands without returns
"roll" => commands::roll::run(&ctx, &command).await, "roll" => commands::roll::run(&ctx, &command).await,
"play" => commands::audio::play::run(&ctx, &command).await, "play" => commands::audio::play::run(&ctx, &command).await,
"stop" => commands::audio::stop::run(&ctx, &command).await, "stop" => commands::audio::stop::run(&ctx, &command).await,
@@ -59,6 +62,7 @@ impl EventHandler for Handler {
"volume" => commands::audio::volume::run(&ctx, &command).await, "volume" => commands::audio::volume::run(&ctx, &command).await,
_ => { _ => {
let content: String = match command.data.name.as_str() { let content: String = match command.data.name.as_str() {
// Match commands with string returns
"ping" => commands::ping::run(&command.data.options), "ping" => commands::ping::run(&command.data.options),
_ => "Unknown command".to_string(), _ => "Unknown command".to_string(),
}; };
@@ -76,57 +80,34 @@ impl EventHandler for Handler {
warn!("No ready guilds found"); warn!("No ready guilds found");
} }
for guild in ready.guilds { for guild in ready.guilds {
// Check if guild exists in database
let guild_id = guild.id.get() as i64;
if let Err(why) = GuildCache::get(guild_id) {
let guild_cache = GuildCache {
id: guild_id,
bot_id: 1,
volume: 100
};
guild_cache.insert();
}
let commands = guild let commands = guild
.id .id
.set_application_commands(&ctx.http, |commands| { .set_commands(&ctx.http, vec![
commands commands::ping::register(),
.create_application_command( commands::roll::register(),
|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::play::register(),
commands::ping::register(command) commands::audio::stop::register(),
}, commands::audio::pause::register(),
) commands::audio::resume::register(),
.create_application_command( commands::audio::skip::register(),
|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::volume::register(),
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; .await;
match commands { match commands {
Ok(c) => info!("Registered {} commands for guild {}", c.len(), guild.id.0), Ok(c) => info!("Registered {} commands for guild {}", c.len(), guild.id.get()),
Err(why) => error!( Err(why) => error!(
"Could not register commands for guild {}: {:?}", "Could not register commands for guild {}: {:?}",
guild.id.0, why guild.id.get(), why
), ),
}; };
} }

View File

@@ -1,6 +1,6 @@
use diesel::prelude::*; use diesel::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use siren::ServiceError; use crate::error::SirenResult;
use crate::storage::{ use crate::storage::{
schema::messages::{self}, schema::messages::{self},
@@ -51,7 +51,7 @@ impl Default for QueryFilters {
} }
impl QueryMessage { impl QueryMessage {
pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> { pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> SirenResult<Vec<Self>> {
let mut conn = connection()?; let mut conn = connection()?;
let mut query = messages::table let mut query = messages::table
.limit(limit as i64) .limit(limit as i64)
@@ -93,7 +93,7 @@ impl QueryMessage {
Ok(messages) Ok(messages)
} }
pub fn get_count(fitlers: &QueryFilters) -> Result<i64, ServiceError> { pub fn get_count(fitlers: &QueryFilters) -> SirenResult<i64> {
let mut conn = connection()?; let mut conn = connection()?;
let mut query = messages::table.into_boxed(); let mut query = messages::table.into_boxed();
// Apply filters // Apply filters
@@ -129,7 +129,7 @@ impl QueryMessage {
Ok(count) Ok(count)
} }
pub fn insert(message: Self) -> Result<QueryMessage, ServiceError> { pub fn insert(message: Self) -> SirenResult<QueryMessage> {
let mut conn = connection()?; let mut conn = connection()?;
let message = diesel::insert_into(messages::table) let message = diesel::insert_into(messages::table)
.values(message) .values(message)

View File

@@ -1,6 +1,7 @@
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use serde_json::Value; use serde_json::Value;
use siren::ServiceError;
use crate::error::{SirenResult, Error as SirenError};
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GPTRole { pub enum GPTRole {
@@ -123,7 +124,7 @@ impl OAI {
pub async fn chat_completion( pub async fn chat_completion(
&self, &self,
request: ChatCompletionRequest, request: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, ServiceError> { ) -> SirenResult<ChatCompletionResponse> {
let url = format!("{}/chat/completions", self.base_url); let url = format!("{}/chat/completions", self.base_url);
let response = self let response = self
.client .client
@@ -142,7 +143,7 @@ impl OAI {
return Ok(response); return Ok(response);
}, },
ResponseEvent::ResponseError(error) => { ResponseEvent::ResponseError(error) => {
return Err(ServiceError { return Err(SirenError {
status: 500, status: 500,
message: format!("Error: {}", error.message.unwrap()), message: format!("Error: {}", error.message.unwrap()),
}); });
@@ -150,7 +151,7 @@ impl OAI {
} }
} }
Err(err) => { Err(err) => {
return Err(ServiceError { return Err(SirenError {
status: 500, status: 500,
message: format!("Error: {}", err), message: format!("Error: {}", err),
}) })

View File

@@ -1,7 +1,7 @@
use diesel::prelude::*; use diesel::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use siren::ServiceError;
use crate::error::SirenResult;
use crate::storage::connection; use crate::storage::connection;
use crate::storage::schema::spells::{self}; use crate::storage::schema::spells::{self};
use crate::dnd::{classes::AbilityType, conditions::ConditionType}; use crate::dnd::{classes::AbilityType, conditions::ConditionType};
@@ -65,7 +65,7 @@ impl Default for QueryFilters {
} }
impl QuerySpell { impl QuerySpell {
pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> { pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> SirenResult<Vec<Self>> {
let mut conn = connection()?; let mut conn = connection()?;
let mut query = spells::table.limit(limit as i64).into_boxed(); let mut query = spells::table.limit(limit as i64).into_boxed();
// Limit query to page and limit // Limit query to page and limit
@@ -147,7 +147,7 @@ impl QuerySpell {
Ok(spells) Ok(spells)
} }
pub fn get_count(filters: &QueryFilters) -> Result<i64, ServiceError> { pub fn get_count(filters: &QueryFilters) -> SirenResult<i64> {
let mut conn = connection()?; let mut conn = connection()?;
let mut query = spells::table.count().into_boxed(); let mut query = spells::table.count().into_boxed();
if let Some(name) = &filters.by_name { if let Some(name) = &filters.by_name {
@@ -223,7 +223,7 @@ impl QuerySpell {
Ok(count) Ok(count)
} }
pub fn get_by_id(id: i32) -> Result<Self, ServiceError> { pub fn get_by_id(id: i32) -> SirenResult<Self> {
let mut conn = connection()?; let mut conn = connection()?;
let spell = spells::table let spell = spells::table
.filter(spells::id.eq(id)) .filter(spells::id.eq(id))
@@ -231,7 +231,7 @@ impl QuerySpell {
Ok(spell) Ok(spell)
} }
pub fn delete(id: i32) -> Result<Self, ServiceError> { pub fn delete(id: i32) -> SirenResult<Self> {
let mut conn = connection()?; let mut conn = connection()?;
let spell = diesel::delete(spells::table.filter(spells::id.eq(id))).get_result(&mut conn)?; let spell = diesel::delete(spells::table.filter(spells::id.eq(id))).get_result(&mut conn)?;
Ok(spell) Ok(spell)
@@ -256,7 +256,7 @@ pub struct InsertSpell {
} }
impl InsertSpell { impl InsertSpell {
pub fn insert(spell: Self) -> Result<QuerySpell, ServiceError> { pub fn insert(spell: Self) -> SirenResult<QuerySpell> {
let mut conn = connection()?; let mut conn = connection()?;
let spell = diesel::insert_into(spells::table) let spell = diesel::insert_into(spells::table)
.values(spell) .values(spell)
@@ -264,7 +264,7 @@ impl InsertSpell {
Ok(spell) Ok(spell)
} }
pub fn update(id: i32, spell: Self) -> Result<QuerySpell, ServiceError> { pub fn update(id: i32, spell: Self) -> SirenResult<QuerySpell> {
let mut conn = connection()?; let mut conn = connection()?;
let spell = diesel::update(spells::table.filter(spells::id.eq(id))) let spell = diesel::update(spells::table.filter(spells::id.eq(id)))
.set(spell) .set(spell)

96
src/error.rs Normal file
View File

@@ -0,0 +1,96 @@
use std::fmt;
use diesel::result::Error as DieselError;
use serde::{Deserialize, Serialize};
pub type SirenResult<T> = Result<T, Error>;
#[derive(Debug, Deserialize, Serialize)]
pub struct Error {
pub status: u16,
pub message: String,
}
impl Error {
pub fn new(error_status_code: u16, error_message: String) -> Self {
Self {
status: error_status_code,
message: error_message,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.message.as_str())
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Self::new(500, format!("Unknown io error: {}", error))
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(error: std::string::FromUtf8Error) -> Self {
Self::new(500, format!("Unknown from utf8 error: {}", error))
}
}
impl From<DieselError> for Error {
fn from(error: DieselError) -> Self {
match error {
DieselError::DatabaseError(kind, err) => match kind {
diesel::result::DatabaseErrorKind::UniqueViolation => {
Self::new(409, err.message().to_string())
}
_ => Self::new(500, err.message().to_string()),
},
DieselError::NotFound => Self::new(404, "The record was not found".to_string()),
DieselError::SerializationError(err) => Self::new(422, err.to_string()),
err => Self::new(500, format!("Unknown database error: {}", err)),
}
}
}
impl From<reqwest::Error> for Error {
fn from(error: reqwest::Error) -> Self {
Self::new(500, format!("Unknown reqwest error: {}", error))
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self::new(500, format!("Unknown serde_json error: {}", error))
}
}
impl From<serenity::Error> for Error {
fn from(error: serenity::Error) -> Self {
Self::new(500, format!("Unknown serenity error: {}", error))
}
}
impl From<redis::RedisError> for Error {
fn from(error: redis::RedisError) -> Self {
Self::new(500, format!("Unknown redis error: {}", error))
}
}
impl From<uuid::Error> for Error {
fn from(error: uuid::Error) -> Self {
Self::new(500, format!("Unknown uuid error: {}", error))
}
}
impl From<std::env::VarError> for Error {
fn from(error: std::env::VarError) -> Self {
Self::new(500, format!("Unknown env error: {}", error))
}
}
impl From<songbird::error::JoinError> for Error {
fn from(error: songbird::error::JoinError) -> Self {
Self::new(500, format!("Unable to join channel: {}", error))
}
}

View File

@@ -1,117 +0,0 @@
use diesel::result::Error as DieselError;
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<redis::RedisError> for ServiceError {
fn from(error: redis::RedisError) -> ServiceError {
ServiceError::new(500, format!("Unknown redis 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))
}
}

View File

@@ -5,18 +5,24 @@ extern crate diesel_migrations;
use std::env; use std::env;
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::Arc; use std::sync::Arc;
use serenity::client::Cache;
use serenity::framework::StandardFramework;
use serenity::http::Http; use serenity::http::Http;
use serenity::prelude::*; use serenity::prelude::*;
use songbird::{SerenityInit, Songbird}; use songbird::{SerenityInit, Songbird};
use reqwest::Client as HttpClient;
use crate::bot::handler::Handler; use crate::bot::handler::Handler;
mod bot; mod bot;
mod dnd; mod dnd;
mod error;
mod storage; mod storage;
pub struct HttpKey;
impl TypeMapKey for HttpKey {
type Value = HttpClient;
}
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
dotenv::dotenv().ok(); dotenv::dotenv().ok();
@@ -27,25 +33,25 @@ async fn main() {
let intents: GatewayIntents = GatewayIntents::all(); let intents: GatewayIntents = GatewayIntents::all();
let http: Http = Http::new(&token); let http: Http = Http::new(&token);
let (owners, _bot_id) = match http.get_current_application_info().await { let (_owners, _bot_id) = match http.get_current_application_info().await {
Ok(info) => { Ok(info) => {
let mut owners: HashSet<serenity::model::id::UserId> = HashSet::new(); let mut owners: HashSet<serenity::model::id::UserId> = HashSet::new();
if let Some(team) = info.team { if let Some(team) = info.team {
owners.insert(team.owner_user_id); owners.insert(team.owner_user_id);
} else { } else {
owners.insert(info.owner.id); owners.insert(info.owner.unwrap().id);
} }
match http.get_current_user().await { match http.get_current_user().await {
Ok(bot) => (owners, bot.id), Ok(bot) => (owners, bot.id),
Err(why) => panic!("Could not access the bot id: {:?}", why), Err(why) => panic!("Could not access the bot id: {why:?}"),
} }
} }
Err(why) => panic!("Could not access application info: {:?}", why), Err(why) => panic!("Could not access application info: {why:?}"),
}; };
let handler = match env::var("OPENAI_API_KEY") { let handler = match env::var("OPENAI_API_KEY") {
Ok(token) => { Ok(token) => {
log::info!("Loaded OpenAI token"); log::info!("OpenAI functionality enabled");
let default_model = env::var("OPENAI_API_MODEL").unwrap_or("gpt-3.5-turbo".to_string()); let default_model = env::var("OPENAI_API_MODEL").unwrap_or("gpt-3.5-turbo".to_string());
Handler { Handler {
oai: Some(bot::oai::OAI { oai: Some(bot::oai::OAI {
@@ -61,7 +67,8 @@ async fn main() {
} }
} }
Err(err) => { Err(err) => {
log::warn!("Could not load OpenAI token: {}", err); log::trace!("No OPENAI_API_KEY found: {err}");
log::warn!("OpenAI functionality disabled");
Handler { oai: None } Handler { oai: None }
} }
}; };
@@ -70,8 +77,9 @@ async fn main() {
let mut client = Client::builder(token, intents) let mut client = Client::builder(token, intents)
.event_handler(handler) .event_handler(handler)
.framework(StandardFramework::new().configure(|c| c.owners(owners))) // .framework(StandardFramework::new().configure(|c| c.owners(owners)))
.register_songbird_with(Arc::clone(&songbird)) .register_songbird_with(Arc::clone(&songbird))
.type_map_insert::<HttpKey>(HttpClient::new())
.await .await
.expect("Error creating client"); .expect("Error creating client");
@@ -81,11 +89,4 @@ async fn main() {
if let Err(why) = client.start_autosharded().await { if let Err(why) = client.start_autosharded().await {
log::error!("Client error: {why:?}"); log::error!("Client error: {why:?}");
} }
}
pub struct AppState {
pub http: Arc<Http>,
pub cache: Arc<Cache>,
pub songbird: Arc<Songbird>,
} }

View File

@@ -1,7 +1,6 @@
use diesel::{r2d2::ConnectionManager as DieselConnectionManager, PgConnection}; use diesel::{r2d2::ConnectionManager as DieselConnectionManager, PgConnection};
use redis::{Client as RedisClient, aio::Connection as RedisConnection}; use redis::{aio::MultiplexedConnection, Client as RedisClient};
use siren::ServiceError; use crate::{diesel_migrations::MigrationHarness, error::{Error as SirenError, SirenResult}};
use crate::diesel_migrations::MigrationHarness;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use log::{error, info}; use log::{error, info};
use r2d2; use r2d2;
@@ -49,18 +48,18 @@ pub async fn init() {
}; };
} }
pub fn connection() -> Result<DbConnection, ServiceError> { pub fn connection() -> SirenResult<DbConnection> {
POOL POOL
.get() .get()
.map_err(|e| ServiceError::new(500, format!("Failed getting db connection: {}", e))) .map_err(|e| SirenError::new(500, format!("Failed getting db connection: {}", e)))
} }
pub fn redis_connection() -> Result<redis::Connection, ServiceError> { pub fn redis_connection() -> SirenResult<redis::Connection> {
let conn = REDIS.get_connection()?; let conn = REDIS.get_connection()?;
Ok(conn) Ok(conn)
} }
pub async fn redis_async_connection() -> Result<RedisConnection, ServiceError> { pub async fn redis_async_connection() -> SirenResult<MultiplexedConnection> {
let conn = REDIS.get_async_connection().await?; let conn = REDIS.get_multiplexed_async_connection().await?;
Ok(conn) Ok(conn)
} }