InactiveHandler on track end

This commit is contained in:
2023-07-05 19:23:26 -04:00
parent 6f66564377
commit 7f89c7a4be
3 changed files with 62 additions and 18 deletions

View File

@@ -6,7 +6,7 @@ use serenity::model::application::interaction::{InteractionResponseType, applica
use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User;
use serenity::prelude::*;
use songbird::Call;
use songbird::{Call, Songbird};
use songbird::input::{Restartable, Input, Metadata, error::Error as SongbirdError};
pub mod pause;
@@ -39,7 +39,7 @@ pub async fn join(ctx: &Context, guild_id_option: &Option<GuildId>, user: &User)
};
debug!("<{}> Joining channel {}", guild_id.0, channel_id);
let manager = songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization").clone();
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),
@@ -63,7 +63,7 @@ pub async fn leave(ctx: &Context, guild_id_option: &Option<GuildId>) -> Result<(
}
};
let manager = songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization").clone();
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 {
@@ -161,3 +161,14 @@ fn is_valid_url(url: &str) -> bool {
Err(_) => return false
}
}
/// Gets the Songbird voice client.
///
/// # Arguments
/// - ctx - The context of the command.
///
/// # Returns
/// Arc<Songbird> - The Songbird voice client.
pub async fn get_songbird(ctx: &Context) -> Arc<Songbird> {
songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization")
}

View File

@@ -1,10 +1,11 @@
use log::{debug, warn, error};
use serenity::prelude::*;
use serenity::{prelude::*, async_trait};
use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use songbird::EventHandler;
use crate::commands::audio::{join, leave, add_song};
use crate::commands::audio::{join, leave, add_song, get_songbird};
use super::{create_response, edit_response};
@@ -58,15 +59,22 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
};
debug!("Play command executed with track: {:?}", track_url);
let manager = songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization").clone();
let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) {
match add_song(handler_lock, &track_url, true).await {
let is_queue_empty = {
let call_handler = handler_lock.lock().await;
call_handler.queue().is_empty()
};
match add_song(handler_lock.clone(), &track_url, is_queue_empty).await {
Ok(added_song) => {
let track_title = added_song.title.unwrap();
debug!("Added song: {}", track_title);
if let Err(why) = edit_response(&ctx, &command, format!("Added song to queue: {}", track_title)).await {
error!("Failed to edit response message: {}", why);
}
let mut handler = handler_lock.lock().await;
handler.remove_all_global_events();
handler.add_global_event(songbird::Event::Track(songbird::TrackEvent::End), InactiveHandler { guild_id, call: manager })
}
Err(why) => {
warn!("Failed to add song: {}", why);
@@ -83,7 +91,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
},
Err(err) => {
warn!("{}", err);
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await {
error!("Failed to edit response message: {}", why);
}
}
@@ -98,3 +106,24 @@ pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicatio
.required(true)
})
}
struct InactiveHandler {
pub call: std::sync::Arc<songbird::Songbird>,
pub guild_id: serenity::model::id::GuildId
}
#[async_trait]
impl EventHandler for InactiveHandler {
async fn act(&self, ctx: &songbird::events::EventContext<'_>) -> Option<songbird::events::Event> {
if let songbird::EventContext::Track(track_list) = ctx {
if track_list.is_empty() {
if let Some(call) = self.call.get(self.guild_id) {
debug!("Track list is empty; leaving voice channel");
let mut handler = call.lock().await;
handler.leave().await.unwrap();
}
}
}
None
}
}