Changing bot commands to be used by endpoints

This commit is contained in:
Benjamin Sherriff
2023-10-06 23:34:25 -04:00
parent cb1fd182f1
commit 3ca91c7765
11 changed files with 133 additions and 125 deletions

View File

@@ -0,0 +1 @@
DROP TABLE guilds;

View File

@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS guilds (
id BIGINT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
volume INTEGER NOT NULL
);

View File

@@ -3,6 +3,7 @@ use std::sync::Arc;
use log::debug;
use serenity::client::Cache;
use serenity::model::application::interaction::{InteractionResponseType, application_command::ApplicationCommandInteraction};
use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User;
@@ -29,16 +30,7 @@ pub struct AudioConfig {
pub volume: f32
}
/// Joins a Discord voice channel.
///
/// # Arguments
/// - ctx - The context of the command.
/// - guild_id_option - The guild ID of the guild to join.
/// - user - The user that is requesting to join the voice channel.
///
/// # Returns
/// Result<(), String> - Ok if the bot successfully joined the voice channel, Err if there was an error.
pub async fn join(ctx: &Context, guild_id_option: &Option<GuildId>, user: &User) -> Result<(), String> {
pub async fn join(cache: &Arc<Cache>, manager: Arc<Songbird>, guild_id_option: &Option<GuildId>, user: &User) -> Result<(), String> {
let guild_id = match guild_id_option {
Some(g) => g,
None => {
@@ -46,13 +38,12 @@ pub async fn join(ctx: &Context, guild_id_option: &Option<GuildId>, user: &User)
}
};
let channel_id = match find_voice_channel(&ctx, &guild_id, &user) {
let channel_id = match find_voice_channel(cache, &guild_id, &user) {
Ok(channel) => channel,
Err(err) => return Err(format!("{}", err))
};
debug!("<{}> Joining channel {}", guild_id.0, channel_id);
let manager = get_songbird(ctx).await;
let (_handle_lock, success) = manager.join(guild_id.to_owned(), channel_id.to_owned()).await;
match success {
Ok(s) => Ok(s),
@@ -60,15 +51,7 @@ pub async fn join(ctx: &Context, guild_id_option: &Option<GuildId>, user: &User)
}
}
/// Leaves a Discord voice channel.
///
/// # Arguments
/// - ctx - The context of the command.
/// - guild_id_option - The guild ID of the guild to leave.
///
/// # Returns
/// Result<(), String> - Ok if the bot successfully left the voice channel, Err if there was an error.
pub async fn leave(ctx: &Context, guild_id_option: &Option<GuildId>) -> Result<(), String> {
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 => {
@@ -76,7 +59,6 @@ pub async fn leave(ctx: &Context, guild_id_option: &Option<GuildId>) -> Result<(
}
};
let manager = get_songbird(ctx).await;
if manager.get(*guild_id).is_some() {
debug!("<{}> Disconnecting from channel", guild_id.0);
if let Err(e) = manager.remove(*guild_id).await {
@@ -86,17 +68,8 @@ pub async fn leave(ctx: &Context, guild_id_option: &Option<GuildId>) -> Result<(
Ok(())
}
/// Finds the voice channel that the user is in.
///
/// # Arguments
/// - ctx - The context of the command.
/// - guild_id - The guild ID of the guild to search.
/// - user - The user to search for.
///
/// # Returns
/// Result<ChannelId, String> - Ok if the user is in a voice channel, Err if the user is not in a voice channel.
fn find_voice_channel(ctx: &Context, guild_id: &GuildId, user: &User) -> Result<ChannelId, String> {
let guild = match guild_id.to_guild_cached(ctx.cache.to_owned()) {
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"))
};
@@ -107,15 +80,6 @@ fn find_voice_channel(ctx: &Context, guild_id: &GuildId, user: &User) -> Result<
}
}
/// Creates a response to an interaction.
///
/// # Arguments
/// - ctx - The context of the command.
/// - command - The command that was sent.
/// - content - The content of the response.
///
/// # Returns
/// Result<(), SerenityError> - Ok if the response was created successfully, Err if there was an error.
pub async fn create_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<(), SerenityError> {
command.create_interaction_response(&ctx.http, |response: &mut serenity::builder::CreateInteractionResponse<'_>| {
response
@@ -124,31 +88,13 @@ pub async fn create_response(ctx: &Context, command: &ApplicationCommandInteract
}).await
}
/// Edits a response to an interaction.
///
/// # Arguments
/// - ctx - The context of the command.
/// - command - The command that was sent.
/// - content - The content of the response.
///
/// # Returns
/// Result<Message, SerenityError> - Ok if the response was edited successfully, Err if there was an error.
pub async fn edit_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<serenity::model::channel::Message, SerenityError> {
command.edit_original_interaction_response(&ctx.http, |response: &mut serenity::builder::EditInteractionResponse| {
response.content(content)
}).await
}
/// Adds a song to the queue.
///
/// # Arguments
/// - call - The call to add the song to.
/// - url - The URL of the song to add.
/// - lazy - Whether or not to lazy load the song.
///
/// # Returns
/// Result<Metadata, SongbirdError> - Ok if the song was added successfully, Err if there was an error.
pub async fn add_song(call: Arc<Mutex<Call>>, url: &str, lazy: bool, audio_config: Option<&AudioConfig>) -> Result<Metadata, SongbirdError> {
pub async fn add_song(call: Arc<Mutex<Call>>, url: &str, lazy: bool, volume: Option<f32>) -> Result<Metadata, SongbirdError> {
let source = if is_valid_url(url) {
Restartable::ytdl(url.to_owned(), lazy).await?
} else {
@@ -158,19 +104,12 @@ pub async fn add_song(call: Arc<Mutex<Call>>, url: &str, lazy: bool, audio_confi
let track: Input = source.into();
let metadata = *track.metadata.clone();
let track_handle = handler.enqueue_source(track);
if let Some(ac) = audio_config {
let _ = track_handle.set_volume(ac.volume);
if let Some(volume) = volume {
let _ = track_handle.set_volume(volume);
}
Ok(metadata)
}
/// Checks if a string is a valid URL.
///
/// # Arguments
/// - url - The string to check.
///
/// # Returns
/// bool - True if the string is a valid URL, false if it is not.
fn is_valid_url(url: &str) -> bool {
match url.parse::<reqwest::Url>() {
Ok(_) => return true,
@@ -178,13 +117,6 @@ fn is_valid_url(url: &str) -> bool {
}
}
/// Gets the Songbird voice client.
///
/// # Arguments
/// - ctx - The context of the command.
///
/// # Returns
/// Arc<Songbird> - The Songbird voice client.
pub async fn get_songbird(ctx: &Context) -> Arc<Songbird> {
songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization")
}

View File

@@ -1,11 +1,18 @@
use std::sync::Arc;
use log::{debug, warn, error};
use serenity::model::prelude::GuildId;
use serenity::model::user::User;
use serenity::{prelude::*, async_trait};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use siren::ServiceError;
use songbird::EventHandler;
use crate::bot::commands::audio::{join, leave, add_song, get_songbird, AudioConfigs};
use crate::AppState;
use crate::bot::commands::audio::{join, leave, add_song, get_songbird};
use crate::db::guilds::QueryGuild;
use super::{create_response, edit_response};
@@ -46,7 +53,8 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
return;
}
match join(&ctx, &command.guild_id, &command.user).await {
let manager = get_songbird(ctx).await;
match join(&ctx.cache, manager,&command.guild_id, &command.user).await {
Ok(_) => {
let guild_id = match command.guild_id {
Some(g) => g,
@@ -65,12 +73,8 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let call_handler = handler_lock.lock().await;
call_handler.queue().is_empty()
};
let audio_config = {
let data_read = ctx.data.read().await;
data_read.get::<AudioConfigs>().expect("Expected AudioConfigs in TypeMap.").clone()
};
let ac = audio_config.read().await;
match add_song(handler_lock.clone(), &track_url, is_queue_empty, ac.get(&guild_id)).await {
let guild = QueryGuild::get(guild_id.0 as i64).unwrap();
match add_song(handler_lock.clone(), &track_url, is_queue_empty, Some(guild.volume)).await {
Ok(added_song) => {
let track_title = added_song.title.unwrap();
debug!("Added track: {}", track_title);
@@ -86,7 +90,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
if let Err(why) = edit_response(&ctx, &command, format!("Failed to add song: {}", why)).await {
error!("Failed to edit response message: {}", why);
}
if let Err(why) = leave(&ctx, &command.guild_id).await {
if let Err(why) = leave(manager, &command.guild_id).await {
error!("Failed to leave voice channel: {}", why);
}
return;
@@ -103,6 +107,40 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
}
pub async fn play(state: Arc<AppState>, guild_id: Option<GuildId>, user: &User, track_url: String) -> Result<(), ServiceError> {
match join(&state.cache, Arc::clone(&state.songbird), &guild_id, user).await {
Ok(_) => {
let guild_id = match guild_id {
Some(g) => g,
None => {
return Err(ServiceError {
status: 422,
message: "No guild ID set".to_string()
});
}
};
if let Some(handler_lock) = state.songbird.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)?;
match add_song(handler_lock.clone(), &track_url, is_queue_empty, Some(guild.volume)).await {
Ok(_) => {},
Err(_) => {}
}
}
Ok(())
},
Err(err) => {
return Err(ServiceError {
status: 422,
message: err.to_string()
});
}
}
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("play").description("Plays the given track").create_option(|option| { option
.name("track")

View File

@@ -4,7 +4,9 @@ use serenity::prelude::*;
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use super::{get_songbird, create_response, edit_response, AudioConfigs, AudioConfig};
use crate::db::guilds::InsertGuild;
use super::{get_songbird, create_response, edit_response};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Get the volume
@@ -55,14 +57,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
return;
}
};
let audio_config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<AudioConfigs>().expect("Expected AudioConfigs in TypeMap.").clone()
};
{
let mut audio_configs = audio_config_lock.write().await;
*audio_configs.entry(guild_id).or_insert(AudioConfig { volume: 1.0 }) = AudioConfig { volume: bound_volume };
}
let _ = InsertGuild::update_audio(guild_id.0 as i64, bound_volume);
let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;

View File

@@ -5,8 +5,10 @@ use serenity::model::gateway::Ready;
use serenity::model::channel::Message;
use serenity::prelude::*;
use crate::db::guilds::InsertGuild;
use super::commands;
use super::commands::audio::{AudioConfigs, create_response, AudioConfig};
use super::commands::audio::create_response;
pub struct Handler {
// Open AI Config
@@ -72,14 +74,7 @@ impl EventHandler for Handler {
warn!("No ready guilds found");
}
for guild in ready.guilds {
let audio_config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<AudioConfigs>().expect("Expected AudioConfigs in TypeMap.").clone()
};
{
let mut audio_configs = audio_config_lock.write().await;
let _ = audio_configs.insert(guild.id, AudioConfig { volume: 1.0 });
}
let _ = InsertGuild::insert(InsertGuild { id: (guild.id.0 as i64), name: "".to_string(), volume: 100.0 });
let commands = guild.id.set_application_commands(&ctx.http, |commands| {
commands.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::ping::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::play::register(command) })

View File

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

View File

@@ -0,0 +1,43 @@
use diesel::prelude::*;
use serde::{Serialize, Deserialize};
use siren::ServiceError;
use crate::db::{schema::guilds, connection};
#[derive(Queryable, QueryableByName, Serialize, Deserialize)]
#[diesel(table_name = guilds)]
pub struct QueryGuild {
pub id: i64,
pub name: String,
pub volume: f32
}
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 name: String,
pub volume: f32
}
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: f32) -> 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)
}
}

View File

@@ -11,6 +11,7 @@ pub mod bestiary;
pub mod classes;
pub mod conditions;
pub mod feats;
pub mod guilds;
pub mod items;
pub mod messages;
pub mod options;

View File

@@ -30,3 +30,11 @@ diesel::table! {
data -> Jsonb
}
}
diesel::table! {
guilds (id) {
id -> BigInt,
name -> Text,
volume -> Float,
}
}

View File

@@ -3,19 +3,18 @@ extern crate diesel;
extern crate diesel_migrations;
use std::env;
use std::collections::{HashSet, HashMap};
use std::collections::HashSet;
use std::sync::Arc;
use bot::commands::audio::AudioConfig;
use log::{error, warn, info};
use serenity::client::Cache;
use serenity::framework::StandardFramework;
use serenity::http::Http;
use serenity::model::prelude::GuildId;
use serenity::prelude::*;
use songbird::{SerenityInit, Songbird};
use actix_cors::Cors;
use actix_web::{HttpServer, App, web};
use crate::bot::{commands::{oai::GPTModel, audio::AudioConfigs}, handler::Handler};
use crate::bot::{commands::oai::GPTModel, handler::Handler};
use dotenv::dotenv;
@@ -74,35 +73,23 @@ async fn main() -> std::io::Result<()> {
}
};
// let songbird = Songbird::serenity_from_config(songbird::Config::default().decode_mode(songbird::driver::DecodeMode::Decode));
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))
// .register_songbird_from_config(songbird::Config::default().decode_mode(songbird::driver::DecodeMode::Decode))
.register_songbird()
.await
.expect("Error creating client");
let audio_configs: Arc<RwLock<HashMap<GuildId, AudioConfig>>> = Arc::new(RwLock::new(HashMap::default()));
{
let mut data = client.data.write().await;
data.insert::<AudioConfigs>(Arc::clone(&audio_configs));
}
let http = Arc::clone(&client.cache_and_http.http);
// let cache_http = Arc::clone(&client.cache_and_http.clone());
// let data = Arc::clone(&client.data.clone());
// let t = songbird::Config::default().decode_mode(songbird::driver::DecodeMode::Decode);
let cache = Arc::clone(&client.cache_and_http.cache);
let app_data = Arc::new(AppState {
http,
songbird: Arc::clone(&songbird),
audio_configs
cache,
songbird: Arc::clone(&songbird)
});
@@ -153,6 +140,6 @@ async fn main() -> std::io::Result<()> {
pub struct AppState {
pub http: Arc<Http>,
pub songbird: Arc<Songbird>,
pub audio_configs: Arc<RwLock<HashMap<GuildId, AudioConfig>>>
pub cache: Arc<Cache>,
pub songbird: Arc<Songbird>
}