Changing bot commands to be used by endpoints
This commit is contained in:
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user