10 Commits

Author SHA1 Message Date
c5d9c49452 improve message format
All checks were successful
tests / fmt (push) Successful in 1m50s
tests / test (push) Successful in 2m1s
tests / clippy (push) Successful in 1m59s
tests / pre-commit (push) Successful in 1m58s
tests / build (push) Successful in 2m7s
deploy / release-image (push) Successful in 5m22s
2024-06-18 17:06:33 +02:00
dbaf1a1374 reset loop state on leave/stop 2024-06-18 15:49:58 +02:00
c0d9f6cad5 update README.md
All checks were successful
tests / fmt (push) Successful in 36s
tests / build (push) Successful in 46s
tests / test (push) Successful in 54s
tests / clippy (push) Successful in 1m45s
tests / pre-commit (push) Successful in 1m52s
deploy / release-image (push) Successful in 6m23s
2024-06-18 11:51:28 +02:00
1aa0efc4a6 collect all youtube errors
All checks were successful
tests / fmt (push) Successful in 33s
tests / build (push) Successful in 45s
tests / test (push) Successful in 2m20s
tests / clippy (push) Successful in 51s
tests / pre-commit (push) Successful in 53s
deploy / release-image (push) Successful in 4m48s
2024-06-18 11:26:52 +02:00
ab7f56fe05 disable arm target (#8)
All checks were successful
tests / test (push) Successful in 1m27s
tests / clippy (push) Successful in 1m32s
tests / pre-commit (push) Successful in 1m33s
tests / fmt (push) Successful in 1m43s
tests / build (push) Successful in 1m42s
deploy / release-image (push) Successful in 4m34s
Reviewed-on: #8
2024-06-18 11:19:44 +02:00
feccbebd4d add error message for playlists that do not exist
Some checks failed
tests / fmt (push) Successful in 2m7s
tests / pre-commit (push) Successful in 2m24s
tests / clippy (push) Successful in 2m25s
tests / test (push) Successful in 2m29s
tests / build (push) Successful in 2m45s
deploy / release-image (push) Has been cancelled
2024-06-18 11:03:45 +02:00
d6a54dfc06 Merge pull request 'add error message for premium tracks' (#6) from dev into main
Some checks failed
tests / fmt (push) Successful in 1m21s
tests / build (push) Successful in 1m20s
tests / clippy (push) Successful in 1m20s
tests / pre-commit (push) Successful in 1m21s
tests / test (push) Successful in 1m34s
deploy / release-image (push) Has been cancelled
Reviewed-on: #6
2024-06-18 10:18:59 +02:00
fa17ed75f6 add error message for premium tracks
All checks were successful
tests / fmt (push) Successful in 1m23s
tests / clippy (push) Successful in 2m13s
tests / pre-commit (push) Successful in 2m11s
tests / build (push) Successful in 2m29s
tests / test (push) Successful in 2m28s
2024-06-18 10:12:48 +02:00
b19f6e552c Merge pull request 'save media source in metadata typemap' (#5) from dev into main
All checks were successful
tests / fmt (push) Successful in 2m15s
tests / build (push) Successful in 2m27s
tests / clippy (push) Successful in 2m28s
tests / pre-commit (push) Successful in 2m30s
tests / test (push) Successful in 2m57s
deploy / release-image (push) Successful in 1h2m46s
Reviewed-on: #5
2024-06-17 17:09:09 +02:00
0bee437e53 save media source in metadata typemap
All checks were successful
tests / fmt (push) Successful in 1m12s
tests / clippy (push) Successful in 1m12s
tests / pre-commit (push) Successful in 1m14s
tests / build (push) Successful in 1m30s
tests / test (push) Successful in 1m44s
2024-06-17 17:06:59 +02:00
15 changed files with 259 additions and 80 deletions

View File

@@ -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

View File

@@ -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"

View File

@@ -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 \

View File

@@ -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;

View File

@@ -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(())
} }

View File

@@ -1,6 +1,26 @@
use crate::state::State; use crate::state::{State, StateRef};
use std::error::Error; use std::{error::Error, sync::Arc};
use twilight_model::gateway::payload::incoming::InteractionCreate; 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( pub(crate) async fn leave(
interaction: Box<InteractionCreate>, interaction: Box<InteractionCreate>,
@@ -16,6 +36,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(())
} }

View File

@@ -1,6 +1,6 @@
use crate::metadata::MetadataMap;
use crate::state::{State, StateRef}; use crate::state::{State, StateRef};
use async_trait::async_trait; use async_trait::async_trait;
use songbird::input::Compose;
use songbird::{Event, EventContext, EventHandler, TrackEvent}; use songbird::{Event, EventContext, EventHandler, TrackEvent};
use std::ops::Sub; use std::ops::Sub;
use std::time::Duration; use std::time::Duration;
@@ -29,12 +29,15 @@ pub(crate) async fn loop_queue(
return Ok(()); return Ok(());
}; };
let looping = if let Some(mut settings) = state.guild_settings.get_mut(&guild_id) { state.guild_settings.entry(guild_id).and_modify(|settings| {
settings.loop_queue = !settings.loop_queue; settings.loop_queue = !settings.loop_queue;
settings.loop_queue });
} else {
false 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) { if let Some(call_lock) = state.songbird.get(guild_id) {
let mut call = call_lock.lock().await; let mut call = call_lock.lock().await;
@@ -47,10 +50,11 @@ pub(crate) async fn loop_queue(
); );
} }
let mut message = "I'm not looping anymore!".to_string(); let message = if looping {
if looping { "I'm now looping the current queue!".to_string()
message = "I'm now looping the current queue!".to_string(); } else {
} "I'm not looping anymore!".to_string()
};
let interaction_response_data = InteractionResponseDataBuilder::new() let interaction_response_data = InteractionResponseDataBuilder::new()
.content(message) .content(message)
@@ -91,29 +95,28 @@ impl EventHandler for TrackEndNotifier {
return None; return None;
}; };
let (_, track_handle) = track_list.first()?; let (_, track_handle) = track_list.first()?;
if let Some(yt) = self if let Some(call_lock) = self.state.songbird.get(self.guild_id) {
.state let mut call = call_lock.lock().await;
.tracks
.get(&self.guild_id) // get metadata from finished track
.unwrap() let old_typemap_lock = track_handle.typemap().read().await;
.get(&track_handle.uuid()) let old_metadata = old_typemap_lock.get::<MetadataMap>().unwrap();
{
let mut src = yt.clone(); // enqueue track
if let Ok(metadata) = src.aux_metadata().await { let handle = call.enqueue_with_preload(
if let Some(call_lock) = self.state.songbird.get(self.guild_id) { old_metadata.src.clone().into(),
let mut call = call_lock.lock().await; old_metadata.duration.map(|duration| -> Duration {
call.enqueue_with_preload( if duration.as_secs() > 5 {
src.into(), duration.sub(Duration::from_secs(5))
metadata.duration.map(|duration| -> Duration { } else {
if duration.as_secs() > 5 { duration
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 None
} }

View File

@@ -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_channel;
mod pause; mod pause;
pub(crate) use pause::pause; pub(crate) use pause::pause;

View File

@@ -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,19 @@ 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(stderr.into());
}
return Err("No tracks found".into());
}
tracing::debug!("tracks: {:?}", tracks); tracing::debug!("tracks: {:?}", tracks);
Ok(tracks) Ok(tracks)
} }
@@ -99,7 +115,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 +165,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
.url
.clone()
.or(yttrack.original_url.clone())
.ok_or("")?;
let mut src = YoutubeDl::new(reqwest::Client::new(), url.clone()); let mut src = YoutubeDl::new(reqwest::Client::new(), url.clone());
let s = src.clone(); let src_copy = src.clone();
let track: Track = src.clone().into(); let track: Track = src_copy.into();
state
.tracks
.entry(guild_id)
.or_default()
.insert(track.uuid, s);
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;
@@ -167,22 +212,65 @@ pub(crate) async fn play(
title: metadata.title, title: metadata.title,
duration: metadata.duration, duration: metadata.duration,
url, url,
src,
}); });
} }
} }
} }
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();
@@ -203,13 +291,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)
@@ -238,4 +327,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."));
}
}
} }

