16 Commits

Author SHA1 Message Date
6b3629436a disable arm target
All checks were successful
tests / fmt (push) Successful in 1m14s
tests / clippy (push) Successful in 1m14s
tests / pre-commit (push) Successful in 1m14s
tests / build (push) Successful in 1m26s
tests / test (push) Successful in 1m27s
2024-06-18 11:14:42 +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
3781785a50 announce /skip and /loop commands
All checks were successful
tests / fmt (push) Successful in 2m15s
tests / pre-commit (push) Successful in 2m24s
tests / clippy (push) Successful in 2m26s
tests / build (push) Successful in 2m31s
tests / test (push) Successful in 2m48s
deploy / release-image (push) Successful in 16m8s
2024-06-17 15:40:49 +02:00
cabae9ea19 Merge pull request 'add /skip and /loop commands' (#4) from dev into main
All checks were successful
tests / fmt (push) Successful in 1m15s
tests / build (push) Successful in 1m19s
tests / clippy (push) Successful in 1m16s
tests / pre-commit (push) Successful in 1m25s
tests / test (push) Successful in 1m38s
deploy / release-image (push) Successful in 16m38s
Reviewed-on: #4
2024-06-17 15:16:32 +02:00
54c36688b7 add loop command
All checks were successful
tests / fmt (push) Successful in 57s
tests / clippy (push) Successful in 1m16s
tests / pre-commit (push) Successful in 1m14s
tests / build (push) Successful in 1m30s
tests / test (push) Successful in 1m36s
2024-06-17 15:14:22 +02:00
55fe212424 add skip command 2024-06-13 20:42:53 +02:00
2c91c744dc Merge pull request 'paginate /queue' (#3) from dev into main
All checks were successful
tests / fmt (push) Successful in 1m30s
tests / build (push) Successful in 1m36s
tests / test (push) Successful in 1m41s
tests / clippy (push) Successful in 1m39s
tests / pre-commit (push) Successful in 1m37s
deploy / release-image (push) Successful in 1h1m56s
Reviewed-on: #3
2024-06-13 00:54:17 +02:00
a0ac87959b paginate /queue
All checks were successful
tests / fmt (push) Successful in 2m15s
tests / fmt (pull_request) Successful in 1m35s
tests / test (push) Successful in 2m39s
tests / pre-commit (push) Successful in 2m37s
tests / clippy (push) Successful in 2m44s
tests / build (push) Successful in 3m4s
tests / clippy (pull_request) Successful in 2m49s
tests / build (pull_request) Successful in 2m53s
tests / test (pull_request) Successful in 2m51s
tests / pre-commit (pull_request) Successful in 1m34s
2024-06-13 00:49:11 +02:00
b4a1efb22a Merge pull request 'use discord embeds in messages' (#2) from dev into main
All checks were successful
tests / fmt (push) Successful in 1m11s
tests / build (push) Successful in 42s
tests / test (push) Successful in 1m50s
tests / clippy (push) Successful in 3m30s
tests / pre-commit (push) Successful in 2m26s
deploy / release-image (push) Successful in 59m13s
Reviewed-on: #2
2024-06-10 23:59:41 +02:00
e831ede37c use discord embeds in messages
All checks were successful
tests / fmt (push) Successful in 3m17s
tests / fmt (pull_request) Successful in 2m35s
tests / test (push) Successful in 3m17s
tests / test (pull_request) Successful in 2m39s
tests / build (push) Successful in 3m26s
tests / clippy (push) Successful in 3m33s
tests / clippy (pull_request) Successful in 2m57s
tests / build (pull_request) Successful in 3m5s
tests / pre-commit (push) Successful in 4m16s
tests / pre-commit (pull_request) Successful in 1m29s
2024-06-10 23:41:29 +02:00
1ca7d5204d make run tests before deploy
All checks were successful
tests / fmt (push) Successful in 38s
tests / build (push) Successful in 47s
tests / test (push) Successful in 40s
tests / clippy (push) Successful in 46s
tests / pre-commit (push) Successful in 44s
deploy / release-image (push) Successful in 1h11m43s
2024-06-08 13:12:32 +02:00
4177cd073a Merge pull request 'Improve readme' (#1) from dev into main
All checks were successful
release / release-image (push) Successful in 58m12s
Rust / build (push) Successful in 5m38s
Rust / test (push) Successful in 1m10s
Rust / clippy (push) Successful in 39s
Rust / fmt (push) Successful in 1m53s
Rust / pre-commit (push) Successful in 43s
Reviewed-on: #1
2024-06-07 15:32:29 +02:00
21 changed files with 1413 additions and 564 deletions

View File

@@ -1,13 +1,27 @@
name: Rust name: tests
on: on:
push: push:
pull_request:
paths-ignore:
- 'README.md'
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always
jobs: jobs:
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
components: rustfmt
- name: Rustfmt Check
uses: actions-rust-lang/rustfmt@v1
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -24,6 +38,11 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- run: sudo apt-get update - run: sudo apt-get update
- run: sudo apt-get install -y cmake - 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 - uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Run tests - name: Run tests
run: cargo test --verbose --all-features run: cargo test --verbose --all-features
@@ -40,18 +59,6 @@ jobs:
- name: Run clippy - name: Run clippy
run: cargo clippy run: cargo clippy
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
components: rustfmt
- name: Rustfmt Check
uses: actions-rust-lang/rustfmt@v1
pre-commit: pre-commit:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:

View File

@@ -1,4 +1,4 @@
name: release name: deploy
on: on:
push: push:
@@ -26,6 +26,6 @@ jobs:
with: with:
platforms: | platforms: |
linux/amd64 linux/amd64
linux/arm64 # linux/arm64
push: true push: true
tags: jheuel/ohrwurm:latest tags: jheuel/ohrwurm:latest

View File

@@ -1,4 +1,4 @@
name: Rust name: tests
on: on:
push: push:
@@ -9,6 +9,18 @@ env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always
jobs: jobs:
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
components: rustfmt
- name: Rustfmt Check
uses: actions-rust-lang/rustfmt@v1
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -25,6 +37,11 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- run: sudo apt-get update - run: sudo apt-get update
- run: sudo apt-get install -y cmake - 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 - uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Run tests - name: Run tests
run: cargo test --verbose --all-features run: cargo test --verbose --all-features
@@ -41,18 +58,6 @@ jobs:
- name: Run clippy - name: Run clippy
run: cargo clippy run: cargo clippy
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
components: rustfmt
- name: Rustfmt Check
uses: actions-rust-lang/rustfmt@v1
pre-commit: pre-commit:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:

1035
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -21,5 +21,10 @@ twilight-standby = "0.15"
twilight-cache-inmemory = "0.15" twilight-cache-inmemory = "0.15"
twilight-util = { version = "0.15", features=["builder"] } twilight-util = { version = "0.15", features=["builder"] }
dotenv = "0.15.0" dotenv = "0.15.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
url = "2.5.0" url = "2.5.0"
anyhow = "1.0.86"
dashmap = "5.5.3"
async-trait = "0.1.80"
uuid = "1.8.0"

20
src/colors.rs Normal file
View File

@@ -0,0 +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;

View File

@@ -9,14 +9,14 @@ pub(crate) async fn delete(
state: State, state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let admin = env::var("ADMIN")?.parse::<u64>()?; let admin = env::var("ADMIN")?.parse::<u64>()?;
if msg.author.id != Id::from(NonZeroU64::new(admin).unwrap()) { if msg.author.id != Id::from(NonZeroU64::new(admin).expect("Could not get author id")) {
return Ok(()); return Ok(());
} }
let n = msg let n = msg
.content .content
.split(' ') .split(' ')
.last() .last()
.unwrap() .unwrap_or("1")
.parse::<u16>() .parse::<u16>()
.unwrap_or(1); .unwrap_or(1);
if n > 100 { if n > 100 {

View File

@@ -2,8 +2,8 @@ use crate::state::State;
use std::error::Error; use std::error::Error;
use tracing::debug; use tracing::debug;
use twilight_model::{ use twilight_model::{
application::interaction::Interaction,
channel::message::MessageFlags, channel::message::MessageFlags,
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType}, http::interaction::{InteractionResponse, InteractionResponseType},
id::{ id::{
marker::{GuildMarker, UserMarker}, marker::{GuildMarker, UserMarker},
@@ -42,7 +42,7 @@ pub(crate) async fn join_channel(
} }
pub(crate) async fn join( pub(crate) async fn join(
interaction: Interaction, interaction: Box<InteractionCreate>,
state: State, state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
debug!( debug!(

View File

@@ -1,9 +1,9 @@
use crate::state::State; use crate::state::State;
use std::error::Error; use std::error::Error;
use twilight_model::application::interaction::Interaction; use twilight_model::gateway::payload::incoming::InteractionCreate;
pub(crate) async fn leave( pub(crate) async fn leave(
interaction: Interaction, interaction: Box<InteractionCreate>,
state: State, state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!( tracing::debug!(

129
src/commands/loop_queue.rs Normal file
View File

@@ -0,0 +1,129 @@
use crate::metadata::MetadataMap;
use crate::state::{Settings, 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)
.or_insert_with(|| Settings { loop_queue: false });
state.guild_settings.entry(guild_id).and_modify(|settings| {
settings.loop_queue = !settings.loop_queue;
println!("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
}
}

View File

@@ -7,10 +7,16 @@ pub(crate) use leave::leave;
mod pause; mod pause;
pub(crate) use pause::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; mod play;
pub(crate) use play::play; pub(crate) use play::play;
mod queue; pub(crate) mod queue;
pub(crate) use queue::queue; pub(crate) use queue::queue;
mod resume; mod resume;
@@ -29,12 +35,14 @@ pub(crate) fn get_chat_commands() -> Vec<twilight_model::application::command::C
vec![ vec![
CommandBuilder::new("join", "Join the channel", CommandType::ChatInput).build(), CommandBuilder::new("join", "Join the channel", CommandType::ChatInput).build(),
CommandBuilder::new("leave", "Leave 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("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) CommandBuilder::new("play", "Add a song to the queue", CommandType::ChatInput)
.option(StringBuilder::new("query", "URL of a song").required(true)) .option(StringBuilder::new("query", "URL of a song").required(true))
.build(), .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(),
] ]
} }

View File

@@ -1,14 +1,14 @@
use crate::state::State; use crate::state::State;
use std::error::Error; use std::error::Error;
use twilight_model::{ use twilight_model::{
application::interaction::Interaction,
channel::message::MessageFlags, channel::message::MessageFlags,
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType}, http::interaction::{InteractionResponse, InteractionResponseType},
}; };
use twilight_util::builder::InteractionResponseDataBuilder; use twilight_util::builder::InteractionResponseDataBuilder;
pub(crate) async fn pause( pub(crate) async fn pause(
interaction: Interaction, interaction: Box<InteractionCreate>,
state: State, state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!( tracing::debug!(

View File

@@ -1,19 +1,70 @@
use crate::colors;
use crate::commands::join::join_channel; use crate::commands::join::join_channel;
use crate::metadata::{Metadata, MetadataMap}; use crate::metadata::{Metadata, MetadataMap};
use crate::state::State; use crate::state::State;
use serde_json::Value;
use serde::{Deserialize, Serialize};
use songbird::input::{Compose, YoutubeDl}; use songbird::input::{Compose, YoutubeDl};
use songbird::tracks::Track;
use std::io::{BufRead, BufReader}; 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 tokio::process::Command;
use tracing::debug; use tracing::debug;
use twilight_model::application::interaction::Interaction; use twilight_model::channel::message::MessageFlags;
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::embed::EmbedBuilder;
use twilight_util::builder::InteractionResponseDataBuilder; use twilight_util::builder::InteractionResponseDataBuilder;
use url::Url; use url::Url;
#[derive(Debug, Serialize, Deserialize)]
struct YouTubeTrack {
url: Option<String>,
original_url: Option<String>,
title: String,
channel: String,
playlist: Option<String>,
playlist_id: Option<String>,
duration_string: String,
}
fn build_playlist_url(playlist_id: &str) -> String {
format!("https://www.youtube.com/playlist?list={}", playlist_id)
}
async fn get_tracks(
url: String,
) -> Result<Vec<YouTubeTrack>, Box<dyn Error + Send + Sync + 'static>> {
let output = Command::new("yt-dlp")
.args(vec![&url, "--flat-playlist", "-j"])
.output()
.await?;
let reader = BufReader::new(output.stdout.as_slice());
let tracks: Vec<YouTubeTrack> = reader
.lines()
.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("No tracks found".into());
}
tracing::debug!("tracks: {:?}", tracks);
Ok(tracks)
}
pub(crate) async fn play( pub(crate) async fn play(
interaction: Interaction, interaction: Box<InteractionCreate>,
state: State, state: State,
query: String, query: String,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
@@ -23,11 +74,17 @@ pub(crate) async fn play(
interaction.author(), interaction.author(),
); );
let content = format!("Adding track(s) to the queue: {}", query);
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::YELLOW)
.build()];
let interaction_response_data = InteractionResponseDataBuilder::new() let interaction_response_data = InteractionResponseDataBuilder::new()
.content(format!("Adding track(s) to queue: {}", query)) .flags(MessageFlags::LOADING)
.embeds(embeds)
.build(); .build();
let response = InteractionResponse { let response = InteractionResponse {
kind: InteractionResponseType::ChannelMessageWithSource, kind: InteractionResponseType::DeferredChannelMessageWithSource,
data: Some(interaction_response_data), data: Some(interaction_response_data),
}; };
state state
@@ -54,29 +111,72 @@ pub(crate) async fn play(
debug!("query: {:?}", query); debug!("query: {:?}", query);
// handle playlist links let tracks = match get_tracks(query).await {
let urls = if query.contains("list=") { Err(e) => {
get_playlist_urls(query).await? let content = format!("{}", e);
} else { let embeds = vec![EmbedBuilder::new()
vec![query] .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
.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)
.color(colors::BLURPLE)
.build()];
state
.http
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.await?;
}
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().resume()?; call.queue().resume()?;
} }
let mut tracks_added = vec![]; let mut tracks_added = vec![];
for url in urls { for track in &tracks {
let mut src = YoutubeDl::new(reqwest::Client::new(), url.to_string()); tracing::debug!("track: {:?}", track);
let url = track.url.clone().or(track.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 { if let Ok(metadata) = src.aux_metadata().await {
debug!("metadata: {:?}", metadata); debug!("metadata: {:?}", metadata);
tracks_added.push(metadata.title.clone()); tracks_added.push((url.clone(), metadata.title.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;
let handle = call.enqueue_with_preload( let handle = call.enqueue_with_preload(
src.into(), track,
metadata.duration.map(|duration| -> Duration { metadata.duration.map(|duration| -> Duration {
if duration.as_secs() > 5 { if duration.as_secs() > 5 {
duration.sub(Duration::from_secs(5)) duration.sub(Duration::from_secs(5))
@@ -89,6 +189,8 @@ pub(crate) async fn play(
x.insert::<MetadataMap>(Metadata { x.insert::<MetadataMap>(Metadata {
title: metadata.title, title: metadata.title,
duration: metadata.duration, duration: metadata.duration,
url,
src,
}); });
} }
} }
@@ -98,51 +200,96 @@ pub(crate) async fn play(
match num_tracks_added { match num_tracks_added {
0 => {} 0 => {}
1 => { 1 => {
content = format!( let (title, url) = if let Some(track) = tracks_added.first() {
"Added \"{}\" to queue", let track = track.clone();
tracks_added.first().unwrap().clone().unwrap() (track.1.unwrap_or("Unknown".to_string()), track.0)
); } else {
("Unknown".to_string(), "".to_string())
};
content = format!("Added [{}]({}) to the queue", title, url);
} }
_ => { _ => {
content = format!("Added {} tracks to queue:\n", num_tracks_added); let first_track = tracks.first().unwrap();
for track in tracks_added.into_iter().take(num_tracks_added.min(3)) { content.push_str(&format!(
content.push_str(&format!(" \"{}\"\n", track.unwrap())); "Adding playlist: [{}]({})\n",
} &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 embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::BLURPLE)
.build()];
state state
.http .http
.interaction(interaction.application_id) .interaction(interaction.application_id)
.update_response(&interaction.token) .update_response(&interaction.token)
.content(Some(&content)) .embeds(Some(&embeds))?
.unwrap()
.await?; .await?;
Ok(()) Ok(())
} }
async fn get_playlist_urls( #[cfg(test)]
url: String, mod tests {
) -> Result<Vec<String>, Box<dyn Error + Send + Sync + 'static>> { use super::*;
let output = Command::new("yt-dlp")
.args(vec![&url, "--flat-playlist", "-j"])
.output()
.await?;
let reader = BufReader::new(output.stdout.as_slice()); #[tokio::test]
let urls = reader async fn test_get_tracks() {
.lines() let urls = [
.map_while(Result::ok) "https://www.youtube.com/playlist?list=PLFxxhcEeloYa1OlnWD6UgxlVQKJH5i_0p",
.map(|line| { "https://music.youtube.com/watch?v=RO75ZzqUOJw",
let entry: Value = serde_json::from_str(&line).unwrap(); "https://www.youtube.com/watch?v=qVHyl0P_P-M",
entry "https://www.youtube.com/watch?v=34CZjsEI1yU",
.get("webpage_url") ];
.unwrap() for url in urls.iter() {
.as_str() 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() .unwrap()
.to_string() .to_string()
}) .contains("This video is only available to Music Premium members"));
.collect(); }
}
Ok(urls) #[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

@@ -1,15 +1,106 @@
use songbird::tracks::TrackHandle;
use twilight_model::channel::message::component::{ActionRow, Button, ButtonStyle};
use twilight_model::channel::message::{Component, Embed, MessageFlags, ReactionType};
use twilight_model::gateway::payload::incoming::InteractionCreate;
use twilight_model::http::interaction::InteractionResponse;
use twilight_model::http::interaction::InteractionResponseType; use twilight_model::http::interaction::InteractionResponseType;
use twilight_model::{ use twilight_util::builder::embed::EmbedBuilder;
application::interaction::Interaction, channel::message::MessageFlags,
http::interaction::InteractionResponse,
};
use twilight_util::builder::InteractionResponseDataBuilder; use twilight_util::builder::InteractionResponseDataBuilder;
use crate::colors;
use crate::{metadata::MetadataMap, state::State}; use crate::{metadata::MetadataMap, state::State};
use std::error::Error; use std::error::Error;
pub(crate) const TRACKS_PER_PAGE: usize = 5;
fn format_duration(duration: std::time::Duration) -> String {
let res = duration.as_secs();
let hours = res / (60 * 60);
let res = res - hours * 60 * 60;
let minutes = res / 60;
let res = res - minutes * 60;
let seconds = res;
let mut s = String::new();
if hours > 0 {
s.push_str(format!("{:02}:", hours).as_str());
}
s.push_str(format!("{:02}:{:02}", minutes, seconds).as_str());
s
}
pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Vec<Embed> {
let mut message = String::new();
if queue.is_empty() {
message.push_str("There are no tracks in the queue.\n");
}
for track in queue
.iter()
.skip(TRACKS_PER_PAGE * page)
.take(TRACKS_PER_PAGE)
{
let map = track.typemap().read().await;
let metadata = map
.get::<MetadataMap>()
.expect("Could not get metadata map");
message.push_str(
format!(
"* [{}]({})",
metadata.title.clone().unwrap_or("Unknown".to_string()),
metadata.url,
)
.as_str(),
);
if let Some(duration) = metadata.duration {
message.push_str(" (");
message.push_str(&format_duration(duration));
message.push(')');
}
message.push('\n');
}
message.push('\n');
let max_pages = queue.len() / TRACKS_PER_PAGE;
if max_pages > 0 {
message.push_str(&format!("page {}/{}", 1 + page, 1 + max_pages));
}
vec![EmbedBuilder::new()
.description(&message)
.color(colors::BLURPLE)
.build()]
}
pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component> {
if max_pages == 0 {
return Vec::new();
}
vec![Component::ActionRow(ActionRow {
components: vec![
Component::Button(Button {
custom_id: Some(format!("page:{}", page as i32 - 1)),
style: ButtonStyle::Primary,
label: Some("Previous page".to_string()),
emoji: Some(ReactionType::Unicode {
name: "⬅️".to_string(),
}),
url: None,
disabled: page == 0,
}),
Component::Button(Button {
custom_id: Some(format!("page:{}", page + 1)),
style: ButtonStyle::Primary,
label: Some("Next page".to_string()),
emoji: Some(ReactionType::Unicode {
name: "➡️".to_string(),
}),
url: None,
disabled: page >= max_pages,
}),
],
})]
}
pub(crate) async fn queue( pub(crate) async fn queue(
interaction: Interaction, interaction: Box<InteractionCreate>,
state: State, state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!( tracing::debug!(
@@ -21,57 +112,42 @@ pub(crate) async fn queue(
let Some(guild_id) = interaction.guild_id else { let Some(guild_id) = interaction.guild_id else {
return Ok(()); return Ok(());
}; };
let content = "Fetching queue".to_string();
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::YELLOW)
.build()];
let interaction_response_data = InteractionResponseDataBuilder::new()
.embeds(embeds)
.flags(MessageFlags::LOADING)
.build();
let response = InteractionResponse {
kind: InteractionResponseType::DeferredChannelMessageWithSource,
data: Some(interaction_response_data),
};
state
.http
.interaction(interaction.application_id)
.create_response(interaction.id, &interaction.token, &response)
.await?;
let mut queue = Vec::new();
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;
let queue = call.queue().current_queue(); queue = call.queue().current_queue();
let mut message = String::new();
if queue.is_empty() {
message.push_str("There are no tracks in the queue.\n");
} else {
message.push_str("Next songs are:\n");
}
for track in queue.iter().take(5) {
let map = track.typemap().read().await;
let metadata = map.get::<MetadataMap>().unwrap();
message.push_str(
format!(
"* `{}",
metadata.title.clone().unwrap_or("Unknown".to_string()),
)
.as_str(),
);
if let Some(duration) = metadata.duration {
let res = duration.as_secs();
let hours = res / (60 * 60);
let res = res - hours * 60 * 60;
let minutes = res / 60;
let res = res - minutes * 60;
let seconds = res;
message.push_str(" (");
if hours > 0 {
message.push_str(format!("{:02}:", hours).as_str());
}
message.push_str(format!("{:02}:{:02}", minutes, seconds).as_str());
message.push(')');
}
message.push_str("`\n");
}
let interaction_response_data = InteractionResponseDataBuilder::new()
.content(&message)
.flags(MessageFlags::EPHEMERAL)
.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?;
} }
let embeds = build_queue_embeds(&queue, 0).await;
let action_row = build_action_row(0, queue.len() / TRACKS_PER_PAGE);
state
.http
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.components(Some(&action_row))?
.await?;
Ok(()) Ok(())
} }

View File

@@ -1,14 +1,14 @@
use crate::state::State; use crate::state::State;
use std::error::Error; use std::error::Error;
use twilight_model::{ use twilight_model::{
application::interaction::Interaction,
channel::message::MessageFlags, channel::message::MessageFlags,
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType}, http::interaction::{InteractionResponse, InteractionResponseType},
}; };
use twilight_util::builder::InteractionResponseDataBuilder; use twilight_util::builder::InteractionResponseDataBuilder;
pub(crate) async fn resume( pub(crate) async fn resume(
interaction: Interaction, interaction: Box<InteractionCreate>,
state: State, state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!( tracing::debug!(

45
src/commands/skip.rs Normal file
View 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(())
}

View File

@@ -1,6 +1,6 @@
use twilight_model::{ use twilight_model::{
application::interaction::Interaction,
channel::message::MessageFlags, channel::message::MessageFlags,
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType}, http::interaction::{InteractionResponse, InteractionResponseType},
}; };
use twilight_util::builder::InteractionResponseDataBuilder; use twilight_util::builder::InteractionResponseDataBuilder;
@@ -9,7 +9,7 @@ use crate::state::State;
use std::error::Error; use std::error::Error;
pub(crate) async fn stop( pub(crate) async fn stop(
interaction: Interaction, interaction: Box<InteractionCreate>,
state: State, state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!( tracing::debug!(

View File

@@ -1,23 +1,30 @@
use crate::commands::{delete, join, leave, pause, play, queue, resume, stop}; 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::state::State; use crate::state::State;
use futures::Future; use futures::Future;
use std::error::Error; use std::error::Error;
use std::sync::Arc; use std::sync::Arc;
use tracing::debug; use tracing::debug;
use twilight_gateway::Event; use twilight_gateway::Event;
use twilight_model::application::interaction::application_command::CommandOptionValue; use twilight_model::application::interaction::application_command::{
use twilight_model::application::interaction::{Interaction, InteractionData}; CommandData, CommandOptionValue,
};
use twilight_model::application::interaction::InteractionData;
use twilight_model::gateway::payload::incoming::VoiceStateUpdate; use twilight_model::gateway::payload::incoming::VoiceStateUpdate;
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
use twilight_util::builder::InteractionResponseDataBuilder;
#[derive(Debug)] #[derive(Debug)]
enum InteractionCommand { enum InteractionCommand {
Play(Interaction, String), Play(String),
Stop(Interaction), Stop,
Pause(Interaction), Pause,
Resume(Interaction), Skip,
Leave(Interaction), Loop,
Join(Interaction), Resume,
Queue(Interaction), Leave,
Join,
Queue,
NotImplemented, NotImplemented,
} }
@@ -75,80 +82,129 @@ impl Handler {
pub(crate) fn new(state: State) -> Self { pub(crate) fn new(state: State) -> Self {
Self { state } Self { state }
} }
pub(crate) async fn act(&self, event: Event) { pub(crate) async fn act(&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") {
spawn(delete(message.0.clone(), Arc::clone(&self.state))); spawn(delete(message.0.clone(), Arc::clone(&self.state)));
} }
Ok(())
} }
Event::VoiceStateUpdate(update) => { Event::VoiceStateUpdate(update) => {
spawn(leave_if_alone(*update.clone(), Arc::clone(&self.state))) spawn(leave_if_alone(*update.clone(), Arc::clone(&self.state)));
Ok(())
} }
_ => {}
}
let interaction_command = match event {
Event::InteractionCreate(interaction) => { Event::InteractionCreate(interaction) => {
debug!("interaction: {:?}", &interaction); tracing::info!("interaction: {:?}", &interaction);
match &interaction.data { match &interaction.data {
Some(InteractionData::ApplicationCommand(command)) => { Some(InteractionData::ApplicationCommand(command)) => {
debug!("command: {:?}", command); let interaction_command = parse_interaction_command(command);
match command.name.as_str() { debug!("{:?}", interaction_command);
"play" => { match interaction_command {
if let Some(query_option) = InteractionCommand::Play(query) => {
command.options.iter().find(|opt| opt.name == "query") spawn(play(interaction, Arc::clone(&self.state), query))
{
if let CommandOptionValue::String(query) = &query_option.value {
InteractionCommand::Play(
interaction.0.clone(),
query.clone(),
)
} else {
InteractionCommand::NotImplemented
}
} else {
InteractionCommand::NotImplemented
}
} }
"stop" => InteractionCommand::Stop(interaction.0.clone()), InteractionCommand::Stop => {
"pause" => InteractionCommand::Pause(interaction.0.clone()), spawn(stop(interaction, Arc::clone(&self.state)))
"resume" => InteractionCommand::Resume(interaction.0.clone()), }
"leave" => InteractionCommand::Leave(interaction.0.clone()), InteractionCommand::Pause => {
"join" => InteractionCommand::Join(interaction.0.clone()), spawn(pause(interaction, Arc::clone(&self.state)))
"queue" => InteractionCommand::Queue(interaction.0.clone()), }
_ => InteractionCommand::NotImplemented, 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:") {
return Ok(());
}
let page = data
.custom_id
.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(())
} }
} }
_ => InteractionCommand::NotImplemented, _ => Ok(()),
} }
} }
_ => InteractionCommand::NotImplemented, event => {
}; tracing::info!("unhandled event: {:?}", event);
debug!("{:?}", interaction_command); Ok(())
match interaction_command {
InteractionCommand::Play(interaction, query) => {
spawn(play(interaction, Arc::clone(&self.state), query))
} }
InteractionCommand::Stop(interaction) => { }
spawn(stop(interaction, Arc::clone(&self.state))) }
} }
InteractionCommand::Pause(interaction) => {
spawn(pause(interaction, Arc::clone(&self.state))) fn parse_interaction_command(command: &CommandData) -> InteractionCommand {
} debug!("command: {:?}", command);
InteractionCommand::Resume(interaction) => { match command.name.as_str() {
spawn(resume(interaction, Arc::clone(&self.state))) "play" => {
} if let Some(query_option) = command.options.iter().find(|opt| opt.name == "query") {
InteractionCommand::Leave(interaction) => { if let CommandOptionValue::String(query) = &query_option.value {
spawn(leave(interaction, Arc::clone(&self.state))) InteractionCommand::Play(query.clone())
} } else {
InteractionCommand::Join(interaction) => { InteractionCommand::NotImplemented
spawn(join(interaction, Arc::clone(&self.state))) }
} } else {
InteractionCommand::Queue(interaction) => { InteractionCommand::NotImplemented
spawn(queue(interaction, Arc::clone(&self.state))) }
} }
_ => {} "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,
} }
} }

View File

@@ -1,9 +1,11 @@
mod handler; mod handler;
use handler::Handler; use handler::Handler;
mod colors;
mod commands; mod commands;
mod metadata; mod metadata;
mod signal; mod signal;
mod state; mod state;
use crate::commands::get_chat_commands; use crate::commands::get_chat_commands;
use dotenv::dotenv; use dotenv::dotenv;
use futures::StreamExt; use futures::StreamExt;
@@ -75,6 +77,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
cache, cache,
songbird, songbird,
standby: Standby::new(), standby: Standby::new(),
guild_settings: Default::default(),
}), }),
) )
}; };
@@ -118,7 +121,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
state.standby.process(&event); state.standby.process(&event);
state.songbird.process(&event).await; state.songbird.process(&event).await;
handler.act(event).await; handler.act(event).await?;
} }
} }
} }

View File

@@ -1,9 +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) src: YoutubeDl,
} }
pub(crate) struct MetadataMap; pub(crate) struct MetadataMap;

View File

@@ -1,15 +1,23 @@
use dashmap::DashMap;
use songbird::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_standby::Standby; use twilight_standby::Standby;
pub(crate) type State = Arc<StateRef>; pub(crate) type State = Arc<StateRef>;
#[derive(Debug)]
pub(crate) struct Settings {
pub(crate) loop_queue: bool,
}
#[derive(Debug)] #[derive(Debug)]
pub(crate) struct StateRef { pub(crate) struct StateRef {
pub(crate) http: HttpClient, pub(crate) http: HttpClient,
pub(crate) cache: InMemoryCache, pub(crate) cache: InMemoryCache,
pub(crate) songbird: Songbird, pub(crate) songbird: Songbird,
pub(crate) standby: Standby, pub(crate) standby: Standby,
pub(crate) guild_settings: DashMap<Id<GuildMarker>, Settings>,
} }