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