Compare commits
14 Commits
2c91c744dc
...
message_fo
| Author | SHA1 | Date | |
|---|---|---|---|
|
c5d9c49452
|
|||
|
dbaf1a1374
|
|||
|
c0d9f6cad5
|
|||
|
1aa0efc4a6
|
|||
|
ab7f56fe05
|
|||
| feccbebd4d | |||
| d6a54dfc06 | |||
|
fa17ed75f6
|
|||
| b19f6e552c | |||
|
0bee437e53
|
|||
|
3781785a50
|
|||
| cabae9ea19 | |||
|
54c36688b7
|
|||
|
55fe212424
|
@@ -2,7 +2,9 @@ name: tests
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
paths-ignore:
|
||||
- 'README.md'
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
@@ -36,6 +38,11 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- run: sudo apt-get update
|
||||
- run: sudo apt-get install -y cmake
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Install yt-dlp
|
||||
run: pip install yt-dlp
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
- name: Run tests
|
||||
run: cargo test --verbose --all-features
|
||||
|
||||
@@ -5,6 +5,9 @@ on:
|
||||
branches:
|
||||
- main
|
||||
|
||||
paths-ignore:
|
||||
- 'README.md'
|
||||
|
||||
jobs:
|
||||
release-image:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -26,6 +29,5 @@ jobs:
|
||||
with:
|
||||
platforms: |
|
||||
linux/amd64
|
||||
linux/arm64
|
||||
push: true
|
||||
tags: jheuel/ohrwurm:latest
|
||||
|
||||
5
.github/workflows/ci.yml
vendored
5
.github/workflows/ci.yml
vendored
@@ -37,6 +37,11 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- run: sudo apt-get update
|
||||
- run: sudo apt-get install -y cmake
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Install yt-dlp
|
||||
run: pip install yt-dlp
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
- name: Run tests
|
||||
run: cargo test --verbose --all-features
|
||||
|
||||
11
Cargo.lock
generated
11
Cargo.lock
generated
@@ -1064,9 +1064,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.2"
|
||||
version = "2.7.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
|
||||
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
@@ -1209,6 +1209,8 @@ name = "ohrwurm"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"dashmap",
|
||||
"dotenv",
|
||||
"futures",
|
||||
"regex",
|
||||
@@ -1227,6 +1229,7 @@ dependencies = [
|
||||
"twilight-standby",
|
||||
"twilight-util",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1488,9 +1491,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.1"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e"
|
||||
checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd"
|
||||
dependencies = [
|
||||
"bitflags 2.5.0",
|
||||
]
|
||||
|
||||
@@ -23,5 +23,8 @@ twilight-util = { version = "0.15", features=["builder"] }
|
||||
dotenv = "0.15.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
url = "2.5.0"
|
||||
url = "2.5.1"
|
||||
anyhow = "1.0.86"
|
||||
dashmap = "5.5.3"
|
||||
async-trait = "0.1.80"
|
||||
uuid = "1.8.0"
|
||||
|
||||
@@ -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.
|
||||
|
||||
# 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
|
||||
docker run -d \
|
||||
--name ohrwurm \
|
||||
|
||||
@@ -1,2 +1,20 @@
|
||||
#[allow(dead_code)]
|
||||
pub(crate) const BLURPLE: u32 = 0x58_65_F2;
|
||||
#[allow(dead_code)]
|
||||
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?;
|
||||
}
|
||||
|
||||
// create guild config
|
||||
state.guild_settings.entry(guild_id).or_default();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,26 @@
|
||||
use crate::state::State;
|
||||
use std::error::Error;
|
||||
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
||||
use crate::state::{State, StateRef};
|
||||
use std::{error::Error, sync::Arc};
|
||||
use twilight_model::{
|
||||
gateway::payload::incoming::InteractionCreate,
|
||||
id::{marker::GuildMarker, Id},
|
||||
};
|
||||
|
||||
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(
|
||||
interaction: Box<InteractionCreate>,
|
||||
@@ -16,6 +36,8 @@ pub(crate) async fn leave(
|
||||
let Some(guild_id) = interaction.guild_id else {
|
||||
return Ok(());
|
||||
};
|
||||
state.songbird.leave(guild_id).await?;
|
||||
|
||||
leave_channel(guild_id, Arc::clone(&state)).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
123
src/commands/loop_queue.rs
Normal file
123
src/commands/loop_queue.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
use crate::metadata::MetadataMap;
|
||||
use crate::state::{State, StateRef};
|
||||
use async_trait::async_trait;
|
||||
use songbird::{Event, EventContext, EventHandler, TrackEvent};
|
||||
use std::ops::Sub;
|
||||
use std::time::Duration;
|
||||
use std::{error::Error, sync::Arc};
|
||||
use twilight_model::{
|
||||
gateway::payload::incoming::InteractionCreate,
|
||||
http::interaction::{InteractionResponse, InteractionResponseType},
|
||||
id::{marker::GuildMarker, Id},
|
||||
};
|
||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||
|
||||
pub(crate) async fn loop_queue(
|
||||
interaction: Box<InteractionCreate>,
|
||||
state: State,
|
||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||
tracing::debug!(
|
||||
"loop command in guild {:?} in channel {:?} by {:?}",
|
||||
interaction.guild_id,
|
||||
interaction.channel,
|
||||
interaction.author(),
|
||||
);
|
||||
|
||||
let guild_id: Id<GuildMarker> = if let Some(guild_id) = interaction.guild_id {
|
||||
guild_id
|
||||
} else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
state.guild_settings.entry(guild_id).and_modify(|settings| {
|
||||
settings.loop_queue = !settings.loop_queue;
|
||||
});
|
||||
|
||||
let looping = state
|
||||
.guild_settings
|
||||
.get(&guild_id)
|
||||
.expect("Cannot get loop state")
|
||||
.loop_queue;
|
||||
|
||||
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||
let mut call = call_lock.lock().await;
|
||||
call.add_global_event(
|
||||
Event::Track(TrackEvent::End),
|
||||
TrackEndNotifier {
|
||||
guild_id,
|
||||
state: Arc::clone(&state),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let message = if looping {
|
||||
"I'm now looping the current queue!".to_string()
|
||||
} else {
|
||||
"I'm not looping anymore!".to_string()
|
||||
};
|
||||
|
||||
let interaction_response_data = InteractionResponseDataBuilder::new()
|
||||
.content(message)
|
||||
.build();
|
||||
|
||||
let response = InteractionResponse {
|
||||
kind: InteractionResponseType::ChannelMessageWithSource,
|
||||
data: Some(interaction_response_data),
|
||||
};
|
||||
|
||||
state
|
||||
.http
|
||||
.interaction(interaction.application_id)
|
||||
.create_response(interaction.id, &interaction.token, &response)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct TrackEndNotifier {
|
||||
guild_id: Id<GuildMarker>,
|
||||
state: Arc<StateRef>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EventHandler for TrackEndNotifier {
|
||||
async fn act(&self, ctx: &EventContext<'_>) -> Option<Event> {
|
||||
if !self
|
||||
.state
|
||||
.guild_settings
|
||||
.get(&self.guild_id)
|
||||
.unwrap()
|
||||
.loop_queue
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let EventContext::Track(track_list) = ctx else {
|
||||
return None;
|
||||
};
|
||||
let (_, track_handle) = track_list.first()?;
|
||||
if let Some(call_lock) = self.state.songbird.get(self.guild_id) {
|
||||
let mut call = call_lock.lock().await;
|
||||
|
||||
// get metadata from finished track
|
||||
let old_typemap_lock = track_handle.typemap().read().await;
|
||||
let old_metadata = old_typemap_lock.get::<MetadataMap>().unwrap();
|
||||
|
||||
// enqueue track
|
||||
let handle = call.enqueue_with_preload(
|
||||
old_metadata.src.clone().into(),
|
||||
old_metadata.duration.map(|duration| -> Duration {
|
||||
if duration.as_secs() > 5 {
|
||||
duration.sub(Duration::from_secs(5))
|
||||
} else {
|
||||
duration
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// insert metadata into new track
|
||||
let mut new_typemap = handle.typemap().write().await;
|
||||
new_typemap.insert::<MetadataMap>(old_metadata.clone());
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,17 @@ pub(crate) use join::join;
|
||||
|
||||
mod leave;
|
||||
pub(crate) use leave::leave;
|
||||
pub(crate) use leave::leave_channel;
|
||||
|
||||
mod pause;
|
||||
pub(crate) use pause::pause;
|
||||
|
||||
mod skip;
|
||||
pub(crate) use skip::skip;
|
||||
|
||||
mod loop_queue;
|
||||
pub(crate) use loop_queue::loop_queue;
|
||||
|
||||
mod play;
|
||||
pub(crate) use play::play;
|
||||
|
||||
@@ -29,12 +36,14 @@ pub(crate) fn get_chat_commands() -> Vec<twilight_model::application::command::C
|
||||
vec![
|
||||
CommandBuilder::new("join", "Join the channel", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("leave", "Leave the channel", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("loop", "Loop queue", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("skip", "Skip track", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("queue", "Print track queue", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("stop", "Stop playing", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("pause", "Pause playing", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("resume", "Resume playing", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("play", "Add a song to the queue", CommandType::ChatInput)
|
||||
.option(StringBuilder::new("query", "URL of a song").required(true))
|
||||
.build(),
|
||||
CommandBuilder::new("queue", "Print track queue", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("resume", "Resume playing", CommandType::ChatInput).build(),
|
||||
CommandBuilder::new("stop", "Stop playing", CommandType::ChatInput).build(),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -5,10 +5,15 @@ use crate::state::State;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use songbird::input::{Compose, YoutubeDl};
|
||||
use songbird::tracks::Track;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::{error::Error, ops::Sub, time::Duration};
|
||||
use std::ops::Sub;
|
||||
use std::{error::Error, time::Duration};
|
||||
use tokio::process::Command;
|
||||
use tracing::debug;
|
||||
use twilight_model::channel::message::embed::{
|
||||
EmbedAuthor, EmbedField, EmbedFooter, EmbedThumbnail,
|
||||
};
|
||||
use twilight_model::channel::message::MessageFlags;
|
||||
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
||||
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
|
||||
@@ -18,11 +23,12 @@ use url::Url;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct YouTubeTrack {
|
||||
url: String,
|
||||
url: Option<String>,
|
||||
original_url: Option<String>,
|
||||
title: String,
|
||||
channel: String,
|
||||
playlist: String,
|
||||
playlist_id: String,
|
||||
playlist: Option<String>,
|
||||
playlist_id: Option<String>,
|
||||
duration_string: String,
|
||||
}
|
||||
|
||||
@@ -44,6 +50,19 @@ async fn get_tracks(
|
||||
.map_while(Result::ok)
|
||||
.flat_map(|line| serde_json::from_str(&line))
|
||||
.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(stderr.into());
|
||||
}
|
||||
return Err("No tracks found".into());
|
||||
}
|
||||
tracing::debug!("tracks: {:?}", tracks);
|
||||
Ok(tracks)
|
||||
}
|
||||
@@ -96,14 +115,38 @@ pub(crate) async fn play(
|
||||
|
||||
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 {
|
||||
let first_track = tracks.first().unwrap();
|
||||
let content = format!(
|
||||
"Adding playlist [{}]({})",
|
||||
first_track.playlist,
|
||||
build_playlist_url(&first_track.playlist_id)
|
||||
first_track
|
||||
.playlist
|
||||
.clone()
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
build_playlist_url(
|
||||
&first_track
|
||||
.playlist_id
|
||||
.clone()
|
||||
.unwrap_or("Unknown".to_string())
|
||||
)
|
||||
);
|
||||
let embeds = vec![EmbedBuilder::new()
|
||||
.description(content)
|
||||
@@ -122,19 +165,40 @@ pub(crate) async fn play(
|
||||
call.queue().resume()?;
|
||||
}
|
||||
|
||||
struct TrackType {
|
||||
url: String,
|
||||
title: Option<String>,
|
||||
duration_string: String,
|
||||
channel: String,
|
||||
thumbnail: Option<String>,
|
||||
}
|
||||
|
||||
let mut tracks_added = vec![];
|
||||
for track in &tracks {
|
||||
tracing::debug!("track: {:?}", track);
|
||||
let url = track.url.clone();
|
||||
let mut src = YoutubeDl::new(reqwest::Client::new(), url.to_string());
|
||||
for yttrack in &tracks {
|
||||
tracing::debug!("track: {:?}", yttrack);
|
||||
let url = yttrack
|
||||
.url
|
||||
.clone()
|
||||
.or(yttrack.original_url.clone())
|
||||
.ok_or("")?;
|
||||
let mut src = YoutubeDl::new(reqwest::Client::new(), url.clone());
|
||||
let src_copy = src.clone();
|
||||
let track: Track = src_copy.into();
|
||||
|
||||
if let Ok(metadata) = src.aux_metadata().await {
|
||||
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) {
|
||||
let mut call = call_lock.lock().await;
|
||||
let handle = call.enqueue_with_preload(
|
||||
src.into(),
|
||||
track,
|
||||
metadata.duration.map(|duration| -> Duration {
|
||||
if duration.as_secs() > 5 {
|
||||
duration.sub(Duration::from_secs(5))
|
||||
@@ -148,41 +212,93 @@ pub(crate) async fn play(
|
||||
title: metadata.title,
|
||||
duration: metadata.duration,
|
||||
url,
|
||||
src,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut content = String::new();
|
||||
let num_tracks_added = tracks_added.len();
|
||||
match num_tracks_added {
|
||||
0 => {}
|
||||
let embeds = match num_tracks_added {
|
||||
0 => {
|
||||
vec![]
|
||||
}
|
||||
1 => {
|
||||
let (title, url) = if let Some(track) = tracks_added.first() {
|
||||
let track = track.clone();
|
||||
(track.1.unwrap_or("Unknown".to_string()), track.0)
|
||||
} else {
|
||||
("Unknown".to_string(), "".to_string())
|
||||
};
|
||||
content = format!("Added [{}]({}) to the queue", title, url);
|
||||
let track = tracks_added.first().unwrap();
|
||||
|
||||
let host = Url::parse(&track.url)?;
|
||||
let host = host
|
||||
.host_str()
|
||||
.unwrap_or_default()
|
||||
.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();
|
||||
content.push_str(&format!(
|
||||
"Adding playlist: [{}]({})\n",
|
||||
&first_track.playlist,
|
||||
build_playlist_url(&first_track.playlist_id)
|
||||
&first_track
|
||||
.playlist
|
||||
.clone()
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
build_playlist_url(
|
||||
&first_track
|
||||
.playlist_id
|
||||
.clone()
|
||||
.unwrap_or("Unknown".to_string())
|
||||
)
|
||||
));
|
||||
content.push_str(&format!(
|
||||
"Added {} tracks to the queue:\n",
|
||||
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
|
||||
.http
|
||||
.interaction(interaction.application_id)
|
||||
@@ -192,3 +308,53 @@ pub(crate) async fn play(
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_tracks() {
|
||||
let urls = [
|
||||
"https://www.youtube.com/playlist?list=PLFxxhcEeloYa1OlnWD6UgxlVQKJH5i_0p",
|
||||
"https://music.youtube.com/watch?v=RO75ZzqUOJw",
|
||||
"https://www.youtube.com/watch?v=qVHyl0P_P-M",
|
||||
"https://www.youtube.com/watch?v=34CZjsEI1yU",
|
||||
];
|
||||
for url in urls.iter() {
|
||||
println!("url: {:?}", url);
|
||||
let tracks = get_tracks(url.to_string()).await.unwrap();
|
||||
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."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
45
src/commands/skip.rs
Normal file
45
src/commands/skip.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use crate::state::State;
|
||||
use std::error::Error;
|
||||
use twilight_model::{
|
||||
gateway::payload::incoming::InteractionCreate,
|
||||
http::interaction::{InteractionResponse, InteractionResponseType},
|
||||
};
|
||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||
|
||||
pub(crate) async fn skip(
|
||||
interaction: Box<InteractionCreate>,
|
||||
state: State,
|
||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||
tracing::debug!(
|
||||
"skip command in guild {:?} in channel {:?} by {:?}",
|
||||
interaction.guild_id,
|
||||
interaction.channel,
|
||||
interaction.author(),
|
||||
);
|
||||
|
||||
let Some(guild_id) = interaction.guild_id else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||
let call = call_lock.lock().await;
|
||||
call.queue().skip()?;
|
||||
}
|
||||
|
||||
let interaction_response_data = InteractionResponseDataBuilder::new()
|
||||
.content("Skipped a track")
|
||||
.build();
|
||||
|
||||
let response = InteractionResponse {
|
||||
kind: InteractionResponseType::ChannelMessageWithSource,
|
||||
data: Some(interaction_response_data),
|
||||
};
|
||||
|
||||
state
|
||||
.http
|
||||
.interaction(interaction.application_id)
|
||||
.create_response(interaction.id, &interaction.token, &response)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -23,6 +23,10 @@ pub(crate) async fn stop(
|
||||
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) {
|
||||
let call = call_lock.lock().await;
|
||||
call.queue().stop();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::commands::queue::{build_action_row, build_queue_embeds, TRACKS_PER_PAGE};
|
||||
use crate::commands::{delete, join, leave, pause, play, queue, resume, stop};
|
||||
use crate::commands::{
|
||||
delete, join, leave, leave_channel, loop_queue, pause, play, queue, resume, skip, stop,
|
||||
};
|
||||
use crate::state::State;
|
||||
use futures::Future;
|
||||
use std::error::Error;
|
||||
@@ -19,6 +21,8 @@ enum InteractionCommand {
|
||||
Play(String),
|
||||
Stop,
|
||||
Pause,
|
||||
Skip,
|
||||
Loop,
|
||||
Resume,
|
||||
Leave,
|
||||
Join,
|
||||
@@ -61,13 +65,7 @@ pub(crate) async fn leave_if_alone(
|
||||
|
||||
// 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?;
|
||||
leave_channel(guild_id, Arc::clone(&state)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -108,6 +106,12 @@ impl Handler {
|
||||
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)))
|
||||
}
|
||||
@@ -191,6 +195,8 @@ fn parse_interaction_command(command: &CommandData) -> InteractionCommand {
|
||||
}
|
||||
"stop" => InteractionCommand::Stop,
|
||||
"pause" => InteractionCommand::Pause,
|
||||
"skip" => InteractionCommand::Skip,
|
||||
"loop" => InteractionCommand::Loop,
|
||||
"resume" => InteractionCommand::Resume,
|
||||
"leave" => InteractionCommand::Leave,
|
||||
"join" => InteractionCommand::Join,
|
||||
|
||||
@@ -77,6 +77,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||
cache,
|
||||
songbird,
|
||||
standby: Standby::new(),
|
||||
guild_settings: Default::default(),
|
||||
}),
|
||||
)
|
||||
};
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
use songbird::typemap::TypeMapKey;
|
||||
use songbird::{input::YoutubeDl, typemap::TypeMapKey};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Metadata {
|
||||
pub(crate) title: Option<String>,
|
||||
pub(crate) duration: Option<Duration>,
|
||||
pub(crate) url: String,
|
||||
pub(crate) src: YoutubeDl,
|
||||
}
|
||||
|
||||
pub(crate) struct MetadataMap;
|
||||
|
||||
20
src/state.rs
20
src/state.rs
@@ -1,15 +1,35 @@
|
||||
use dashmap::DashMap;
|
||||
use songbird::Songbird;
|
||||
use std::sync::Arc;
|
||||
use twilight_cache_inmemory::InMemoryCache;
|
||||
use twilight_http::Client as HttpClient;
|
||||
use twilight_model::id::{marker::GuildMarker, Id};
|
||||
use twilight_standby::Standby;
|
||||
|
||||
pub(crate) type State = Arc<StateRef>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Settings {
|
||||
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)]
|
||||
pub(crate) struct StateRef {
|
||||
pub(crate) http: HttpClient,
|
||||
pub(crate) cache: InMemoryCache,
|
||||
pub(crate) songbird: Songbird,
|
||||
pub(crate) standby: Standby,
|
||||
pub(crate) guild_settings: DashMap<Id<GuildMarker>, Settings>,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user