View File

@@ -27,7 +27,7 @@ pub(crate) async fn skip(
} }
let interaction_response_data = InteractionResponseDataBuilder::new() let interaction_response_data = InteractionResponseDataBuilder::new()
.content("Skipped the next track") .content("Skipped a track")
.build(); .build();
let response = InteractionResponse { let response = InteractionResponse {

View File

@@ -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();

View File

@@ -1,5 +1,7 @@
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::{
delete, join, leave, leave_channel, loop_queue, pause, play, queue, resume, skip, stop,
};
use crate::state::State; use crate::state::State;
use futures::Future; use futures::Future;
use std::error::Error; use std::error::Error;
@@ -63,13 +65,7 @@ pub(crate) async fn leave_if_alone(
// count is 1 if the bot is the only one in the channel // count is 1 if the bot is the only one in the channel
if count == 1 { if count == 1 {
// stop playing leave_channel(guild_id, Arc::clone(&state)).await?;
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(()) Ok(())
} }

View File

@@ -78,7 +78,6 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
songbird, songbird,
standby: Standby::new(), standby: Standby::new(),
guild_settings: Default::default(), guild_settings: Default::default(),
tracks: Default::default(),
}), }),
) )
}; };

View File

@@ -1,10 +1,12 @@
use songbird::typemap::TypeMapKey; use songbird::{input::YoutubeDl, typemap::TypeMapKey};
use std::time::Duration; use std::time::Duration;
#[derive(Clone)]
pub(crate) struct Metadata { pub(crate) struct Metadata {
pub(crate) title: Option<String>, pub(crate) title: Option<String>,
pub(crate) duration: Option<Duration>, pub(crate) duration: Option<Duration>,
pub(crate) url: String, pub(crate) url: String,
pub(crate) src: YoutubeDl,
} }
pub(crate) struct MetadataMap; pub(crate) struct MetadataMap;

View File

@@ -1,11 +1,10 @@
use dashmap::DashMap; use dashmap::DashMap;
use songbird::{input::YoutubeDl, Songbird}; use songbird::Songbird;
use std::sync::Arc; use std::sync::Arc;
use twilight_cache_inmemory::InMemoryCache; use twilight_cache_inmemory::InMemoryCache;
use twilight_http::Client as HttpClient; use twilight_http::Client as HttpClient;
use twilight_model::id::{marker::GuildMarker, Id}; use twilight_model::id::{marker::GuildMarker, Id};
use twilight_standby::Standby; use twilight_standby::Standby;
use uuid::Uuid;
pub(crate) type State = Arc<StateRef>; pub(crate) type State = Arc<StateRef>;
@@ -14,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,
@@ -21,5 +32,4 @@ pub(crate) struct StateRef {
pub(crate) songbird: Songbird, pub(crate) songbird: Songbird,
pub(crate) standby: Standby, pub(crate) standby: Standby,
pub(crate) guild_settings: DashMap<Id<GuildMarker>, Settings>, pub(crate) guild_settings: DashMap<Id<GuildMarker>, Settings>,
pub(crate) tracks: DashMap<Id<GuildMarker>, DashMap<Uuid, YoutubeDl>>,
} }