TrackQueues: Convenience methods and extension (#7)

* Adds a uuid field to tracks and handles to make it easier to identify and match event sources after the fact.
* Adds optional feature "builtin-queue" to expose a queue on every driver, as a convenience for users who can guarantee they'll need a queue for every driver/call.
* Adds methods to queues to allow access to the currently running track handle, remove a specified queue entry, as well as to mutate the underlying queue from a closure.
This commit is contained in:
Kyle Simpson
2020-11-16 08:57:54 +00:00
committed by GitHub
parent 047ce0379a
commit de652250d8
7 changed files with 387 additions and 119 deletions

View File

@@ -10,6 +10,7 @@ tracing-subscriber = "0.2"
tracing-futures = "0.2"
[dependencies.songbird]
features = ["builtin-queue"]
path = "../../../"
[dependencies.serenity]

View File

@@ -10,35 +10,32 @@
//! features = ["cache", "framework", "standard_framework", "voice"]
//! ```
use std::{
collections::HashMap,
env,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
time::Duration,
sync::{atomic::{AtomicUsize, Ordering}, Arc}
};
use serenity::{
async_trait,
client::{Client, Context, EventHandler},
http::Http,
framework::{
StandardFramework,
standard::{
Args, CommandResult,
macros::{command, group},
Args,
CommandResult,
},
StandardFramework,
},
model::{
channel::Message,
gateway::Ready,
misc::Mentionable,
prelude::{ChannelId, GuildId},
},
http::Http,
model::{channel::Message, gateway::Ready, misc::Mentionable, prelude::ChannelId},
Result as SerenityResult,
};
use songbird::{
input,
tracks::TrackQueue,
Event,
EventContext,
EventHandler as VoiceEventHandler,
@@ -46,15 +43,6 @@ use songbird::{
TrackEvent,
};
// This imports `typemap`'s `Key` as `TypeMapKey`.
use serenity::prelude::*;
struct VoiceQueueManager;
impl TypeMapKey for VoiceQueueManager {
type Value = Arc<Mutex<HashMap<GuildId, TrackQueue>>>;
}
struct Handler;
#[async_trait]
@@ -65,7 +53,9 @@ impl EventHandler for Handler {
}
#[group]
#[commands(deafen, join, leave, mute, play_fade, queue, skip, stop, ping, undeafen, unmute)]
#[commands(
deafen, join, leave, mute, play_fade, queue, skip, stop, ping, undeafen, unmute
)]
struct General;
#[tokio::main]
@@ -73,12 +63,10 @@ async fn main() {
tracing_subscriber::fmt::init();
// Configure the client with your Discord bot token in the environment.
let token = env::var("DISCORD_TOKEN")
.expect("Expected a token in the environment");
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
let framework = StandardFramework::new()
.configure(|c| c
.prefix("~"))
.configure(|c| c.prefix("~"))
.group(&GENERAL_GROUP);
let mut client = Client::builder(&token)
@@ -88,15 +76,10 @@ async fn main() {
.await
.expect("Err creating client");
// Obtain a lock to the data owned by the client, and insert the client's
// voice manager into it. This allows the voice manager to be accessible by
// event handlers and framework commands.
{
let mut data = client.data.write().await;
data.insert::<VoiceQueueManager>(Arc::new(Mutex::new(HashMap::new())));
}
let _ = client.start().await.map_err(|why| println!("Client ended: {:?}", why));
let _ = client
.start()
.await
.map_err(|why| println!("Client ended: {:?}", why));
}
#[command]
@@ -104,8 +87,10 @@ async fn deafen(ctx: &Context, msg: &Message) -> CommandResult {
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let manager = songbird::get(ctx).await
.expect("Songbird Voice client placed in at initialisation.").clone();
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
let handler_lock = match manager.get(guild_id) {
Some(handler) => handler,
@@ -122,7 +107,11 @@ async fn deafen(ctx: &Context, msg: &Message) -> CommandResult {
check_msg(msg.channel_id.say(&ctx.http, "Already deafened").await);
} else {
if let Err(e) = handler.deafen(true).await {
check_msg(msg.channel_id.say(&ctx.http, format!("Failed: {:?}", e)).await);
check_msg(
msg.channel_id
.say(&ctx.http, format!("Failed: {:?}", e))
.await,
);
}
check_msg(msg.channel_id.say(&ctx.http, "Deafened").await);
@@ -138,26 +127,32 @@ async fn join(ctx: &Context, msg: &Message) -> CommandResult {
let guild_id = guild.id;
let channel_id = guild
.voice_states.get(&msg.author.id)
.voice_states
.get(&msg.author.id)
.and_then(|voice_state| voice_state.channel_id);
let connect_to = match channel_id {
Some(channel) => channel,
None => {
check_msg(msg.reply(ctx, "Not in a voice channel").await);
return Ok(());
}
},
};
let manager = songbird::get(ctx).await
.expect("Songbird Voice client placed in at initialisation.").clone();
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
let (handle_lock, success) = manager.join(guild_id, connect_to).await;
if let Ok(_channel) = success {
check_msg(msg.channel_id.say(&ctx.http, &format!("Joined {}", connect_to.mention())).await);
check_msg(
msg.channel_id
.say(&ctx.http, &format!("Joined {}", connect_to.mention()))
.await,
);
let chan_id = msg.channel_id;
@@ -167,17 +162,28 @@ async fn join(ctx: &Context, msg: &Message) -> CommandResult {
handle.add_global_event(
Event::Track(TrackEvent::End),
TrackEndNotifier { chan_id, http: send_http },
TrackEndNotifier {
chan_id,
http: send_http,
},
);
let send_http = ctx.http.clone();
handle.add_global_event(
Event::Periodic(Duration::from_secs(60), None),
ChannelDurationNotifier { chan_id, count: Default::default(), http: send_http },
ChannelDurationNotifier {
chan_id,
count: Default::default(),
http: send_http,
},
);
} else {
check_msg(msg.channel_id.say(&ctx.http, "Error joining the channel").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Error joining the channel")
.await,
);
}
Ok(())
@@ -192,7 +198,11 @@ struct TrackEndNotifier {
impl VoiceEventHandler for TrackEndNotifier {
async fn act(&self, ctx: &EventContext<'_>) -> Option<Event> {
if let EventContext::Track(track_list) = ctx {
check_msg(self.chan_id.say(&self.http, &format!("Tracks ended: {}.", track_list.len())).await);
check_msg(
self.chan_id
.say(&self.http, &format!("Tracks ended: {}.", track_list.len()))
.await,
);
}
None
@@ -209,7 +219,17 @@ struct ChannelDurationNotifier {
impl VoiceEventHandler for ChannelDurationNotifier {
async fn act(&self, _ctx: &EventContext<'_>) -> Option<Event> {
let count_before = self.count.fetch_add(1, Ordering::Relaxed);
check_msg(self.chan_id.say(&self.http, &format!("I've been in this channel for {} minutes!", count_before + 1)).await);
check_msg(
self.chan_id
.say(
&self.http,
&format!(
"I've been in this channel for {} minutes!",
count_before + 1
),
)
.await,
);
None
}
@@ -221,13 +241,19 @@ async fn leave(ctx: &Context, msg: &Message) -> CommandResult {
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let manager = songbird::get(ctx).await
.expect("Songbird Voice client placed in at initialisation.").clone();
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
let has_handler = manager.get(guild_id).is_some();
if has_handler {
if let Err(e) = manager.remove(guild_id).await {
check_msg(msg.channel_id.say(&ctx.http, format!("Failed: {:?}", e)).await);
check_msg(
msg.channel_id
.say(&ctx.http, format!("Failed: {:?}", e))
.await,
);
}
check_msg(msg.channel_id.say(&ctx.http, "Left voice channel").await);
@@ -244,8 +270,10 @@ async fn mute(ctx: &Context, msg: &Message) -> CommandResult {
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let manager = songbird::get(ctx).await
.expect("Songbird Voice client placed in at initialisation.").clone();
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
let handler_lock = match manager.get(guild_id) {
Some(handler) => handler,
@@ -262,7 +290,11 @@ async fn mute(ctx: &Context, msg: &Message) -> CommandResult {
check_msg(msg.channel_id.say(&ctx.http, "Already muted").await);
} else {
if let Err(e) = handler.mute(true).await {
check_msg(msg.channel_id.say(&ctx.http, format!("Failed: {:?}", e)).await);
check_msg(
msg.channel_id
.say(&ctx.http, format!("Failed: {:?}", e))
.await,
);
}
check_msg(msg.channel_id.say(&ctx.http, "Now muted").await);
@@ -284,14 +316,22 @@ async fn play_fade(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul
let url = match args.single::<String>() {
Ok(url) => url,
Err(_) => {
check_msg(msg.channel_id.say(&ctx.http, "Must provide a URL to a video or audio").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Must provide a URL to a video or audio")
.await,
);
return Ok(());
},
};
if !url.starts_with("http") {
check_msg(msg.channel_id.say(&ctx.http, "Must provide a valid URL").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Must provide a valid URL")
.await,
);
return Ok(());
}
@@ -299,8 +339,10 @@ async fn play_fade(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let manager = songbird::get(ctx).await
.expect("Songbird Voice client placed in at initialisation.").clone();
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
if let Some(handler_lock) = manager.get(guild_id) {
let mut handler = handler_lock.lock().await;
@@ -318,7 +360,7 @@ async fn play_fade(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul
// This handler object will allow you to, as needed,
// control the audio track via events and further commands.
let song = handler.play_source(source.into());
let song = handler.play_source(source);
let send_http = ctx.http.clone();
let chan_id = msg.channel_id;
@@ -326,21 +368,31 @@ async fn play_fade(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul
// periodically make a track quieter until it can be no longer heard.
let _ = song.add_event(
Event::Periodic(Duration::from_secs(5), Some(Duration::from_secs(7))),
SongFader { chan_id, http: send_http },
SongFader {
chan_id,
http: send_http,
},
);
let send_http = ctx.http.clone();
// This shows how to fire an event once an audio track completes,
// either due to hitting the end of the bytestream or stopped by user code.
let _ = song.add_event(
Event::Track(TrackEvent::End),
SongEndNotifier { chan_id, http: send_http },
SongEndNotifier {
chan_id,
http: send_http,
},
);
check_msg(msg.channel_id.say(&ctx.http, "Playing song").await);
} else {
check_msg(msg.channel_id.say(&ctx.http, "Not in a voice channel to play in").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Not in a voice channel to play in")
.await,
);
}
Ok(())
@@ -379,7 +431,11 @@ struct SongEndNotifier {
#[async_trait]
impl VoiceEventHandler for SongEndNotifier {
async fn act(&self, _ctx: &EventContext<'_>) -> Option<Event> {
check_msg(self.chan_id.say(&self.http, "Song faded out completely!").await);
check_msg(
self.chan_id
.say(&self.http, "Song faded out completely!")
.await,
);
None
}
@@ -391,14 +447,22 @@ async fn queue(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let url = match args.single::<String>() {
Ok(url) => url,
Err(_) => {
check_msg(msg.channel_id.say(&ctx.http, "Must provide a URL to a video or audio").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Must provide a URL to a video or audio")
.await,
);
return Ok(());
},
};
if !url.starts_with("http") {
check_msg(msg.channel_id.say(&ctx.http, "Must provide a valid URL").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Must provide a valid URL")
.await,
);
return Ok(());
}
@@ -406,10 +470,10 @@ async fn queue(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let manager = songbird::get(ctx).await
.expect("Songbird Voice client placed in at initialisation.").clone();
let queues_lock = ctx.data.read().await.get::<VoiceQueueManager>().cloned().expect("Expected VoiceQueueManager in ShareMap.");
let mut track_queues = queues_lock.lock().await;
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
if let Some(handler_lock) = manager.get(guild_id) {
let mut handler = handler_lock.lock().await;
@@ -424,16 +488,22 @@ async fn queue(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
},
};
// We need to ensure that this guild has a TrackQueue created for it.
let queue = track_queues.entry(guild_id)
.or_default();
handler.enqueue_source(source);
// Queueing a track is this easy!
queue.add_source(source, &mut handler);
check_msg(msg.channel_id.say(&ctx.http, format!("Added song to queue: position {}", queue.len())).await);
check_msg(
msg.channel_id
.say(
&ctx.http,
format!("Added song to queue: position {}", handler.queue().len()),
)
.await,
);
} else {
check_msg(msg.channel_id.say(&ctx.http, "Not in a voice channel to play in").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Not in a voice channel to play in")
.await,
);
}
Ok(())
@@ -445,15 +515,30 @@ async fn skip(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let queues_lock = ctx.data.read().await.get::<VoiceQueueManager>().cloned().expect("Expected VoiceQueueManager in ShareMap.");
let mut track_queues = queues_lock.lock().await;
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
if let Some(queue) = track_queues.get_mut(&guild_id) {
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
let queue = handler.queue();
let _ = queue.skip();
check_msg(msg.channel_id.say(&ctx.http, format!("Song skipped: {} in queue.", queue.len())).await);
check_msg(
msg.channel_id
.say(
&ctx.http,
format!("Song skipped: {} in queue.", queue.len()),
)
.await,
);
} else {
check_msg(msg.channel_id.say(&ctx.http, "Not in a voice channel to play in").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Not in a voice channel to play in")
.await,
);
}
Ok(())
@@ -465,15 +550,23 @@ async fn stop(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let queues_lock = ctx.data.read().await.get::<VoiceQueueManager>().cloned().expect("Expected VoiceQueueManager in ShareMap.");
let mut track_queues = queues_lock.lock().await;
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
if let Some(queue) = track_queues.get_mut(&guild_id) {
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
let queue = handler.queue();
let _ = queue.stop();
check_msg(msg.channel_id.say(&ctx.http, "Queue cleared.").await);
} else {
check_msg(msg.channel_id.say(&ctx.http, "Not in a voice channel to play in").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Not in a voice channel to play in")
.await,
);
}
Ok(())
@@ -485,18 +578,28 @@ async fn undeafen(ctx: &Context, msg: &Message) -> CommandResult {
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let manager = songbird::get(ctx).await
.expect("Songbird Voice client placed in at initialisation.").clone();
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
if let Some(handler_lock) = manager.get(guild_id) {
let mut handler = handler_lock.lock().await;
if let Err(e) = handler.deafen(false).await {
check_msg(msg.channel_id.say(&ctx.http, format!("Failed: {:?}", e)).await);
check_msg(
msg.channel_id
.say(&ctx.http, format!("Failed: {:?}", e))
.await,
);
}
check_msg(msg.channel_id.say(&ctx.http, "Undeafened").await);
} else {
check_msg(msg.channel_id.say(&ctx.http, "Not in a voice channel to undeafen in").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Not in a voice channel to undeafen in")
.await,
);
}
Ok(())
@@ -507,18 +610,28 @@ async fn undeafen(ctx: &Context, msg: &Message) -> CommandResult {
async fn unmute(ctx: &Context, msg: &Message) -> CommandResult {
let guild = msg.guild(&ctx.cache).await.unwrap();
let guild_id = guild.id;
let manager = songbird::get(ctx).await
.expect("Songbird Voice client placed in at initialisation.").clone();
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialisation.")
.clone();
if let Some(handler_lock) = manager.get(guild_id) {
let mut handler = handler_lock.lock().await;
if let Err(e) = handler.mute(false).await {
check_msg(msg.channel_id.say(&ctx.http, format!("Failed: {:?}", e)).await);
check_msg(
msg.channel_id
.say(&ctx.http, format!("Failed: {:?}", e))
.await,
);
}
check_msg(msg.channel_id.say(&ctx.http, "Unmuted").await);
} else {
check_msg(msg.channel_id.say(&ctx.http, "Not in a voice channel to unmute in").await);
check_msg(
msg.channel_id
.say(&ctx.http, "Not in a voice channel to unmute in")
.await,
);
}
Ok(())