Compare commits
12 Commits
b19f6e552c
...
cleanup
| Author | SHA1 | Date | |
|---|---|---|---|
|
4a69e0f578
|
|||
|
cad6cf22fa
|
|||
|
9f0e934f92
|
|||
|
92be6c26a6
|
|||
|
c5d9c49452
|
|||
|
dbaf1a1374
|
|||
|
c0d9f6cad5
|
|||
|
1aa0efc4a6
|
|||
|
ab7f56fe05
|
|||
| feccbebd4d | |||
| d6a54dfc06 | |||
|
fa17ed75f6
|
@@ -5,6 +5,9 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
|
||||||
|
paths-ignore:
|
||||||
|
- 'README.md'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
release-image:
|
release-image:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -26,6 +29,5 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
platforms: |
|
platforms: |
|
||||||
linux/amd64
|
linux/amd64
|
||||||
linux/arm64
|
|
||||||
push: true
|
push: true
|
||||||
tags: jheuel/ohrwurm:latest
|
tags: jheuel/ohrwurm:latest
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ twilight-util = { version = "0.15", features=["builder"] }
|
|||||||
dotenv = "0.15.0"
|
dotenv = "0.15.0"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
url = "2.5.0"
|
url = "2.5.1"
|
||||||
anyhow = "1.0.86"
|
anyhow = "1.0.86"
|
||||||
dashmap = "5.5.3"
|
dashmap = "5.5.3"
|
||||||
async-trait = "0.1.80"
|
async-trait = "0.1.80"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
Ohrwurm is a user-friendly bot designed to play music in Discord voice chats. Once added to your server, you can request a song using the command `/play {query}`, where query can be a URL to a YouTube video or playlist, or a simple search term. The bot will fetch the song and start playing it. You can pause the music with `/pause`, resume playback with `/resume`, and stop and clear the queue with `/stop`. If the bot is alone in a voice chat, it will automatically leave, but you can also manually make it leave with the `/leave` command.
|
Ohrwurm is a user-friendly bot designed to play music in Discord voice chats. Once added to your server, you can request a song using the command `/play {query}`, where query can be a URL to a YouTube video or playlist, or a simple search term. The bot will fetch the song and start playing it. You can pause the music with `/pause`, resume playback with `/resume`, and stop and clear the queue with `/stop`. If the bot is alone in a voice chat, it will automatically leave, but you can also manually make it leave with the `/leave` command.
|
||||||
|
|
||||||
# Deployment
|
# Deployment
|
||||||
To deploy Ohrwurm with Docker, you can use the [provided Docker](https://hub.docker.com/r/jheuel/ohrwurm) image:
|
To deploy Ohrwurm with Docker, you can use the [provided Docker image](https://hub.docker.com/r/jheuel/ohrwurm):
|
||||||
```bash
|
```bash
|
||||||
docker run -d \
|
docker run -d \
|
||||||
--name ohrwurm \
|
--name ohrwurm \
|
||||||
|
|||||||
@@ -1,2 +1,20 @@
|
|||||||
|
#[allow(dead_code)]
|
||||||
pub(crate) const BLURPLE: u32 = 0x58_65_F2;
|
pub(crate) const BLURPLE: u32 = 0x58_65_F2;
|
||||||
|
#[allow(dead_code)]
|
||||||
pub(crate) const YELLOW: u32 = 0xFE_E7_5C;
|
pub(crate) const YELLOW: u32 = 0xFE_E7_5C;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const WHITE: u32 = 0xFF_FF_FF;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const GREYPLE: u32 = 0x99_AA_B5;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const BLACK: u32 = 0x23_27_2A;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const DARK_BUT_NOT_BLACK: u32 = 0x2C_2F_33;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const NOT_QUITE_BLACK: u32 = 0x23_27_2A;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const GREEN: u32 = 0x57_F2_87;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const FUCHSIA: u32 = 0xEB_45_9E;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const RED: u32 = 0xED_42_45;
|
||||||
|
|||||||
@@ -38,6 +38,9 @@ pub(crate) async fn join_channel(
|
|||||||
call.deafen(true).await?;
|
call.deafen(true).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// create guild config
|
||||||
|
state.guild_settings.entry(guild_id).or_default();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,56 @@
|
|||||||
use crate::state::State;
|
use crate::state::{State, StateRef};
|
||||||
use std::error::Error;
|
use anyhow::Context;
|
||||||
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
use std::{error::Error, sync::Arc};
|
||||||
|
use twilight_model::{
|
||||||
|
gateway::payload::incoming::InteractionCreate,
|
||||||
|
id::{marker::GuildMarker, Id},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(crate) async fn leave_if_alone(
|
||||||
|
guild_id: Id<GuildMarker>,
|
||||||
|
state: State,
|
||||||
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
|
let user = state
|
||||||
|
.cache
|
||||||
|
.current_user()
|
||||||
|
.context("Cannot get current user")?;
|
||||||
|
let user_voice_state = state
|
||||||
|
.cache
|
||||||
|
.voice_state(user.id, guild_id)
|
||||||
|
.context("Cannot get voice state")?;
|
||||||
|
let channel = state
|
||||||
|
.cache
|
||||||
|
.channel(user_voice_state.channel_id())
|
||||||
|
.context("Cannot get channel")?;
|
||||||
|
let channel_voice_states = state
|
||||||
|
.cache
|
||||||
|
.voice_channel_states(channel.id)
|
||||||
|
.context("Cannot get voice channel")?;
|
||||||
|
let count = channel_voice_states.count();
|
||||||
|
|
||||||
|
// count is 1 if the bot is the only one in the channel
|
||||||
|
if count == 1 {
|
||||||
|
leave_channel(guild_id, Arc::clone(&state)).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn leave_channel(
|
||||||
|
guild_id: Id<GuildMarker>,
|
||||||
|
state: Arc<StateRef>,
|
||||||
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
|
// stop playing
|
||||||
|
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||||
|
let call = call_lock.lock().await;
|
||||||
|
call.queue().stop();
|
||||||
|
}
|
||||||
|
// leave the voice channel
|
||||||
|
state.songbird.leave(guild_id).await?;
|
||||||
|
|
||||||
|
// reset guild settings
|
||||||
|
state.guild_settings.remove(&guild_id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn leave(
|
pub(crate) async fn leave(
|
||||||
interaction: Box<InteractionCreate>,
|
interaction: Box<InteractionCreate>,
|
||||||
@@ -16,6 +66,8 @@ pub(crate) async fn leave(
|
|||||||
let Some(guild_id) = interaction.guild_id else {
|
let Some(guild_id) = interaction.guild_id else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
state.songbird.leave(guild_id).await?;
|
|
||||||
|
leave_channel(guild_id, Arc::clone(&state)).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::metadata::MetadataMap;
|
use crate::metadata::MetadataMap;
|
||||||
use crate::state::{Settings, State, StateRef};
|
use crate::state::{State, StateRef};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use songbird::{Event, EventContext, EventHandler, TrackEvent};
|
use songbird::{Event, EventContext, EventHandler, TrackEvent};
|
||||||
use std::ops::Sub;
|
use std::ops::Sub;
|
||||||
@@ -29,14 +29,8 @@ pub(crate) async fn loop_queue(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
state
|
|
||||||
.guild_settings
|
|
||||||
.entry(guild_id)
|
|
||||||
.or_insert_with(|| Settings { loop_queue: false });
|
|
||||||
|
|
||||||
state.guild_settings.entry(guild_id).and_modify(|settings| {
|
state.guild_settings.entry(guild_id).and_modify(|settings| {
|
||||||
settings.loop_queue = !settings.loop_queue;
|
settings.loop_queue = !settings.loop_queue;
|
||||||
println!("loop_queue: {}", settings.loop_queue);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let looping = state
|
let looping = state
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ pub(crate) use join::join;
|
|||||||
|
|
||||||
mod leave;
|
mod leave;
|
||||||
pub(crate) use leave::leave;
|
pub(crate) use leave::leave;
|
||||||
|
pub(crate) use leave::leave_if_alone;
|
||||||
|
|
||||||
mod pause;
|
mod pause;
|
||||||
pub(crate) use pause::pause;
|
pub(crate) use pause::pause;
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ use std::ops::Sub;
|
|||||||
use std::{error::Error, time::Duration};
|
use std::{error::Error, time::Duration};
|
||||||
use tokio::process::Command;
|
use tokio::process::Command;
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
|
use twilight_model::channel::message::embed::{
|
||||||
|
EmbedAuthor, EmbedField, EmbedFooter, EmbedThumbnail,
|
||||||
|
};
|
||||||
use twilight_model::channel::message::MessageFlags;
|
use twilight_model::channel::message::MessageFlags;
|
||||||
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
||||||
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
|
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
|
||||||
@@ -47,6 +50,18 @@ async fn get_tracks(
|
|||||||
.map_while(Result::ok)
|
.map_while(Result::ok)
|
||||||
.flat_map(|line| serde_json::from_str(&line))
|
.flat_map(|line| serde_json::from_str(&line))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
if tracks.is_empty() {
|
||||||
|
if let Ok(stderr) = String::from_utf8(output.stderr) {
|
||||||
|
if stderr.contains("This video is only available to Music Premium members") {
|
||||||
|
return Err("This video is only available to Music Premium members".into());
|
||||||
|
}
|
||||||
|
if stderr.contains("YouTube said: The playlist does not exist.") {
|
||||||
|
return Err("YouTube said: The playlist does not exist.".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Err("No tracks found".into());
|
||||||
|
}
|
||||||
tracing::debug!("tracks: {:?}", tracks);
|
tracing::debug!("tracks: {:?}", tracks);
|
||||||
Ok(tracks)
|
Ok(tracks)
|
||||||
}
|
}
|
||||||
@@ -99,7 +114,23 @@ pub(crate) async fn play(
|
|||||||
|
|
||||||
debug!("query: {:?}", query);
|
debug!("query: {:?}", query);
|
||||||
|
|
||||||
let tracks = get_tracks(query).await?;
|
let tracks = match get_tracks(query).await {
|
||||||
|
Err(e) => {
|
||||||
|
let content = format!("{}", e);
|
||||||
|
let embeds = vec![EmbedBuilder::new()
|
||||||
|
.description(content)
|
||||||
|
.color(colors::RED)
|
||||||
|
.build()];
|
||||||
|
state
|
||||||
|
.http
|
||||||
|
.interaction(interaction.application_id)
|
||||||
|
.update_response(&interaction.token)
|
||||||
|
.embeds(Some(&embeds))?
|
||||||
|
.await?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Ok(tracks) => tracks,
|
||||||
|
};
|
||||||
|
|
||||||
if tracks.len() > 1 {
|
if tracks.len() > 1 {
|
||||||
let first_track = tracks.first().unwrap();
|
let first_track = tracks.first().unwrap();
|
||||||
@@ -133,22 +164,35 @@ pub(crate) async fn play(
|
|||||||
call.queue().resume()?;
|
call.queue().resume()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct TrackType {
|
||||||
|
url: String,
|
||||||
|
title: Option<String>,
|
||||||
|
duration_string: String,
|
||||||
|
channel: String,
|
||||||
|
thumbnail: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
let mut tracks_added = vec![];
|
let mut tracks_added = vec![];
|
||||||
for track in &tracks {
|
for yttrack in &tracks {
|
||||||
tracing::debug!("track: {:?}", track);
|
tracing::debug!("track: {:?}", yttrack);
|
||||||
let url = track.url.clone().or(track.original_url.clone()).ok_or("")?;
|
let url = yttrack
|
||||||
|
.original_url
|
||||||
|
.clone()
|
||||||
|
.or(yttrack.url.clone())
|
||||||
|
.ok_or("Could not find url")?;
|
||||||
let mut src = YoutubeDl::new(reqwest::Client::new(), url.clone());
|
let mut src = YoutubeDl::new(reqwest::Client::new(), url.clone());
|
||||||
let src_copy = src.clone();
|
let src_copy = src.clone();
|
||||||
let track: Track = src_copy.into();
|
let track: Track = src_copy.into();
|
||||||
//state
|
|
||||||
// .tracks
|
|
||||||
// .entry(guild_id)
|
|
||||||
// .or_default()
|
|
||||||
// .insert(track.uuid, src);
|
|
||||||
|
|
||||||
if let Ok(metadata) = src.aux_metadata().await {
|
if let Ok(metadata) = src.aux_metadata().await {
|
||||||
debug!("metadata: {:?}", metadata);
|
debug!("metadata: {:?}", metadata);
|
||||||
tracks_added.push((url.clone(), metadata.title.clone()));
|
tracks_added.push(TrackType {
|
||||||
|
url: url.clone(),
|
||||||
|
title: metadata.title.clone(),
|
||||||
|
duration_string: yttrack.duration_string.clone(),
|
||||||
|
channel: yttrack.channel.clone(),
|
||||||
|
thumbnail: metadata.thumbnail.clone(),
|
||||||
|
});
|
||||||
|
|
||||||
if let Some(call_lock) = state.songbird.get(guild_id) {
|
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||||
let mut call = call_lock.lock().await;
|
let mut call = call_lock.lock().await;
|
||||||
@@ -174,16 +218,58 @@ pub(crate) async fn play(
|
|||||||
}
|
}
|
||||||
let mut content = String::new();
|
let mut content = String::new();
|
||||||
let num_tracks_added = tracks_added.len();
|
let num_tracks_added = tracks_added.len();
|
||||||
match num_tracks_added {
|
let embeds = match num_tracks_added {
|
||||||
0 => {}
|
0 => {
|
||||||
|
vec![]
|
||||||
|
}
|
||||||
1 => {
|
1 => {
|
||||||
let (title, url) = if let Some(track) = tracks_added.first() {
|
let track = tracks_added.first().unwrap();
|
||||||
let track = track.clone();
|
|
||||||
(track.1.unwrap_or("Unknown".to_string()), track.0)
|
let host = Url::parse(&track.url)?;
|
||||||
} else {
|
let host = host
|
||||||
("Unknown".to_string(), "".to_string())
|
.host_str()
|
||||||
};
|
.unwrap_or_default()
|
||||||
content = format!("Added [{}]({}) to the queue", title, url);
|
.trim_start_matches("www.");
|
||||||
|
let mut embed = EmbedBuilder::new()
|
||||||
|
.author(EmbedAuthor {
|
||||||
|
name: "🔊 Added to queue".to_string(),
|
||||||
|
icon_url: None,
|
||||||
|
proxy_icon_url: None,
|
||||||
|
url: None,
|
||||||
|
})
|
||||||
|
.title(track.title.clone().unwrap_or("Unknown".to_string()))
|
||||||
|
.url(track.url.clone())
|
||||||
|
.color(colors::BLURPLE)
|
||||||
|
.footer(EmbedFooter {
|
||||||
|
text: format!("Streaming from {}", host),
|
||||||
|
icon_url: Some(format!(
|
||||||
|
"https://www.google.com/s2/favicons?domain={}",
|
||||||
|
host
|
||||||
|
)),
|
||||||
|
proxy_icon_url: None,
|
||||||
|
})
|
||||||
|
.field(EmbedField {
|
||||||
|
inline: true,
|
||||||
|
name: "Duration".to_string(),
|
||||||
|
value: track.duration_string.clone(),
|
||||||
|
})
|
||||||
|
.field(EmbedField {
|
||||||
|
inline: true,
|
||||||
|
name: "Channel".to_string(),
|
||||||
|
value: track.channel.clone(),
|
||||||
|
})
|
||||||
|
.build();
|
||||||
|
|
||||||
|
if let Some(thumbnail) = &track.thumbnail {
|
||||||
|
embed.thumbnail = Some(EmbedThumbnail {
|
||||||
|
height: None,
|
||||||
|
proxy_url: None,
|
||||||
|
url: thumbnail.to_string(),
|
||||||
|
width: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
vec![embed]
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
let first_track = tracks.first().unwrap();
|
let first_track = tracks.first().unwrap();
|
||||||
@@ -204,13 +290,14 @@ pub(crate) async fn play(
|
|||||||
"Added {} tracks to the queue:\n",
|
"Added {} tracks to the queue:\n",
|
||||||
num_tracks_added
|
num_tracks_added
|
||||||
));
|
));
|
||||||
|
let embed = EmbedBuilder::new()
|
||||||
|
.description(content)
|
||||||
|
.color(colors::BLURPLE)
|
||||||
|
.build();
|
||||||
|
vec![embed]
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
let embeds = vec![EmbedBuilder::new()
|
|
||||||
.description(content)
|
|
||||||
.color(colors::BLURPLE)
|
|
||||||
.build()];
|
|
||||||
state
|
state
|
||||||
.http
|
.http
|
||||||
.interaction(interaction.application_id)
|
.interaction(interaction.application_id)
|
||||||
@@ -239,4 +326,34 @@ mod tests {
|
|||||||
assert!(!tracks.is_empty());
|
assert!(!tracks.is_empty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_premium_tracks() {
|
||||||
|
let urls = ["https://www.youtube.com/watch?v=QgMZRmxQ0Dc"];
|
||||||
|
for url in urls.iter() {
|
||||||
|
println!("url: {:?}", url);
|
||||||
|
let tracks = get_tracks(url.to_string()).await;
|
||||||
|
assert!(tracks.is_err());
|
||||||
|
assert!(tracks
|
||||||
|
.err()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
.contains("This video is only available to Music Premium members"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_playlist_does_not_exist_tracks() {
|
||||||
|
let urls = ["https://www.youtube.com/playlist?list=PLox0oG0uy8Lc1IaIfGyrvtuRItuEyJiyG"];
|
||||||
|
for url in urls.iter() {
|
||||||
|
println!("url: {:?}", url);
|
||||||
|
let tracks = get_tracks(url.to_string()).await;
|
||||||
|
assert!(tracks.is_err());
|
||||||
|
assert!(tracks
|
||||||
|
.err()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
.contains("YouTube said: The playlist does not exist."));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,9 +59,9 @@ pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Ve
|
|||||||
}
|
}
|
||||||
message.push('\n');
|
message.push('\n');
|
||||||
|
|
||||||
let max_pages = queue.len() / TRACKS_PER_PAGE;
|
let n_pages = (queue.len() + TRACKS_PER_PAGE - 1) / TRACKS_PER_PAGE;
|
||||||
if max_pages > 0 {
|
if n_pages > 1 {
|
||||||
message.push_str(&format!("page {}/{}", 1 + page, 1 + max_pages));
|
message.push_str(&format!("page {}/{}", 1 + page, n_pages));
|
||||||
}
|
}
|
||||||
vec![EmbedBuilder::new()
|
vec![EmbedBuilder::new()
|
||||||
.description(&message)
|
.description(&message)
|
||||||
@@ -69,10 +69,7 @@ pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Ve
|
|||||||
.build()]
|
.build()]
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component> {
|
pub(crate) fn build_action_row(page: usize, n_pages: usize) -> Vec<Component> {
|
||||||
if max_pages == 0 {
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
vec![Component::ActionRow(ActionRow {
|
vec![Component::ActionRow(ActionRow {
|
||||||
components: vec![
|
components: vec![
|
||||||
Component::Button(Button {
|
Component::Button(Button {
|
||||||
@@ -85,6 +82,16 @@ pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component>
|
|||||||
url: None,
|
url: None,
|
||||||
disabled: page == 0,
|
disabled: page == 0,
|
||||||
}),
|
}),
|
||||||
|
Component::Button(Button {
|
||||||
|
custom_id: Some(format!("page:{}", page)),
|
||||||
|
style: ButtonStyle::Primary,
|
||||||
|
label: Some("Refresh".to_string()),
|
||||||
|
emoji: Some(ReactionType::Unicode {
|
||||||
|
name: "🔄".to_string(),
|
||||||
|
}),
|
||||||
|
url: None,
|
||||||
|
disabled: false,
|
||||||
|
}),
|
||||||
Component::Button(Button {
|
Component::Button(Button {
|
||||||
custom_id: Some(format!("page:{}", page + 1)),
|
custom_id: Some(format!("page:{}", page + 1)),
|
||||||
style: ButtonStyle::Primary,
|
style: ButtonStyle::Primary,
|
||||||
@@ -93,7 +100,7 @@ pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component>
|
|||||||
name: "➡️".to_string(),
|
name: "➡️".to_string(),
|
||||||
}),
|
}),
|
||||||
url: None,
|
url: None,
|
||||||
disabled: page >= max_pages,
|
disabled: page >= n_pages - 1,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
})]
|
})]
|
||||||
@@ -139,7 +146,8 @@ pub(crate) async fn queue(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let embeds = build_queue_embeds(&queue, 0).await;
|
let embeds = build_queue_embeds(&queue, 0).await;
|
||||||
let action_row = build_action_row(0, queue.len() / TRACKS_PER_PAGE);
|
let n_pages = (queue.len() + TRACKS_PER_PAGE - 1) / TRACKS_PER_PAGE;
|
||||||
|
let action_row = build_action_row(0, n_pages);
|
||||||
|
|
||||||
state
|
state
|
||||||
.http
|
.http
|
||||||
|
|||||||
@@ -23,6 +23,10 @@ pub(crate) async fn stop(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
|
state.guild_settings.entry(guild_id).and_modify(|settings| {
|
||||||
|
settings.loop_queue = false;
|
||||||
|
});
|
||||||
|
|
||||||
if let Some(call_lock) = state.songbird.get(guild_id) {
|
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||||
let call = call_lock.lock().await;
|
let call = call_lock.lock().await;
|
||||||
call.queue().stop();
|
call.queue().stop();
|
||||||
|
|||||||
284
src/handler.rs
284
src/handler.rs
@@ -1,79 +1,19 @@
|
|||||||
use crate::commands::queue::{build_action_row, build_queue_embeds, TRACKS_PER_PAGE};
|
use crate::commands::queue::{build_action_row, build_queue_embeds, TRACKS_PER_PAGE};
|
||||||
use crate::commands::{delete, join, leave, loop_queue, pause, play, queue, resume, skip, stop};
|
use crate::commands::{
|
||||||
use crate::state::State;
|
delete, join, leave, leave_if_alone, loop_queue, pause, play, queue, resume, skip, stop,
|
||||||
use futures::Future;
|
|
||||||
use std::error::Error;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use tracing::debug;
|
|
||||||
use twilight_gateway::Event;
|
|
||||||
use twilight_model::application::interaction::application_command::{
|
|
||||||
CommandData, CommandOptionValue,
|
|
||||||
};
|
};
|
||||||
|
use crate::interaction_commands::InteractionCommand;
|
||||||
|
use crate::state::State;
|
||||||
|
use crate::utils::spawn;
|
||||||
|
use anyhow::Context;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use twilight_gateway::Event;
|
||||||
|
use twilight_model::application::interaction::message_component::MessageComponentInteractionData;
|
||||||
use twilight_model::application::interaction::InteractionData;
|
use twilight_model::application::interaction::InteractionData;
|
||||||
use twilight_model::gateway::payload::incoming::VoiceStateUpdate;
|
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
||||||
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
|
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
|
||||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
enum InteractionCommand {
|
|
||||||
Play(String),
|
|
||||||
Stop,
|
|
||||||
Pause,
|
|
||||||
Skip,
|
|
||||||
Loop,
|
|
||||||
Resume,
|
|
||||||
Leave,
|
|
||||||
Join,
|
|
||||||
Queue,
|
|
||||||
NotImplemented,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn spawn(
|
|
||||||
fut: impl Future<Output = Result<(), Box<dyn Error + Send + Sync + 'static>>> + Send + 'static,
|
|
||||||
) {
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if let Err(why) = fut.await {
|
|
||||||
tracing::debug!("handler error: {:?}", why);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn leave_if_alone(
|
|
||||||
update: VoiceStateUpdate,
|
|
||||||
state: State,
|
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|
||||||
let guild_id = update.guild_id.ok_or("Guild ID not found")?;
|
|
||||||
let user = state
|
|
||||||
.cache
|
|
||||||
.current_user()
|
|
||||||
.ok_or("Cannot get current user")?;
|
|
||||||
let user_voice_state = state
|
|
||||||
.cache
|
|
||||||
.voice_state(user.id, guild_id)
|
|
||||||
.ok_or("Cannot get voice state")?;
|
|
||||||
let channel = state
|
|
||||||
.cache
|
|
||||||
.channel(user_voice_state.channel_id())
|
|
||||||
.ok_or("Cannot get channel")?;
|
|
||||||
let channel_voice_states = state
|
|
||||||
.cache
|
|
||||||
.voice_channel_states(channel.id)
|
|
||||||
.ok_or("Cannot get voice channel")?;
|
|
||||||
let count = channel_voice_states.count();
|
|
||||||
|
|
||||||
// count is 1 if the bot is the only one in the channel
|
|
||||||
if count == 1 {
|
|
||||||
// stop playing
|
|
||||||
if let Some(call_lock) = state.songbird.get(guild_id) {
|
|
||||||
let call = call_lock.lock().await;
|
|
||||||
call.queue().stop();
|
|
||||||
}
|
|
||||||
// leave the voice channel
|
|
||||||
state.songbird.leave(guild_id).await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct Handler {
|
pub(crate) struct Handler {
|
||||||
state: State,
|
state: State,
|
||||||
}
|
}
|
||||||
@@ -83,6 +23,13 @@ impl Handler {
|
|||||||
Self { state }
|
Self { state }
|
||||||
}
|
}
|
||||||
pub(crate) async fn act(&self, event: Event) -> anyhow::Result<()> {
|
pub(crate) async fn act(&self, event: Event) -> anyhow::Result<()> {
|
||||||
|
self.handle_messages(&event).await?;
|
||||||
|
self.handle_voice_state_update(&event).await?;
|
||||||
|
self.handle_interaction(&event).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_messages(&self, event: &Event) -> anyhow::Result<()> {
|
||||||
match event {
|
match event {
|
||||||
Event::MessageCreate(message) if message.content.starts_with('!') => {
|
Event::MessageCreate(message) if message.content.starts_with('!') => {
|
||||||
if message.content.contains("!delete") {
|
if message.content.contains("!delete") {
|
||||||
@@ -90,121 +37,102 @@ impl Handler {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_voice_state_update(&self, event: &Event) -> anyhow::Result<()> {
|
||||||
|
match event {
|
||||||
Event::VoiceStateUpdate(update) => {
|
Event::VoiceStateUpdate(update) => {
|
||||||
spawn(leave_if_alone(*update.clone(), Arc::clone(&self.state)));
|
let guild_id = update.guild_id.context("Guild ID not found")?;
|
||||||
|
spawn(leave_if_alone(guild_id, Arc::clone(&self.state)));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Event::InteractionCreate(interaction) => {
|
_ => Ok(()),
|
||||||
tracing::info!("interaction: {:?}", &interaction);
|
}
|
||||||
match &interaction.data {
|
}
|
||||||
Some(InteractionData::ApplicationCommand(command)) => {
|
|
||||||
let interaction_command = parse_interaction_command(command);
|
|
||||||
debug!("{:?}", interaction_command);
|
|
||||||
match interaction_command {
|
|
||||||
InteractionCommand::Play(query) => {
|
|
||||||
spawn(play(interaction, Arc::clone(&self.state), query))
|
|
||||||
}
|
|
||||||
InteractionCommand::Stop => {
|
|
||||||
spawn(stop(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
InteractionCommand::Pause => {
|
|
||||||
spawn(pause(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
InteractionCommand::Skip => {
|
|
||||||
spawn(skip(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
InteractionCommand::Loop => {
|
|
||||||
spawn(loop_queue(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
InteractionCommand::Resume => {
|
|
||||||
spawn(resume(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
InteractionCommand::Leave => {
|
|
||||||
spawn(leave(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
InteractionCommand::Join => {
|
|
||||||
spawn(join(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
InteractionCommand::Queue => {
|
|
||||||
spawn(queue(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Some(InteractionData::MessageComponent(data)) => {
|
|
||||||
tracing::info!("message component: {:?}", data);
|
|
||||||
|
|
||||||
if !data.custom_id.starts_with("page:") {
|
async fn handle_interaction(&self, event: &Event) -> anyhow::Result<()> {
|
||||||
return Ok(());
|
match event {
|
||||||
}
|
Event::InteractionCreate(interaction) => match &interaction.data {
|
||||||
let page = data
|
Some(InteractionData::ApplicationCommand(command)) => {
|
||||||
.custom_id
|
self.handle_application_command(command.clone().into(), interaction.clone())
|
||||||
.trim_start_matches("page:")
|
|
||||||
.parse::<usize>()
|
|
||||||
.unwrap_or(0);
|
|
||||||
tracing::info!("page: {:?}", page);
|
|
||||||
|
|
||||||
if let Some(guild_id) = interaction.guild_id {
|
|
||||||
let mut queue = Vec::new();
|
|
||||||
if let Some(call_lock) = self.state.songbird.get(guild_id) {
|
|
||||||
let call = call_lock.lock().await;
|
|
||||||
queue = call.queue().current_queue();
|
|
||||||
}
|
|
||||||
let embeds = build_queue_embeds(&queue, page).await;
|
|
||||||
let action_row = build_action_row(page, queue.len() / TRACKS_PER_PAGE);
|
|
||||||
|
|
||||||
let interaction_response_data = InteractionResponseDataBuilder::new()
|
|
||||||
.embeds(embeds)
|
|
||||||
.components(action_row)
|
|
||||||
.build();
|
|
||||||
let response = InteractionResponse {
|
|
||||||
kind: InteractionResponseType::UpdateMessage,
|
|
||||||
data: Some(interaction_response_data),
|
|
||||||
};
|
|
||||||
self.state
|
|
||||||
.http
|
|
||||||
.interaction(interaction.application_id)
|
|
||||||
.create_response(interaction.id, &interaction.token, &response)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => Ok(()),
|
|
||||||
}
|
}
|
||||||
|
Some(InteractionData::MessageComponent(data)) => {
|
||||||
|
self.handle_message_component(data, interaction.clone())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
_ => Ok(()),
|
||||||
|
},
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_application_command(
|
||||||
|
&self,
|
||||||
|
command: InteractionCommand,
|
||||||
|
interaction: Box<InteractionCreate>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
{
|
||||||
|
match command {
|
||||||
|
InteractionCommand::Play(query) => {
|
||||||
|
spawn(play(interaction, Arc::clone(&self.state), query))
|
||||||
|
}
|
||||||
|
InteractionCommand::Stop => spawn(stop(interaction, Arc::clone(&self.state))),
|
||||||
|
InteractionCommand::Pause => spawn(pause(interaction, Arc::clone(&self.state))),
|
||||||
|
InteractionCommand::Skip => spawn(skip(interaction, Arc::clone(&self.state))),
|
||||||
|
InteractionCommand::Loop => spawn(loop_queue(interaction, Arc::clone(&self.state))),
|
||||||
|
InteractionCommand::Resume => spawn(resume(interaction, Arc::clone(&self.state))),
|
||||||
|
InteractionCommand::Leave => spawn(leave(interaction, Arc::clone(&self.state))),
|
||||||
|
InteractionCommand::Join => spawn(join(interaction, Arc::clone(&self.state))),
|
||||||
|
InteractionCommand::Queue => spawn(queue(interaction, Arc::clone(&self.state))),
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
event => {
|
Ok(())
|
||||||
tracing::info!("unhandled event: {:?}", event);
|
}
|
||||||
Ok(())
|
}
|
||||||
|
|
||||||
|
async fn handle_message_component(
|
||||||
|
&self,
|
||||||
|
data: &MessageComponentInteractionData,
|
||||||
|
interaction: Box<InteractionCreate>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
if !data.custom_id.starts_with("page:") {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let page = data
|
||||||
|
.custom_id
|
||||||
|
.trim_start_matches("page:")
|
||||||
|
.parse::<usize>()
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
if let Some(guild_id) = interaction.guild_id {
|
||||||
|
let mut queue = Vec::new();
|
||||||
|
if let Some(call_lock) = self.state.songbird.get(guild_id) {
|
||||||
|
let call = call_lock.lock().await;
|
||||||
|
queue = call.queue().current_queue();
|
||||||
}
|
}
|
||||||
|
let n_pages = (queue.len() + TRACKS_PER_PAGE - 1) / TRACKS_PER_PAGE;
|
||||||
|
let page = page.min(n_pages - 1).max(0);
|
||||||
|
let embeds = build_queue_embeds(&queue, page).await;
|
||||||
|
let action_row = build_action_row(page, n_pages);
|
||||||
|
|
||||||
|
let interaction_response_data = InteractionResponseDataBuilder::new()
|
||||||
|
.embeds(embeds)
|
||||||
|
.components(action_row)
|
||||||
|
.build();
|
||||||
|
let response = InteractionResponse {
|
||||||
|
kind: InteractionResponseType::UpdateMessage,
|
||||||
|
data: Some(interaction_response_data),
|
||||||
|
};
|
||||||
|
self.state
|
||||||
|
.http
|
||||||
|
.interaction(interaction.application_id)
|
||||||
|
.create_response(interaction.id, &interaction.token, &response)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_interaction_command(command: &CommandData) -> InteractionCommand {
|
|
||||||
debug!("command: {:?}", command);
|
|
||||||
match command.name.as_str() {
|
|
||||||
"play" => {
|
|
||||||
if let Some(query_option) = command.options.iter().find(|opt| opt.name == "query") {
|
|
||||||
if let CommandOptionValue::String(query) = &query_option.value {
|
|
||||||
InteractionCommand::Play(query.clone())
|
|
||||||
} else {
|
|
||||||
InteractionCommand::NotImplemented
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
InteractionCommand::NotImplemented
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"stop" => InteractionCommand::Stop,
|
|
||||||
"pause" => InteractionCommand::Pause,
|
|
||||||
"skip" => InteractionCommand::Skip,
|
|
||||||
"loop" => InteractionCommand::Loop,
|
|
||||||
"resume" => InteractionCommand::Resume,
|
|
||||||
"leave" => InteractionCommand::Leave,
|
|
||||||
"join" => InteractionCommand::Join,
|
|
||||||
"queue" => InteractionCommand::Queue,
|
|
||||||
_ => InteractionCommand::NotImplemented,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
44
src/interaction_commands.rs
Normal file
44
src/interaction_commands.rs
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
use twilight_model::application::interaction::application_command::{
|
||||||
|
CommandData, CommandOptionValue,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) enum InteractionCommand {
|
||||||
|
Play(String),
|
||||||
|
Stop,
|
||||||
|
Pause,
|
||||||
|
Skip,
|
||||||
|
Loop,
|
||||||
|
Resume,
|
||||||
|
Leave,
|
||||||
|
Join,
|
||||||
|
Queue,
|
||||||
|
NotImplemented,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Box<CommandData>> for InteractionCommand {
|
||||||
|
fn from(command: Box<CommandData>) -> InteractionCommand {
|
||||||
|
match command.name.as_str() {
|
||||||
|
"play" => {
|
||||||
|
if let Some(query_option) = command.options.iter().find(|opt| opt.name == "query") {
|
||||||
|
if let CommandOptionValue::String(query) = &query_option.value {
|
||||||
|
InteractionCommand::Play(query.clone())
|
||||||
|
} else {
|
||||||
|
InteractionCommand::NotImplemented
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
InteractionCommand::NotImplemented
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"stop" => InteractionCommand::Stop,
|
||||||
|
"pause" => InteractionCommand::Pause,
|
||||||
|
"skip" => InteractionCommand::Skip,
|
||||||
|
"loop" => InteractionCommand::Loop,
|
||||||
|
"resume" => InteractionCommand::Resume,
|
||||||
|
"leave" => InteractionCommand::Leave,
|
||||||
|
"join" => InteractionCommand::Join,
|
||||||
|
"queue" => InteractionCommand::Queue,
|
||||||
|
_ => InteractionCommand::NotImplemented,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,9 +2,11 @@ mod handler;
|
|||||||
use handler::Handler;
|
use handler::Handler;
|
||||||
mod colors;
|
mod colors;
|
||||||
mod commands;
|
mod commands;
|
||||||
|
mod interaction_commands;
|
||||||
mod metadata;
|
mod metadata;
|
||||||
mod signal;
|
mod signal;
|
||||||
mod state;
|
mod state;
|
||||||
|
mod utils;
|
||||||
|
|
||||||
use crate::commands::get_chat_commands;
|
use crate::commands::get_chat_commands;
|
||||||
use dotenv::dotenv;
|
use dotenv::dotenv;
|
||||||
|
|||||||
12
src/state.rs
12
src/state.rs
@@ -13,6 +13,18 @@ pub(crate) struct Settings {
|
|||||||
pub(crate) loop_queue: bool,
|
pub(crate) loop_queue: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Settings {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
Self { loop_queue: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Settings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub(crate) struct StateRef {
|
pub(crate) struct StateRef {
|
||||||
pub(crate) http: HttpClient,
|
pub(crate) http: HttpClient,
|
||||||
|
|||||||
12
src/utils.rs
Normal file
12
src/utils.rs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
use futures::Future;
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
|
pub(crate) fn spawn(
|
||||||
|
fut: impl Future<Output = Result<(), Box<dyn Error + Send + Sync + 'static>>> + Send + 'static,
|
||||||
|
) {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(why) = fut.await {
|
||||||
|
tracing::debug!("handler error: {:?}", why);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user