update twilight, songbird and reqwest
This commit is contained in:
1019
Cargo.lock
generated
1019
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
16
Cargo.toml
16
Cargo.toml
@@ -7,20 +7,20 @@ license = "MIT"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
symphonia = { version = "0.5.2", features=["all", "opt-simd"] }
|
symphonia = { version = "0.5.2", features=["all", "opt-simd"] }
|
||||||
songbird = { version = "0.4.0", features = ["driver", "gateway", "twilight", "rustls", "builtin-queue"] }
|
songbird = { version = "0.5.0", features = ["driver", "gateway", "twilight", "rustls", "builtin-queue"] }
|
||||||
tokio = { features = ["macros", "rt-multi-thread", "signal", "sync"], version = "1" }
|
tokio = { features = ["macros", "rt-multi-thread", "signal", "sync"], version = "1" }
|
||||||
sqlx = { version = "0.7", features = [ "runtime-tokio", "sqlite", "chrono", "migrate"] }
|
sqlx = { version = "0.7", features = [ "runtime-tokio", "sqlite", "chrono", "migrate"] }
|
||||||
regex = { version = "1", features = ["unicode-case"] }
|
regex = { version = "1", features = ["unicode-case"] }
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
reqwest = "0.11"
|
reqwest = "0.12"
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = "0.2"
|
tracing-subscriber = "0.2"
|
||||||
twilight-gateway = "0.15"
|
twilight-gateway = "0.16"
|
||||||
twilight-http = "0.15"
|
twilight-http = "0.16"
|
||||||
twilight-model = "0.15"
|
twilight-model = "0.16"
|
||||||
twilight-standby = "0.15"
|
twilight-standby = "0.16"
|
||||||
twilight-cache-inmemory = "0.15"
|
twilight-cache-inmemory = "0.16"
|
||||||
twilight-util = { version = "0.15", features=["builder"] }
|
twilight-util = { version = "0.16", 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"
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ pub(crate) async fn delete(
|
|||||||
.http
|
.http
|
||||||
.channel_messages(msg.channel_id)
|
.channel_messages(msg.channel_id)
|
||||||
.before(msg.id)
|
.before(msg.id)
|
||||||
.limit(n)?
|
.limit(n)
|
||||||
.await?
|
.await?
|
||||||
.model()
|
.model()
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::metadata::MetadataMap;
|
use crate::metadata::Metadata;
|
||||||
use crate::state::{State, StateRef};
|
use crate::state::{State, StateRef};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use songbird::{Event, EventContext, EventHandler, TrackEvent};
|
use songbird::{Event, EventContext, EventHandler, TrackEvent};
|
||||||
@@ -99,9 +99,7 @@ impl EventHandler for TrackEndNotifier {
|
|||||||
let mut call = call_lock.lock().await;
|
let mut call = call_lock.lock().await;
|
||||||
|
|
||||||
// get metadata from finished track
|
// get metadata from finished track
|
||||||
let old_typemap_lock = track_handle.typemap().read().await;
|
let old_metadata = track_handle.data::<Metadata>();
|
||||||
let old_metadata = old_typemap_lock.get::<MetadataMap>().unwrap();
|
|
||||||
|
|
||||||
// enqueue track
|
// enqueue track
|
||||||
let handle = call.enqueue_with_preload(
|
let handle = call.enqueue_with_preload(
|
||||||
old_metadata.src.clone().into(),
|
old_metadata.src.clone().into(),
|
||||||
@@ -115,8 +113,8 @@ impl EventHandler for TrackEndNotifier {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// insert metadata into new track
|
// insert metadata into new track
|
||||||
let mut new_typemap = handle.typemap().write().await;
|
let mut _new_metadata = handle.data::<Metadata>();
|
||||||
new_typemap.insert::<MetadataMap>(old_metadata.clone());
|
_new_metadata = old_metadata.clone();
|
||||||
}
|
}
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::commands::join::join_channel;
|
use crate::commands::join::join_channel;
|
||||||
use crate::metadata::{Metadata, MetadataMap};
|
use crate::metadata::Metadata;
|
||||||
use crate::state::State;
|
use crate::state::State;
|
||||||
use crate::{colors, db};
|
use crate::{colors, db};
|
||||||
|
|
||||||
@@ -266,7 +266,7 @@ pub(crate) async fn play(
|
|||||||
.http
|
.http
|
||||||
.interaction(interaction.application_id)
|
.interaction(interaction.application_id)
|
||||||
.update_response(&interaction.token)
|
.update_response(&interaction.token)
|
||||||
.embeds(Some(&embeds))?
|
.embeds(Some(&embeds))
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -348,7 +348,7 @@ pub(crate) async fn play_inner(
|
|||||||
.http
|
.http
|
||||||
.interaction(interaction.application_id)
|
.interaction(interaction.application_id)
|
||||||
.update_response(&interaction.token)
|
.update_response(&interaction.token)
|
||||||
.embeds(Some(&embeds))?
|
.embeds(Some(&embeds))
|
||||||
.await
|
.await
|
||||||
.context("Could not send playlist loading message")?;
|
.context("Could not send playlist loading message")?;
|
||||||
}
|
}
|
||||||
@@ -401,8 +401,8 @@ pub(crate) async fn play_inner(
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
let mut x = handle.typemap().write().await;
|
let mut _x = handle.data::<Metadata>();
|
||||||
x.insert::<MetadataMap>(Metadata {
|
_x = Arc::new(Metadata {
|
||||||
title: metadata.title,
|
title: metadata.title,
|
||||||
duration: metadata.duration,
|
duration: metadata.duration,
|
||||||
url,
|
url,
|
||||||
@@ -427,7 +427,7 @@ pub(crate) async fn play_inner(
|
|||||||
.http
|
.http
|
||||||
.interaction(interaction.application_id)
|
.interaction(interaction.application_id)
|
||||||
.update_response(&interaction.token)
|
.update_response(&interaction.token)
|
||||||
.embeds(Some(&embeds))?
|
.embeds(Some(&embeds))
|
||||||
.await?;
|
.await?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -440,7 +440,7 @@ pub(crate) async fn play_inner(
|
|||||||
.http
|
.http
|
||||||
.interaction(interaction.application_id)
|
.interaction(interaction.application_id)
|
||||||
.update_response(&interaction.token)
|
.update_response(&interaction.token)
|
||||||
.embeds(Some(&embeds))?
|
.embeds(Some(&embeds))
|
||||||
.await
|
.await
|
||||||
.context("Could not send final play message")?;
|
.context("Could not send final play message")?;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use songbird::tracks::TrackHandle;
|
use songbird::tracks::TrackHandle;
|
||||||
use twilight_model::channel::message::component::{ActionRow, Button, ButtonStyle};
|
use twilight_model::channel::message::component::{ActionRow, Button, ButtonStyle};
|
||||||
use twilight_model::channel::message::{Component, Embed, MessageFlags, ReactionType};
|
use twilight_model::channel::message::{Component, Embed, EmojiReactionType, MessageFlags};
|
||||||
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
||||||
use twilight_model::http::interaction::InteractionResponse;
|
use twilight_model::http::interaction::InteractionResponse;
|
||||||
use twilight_model::http::interaction::InteractionResponseType;
|
use twilight_model::http::interaction::InteractionResponseType;
|
||||||
@@ -8,7 +8,8 @@ use twilight_util::builder::embed::EmbedBuilder;
|
|||||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
|
|
||||||
use crate::colors;
|
use crate::colors;
|
||||||
use crate::{metadata::MetadataMap, state::State};
|
use crate::metadata::Metadata;
|
||||||
|
use crate::state::State;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
pub(crate) const TRACKS_PER_PAGE: usize = 5;
|
pub(crate) const TRACKS_PER_PAGE: usize = 5;
|
||||||
@@ -38,10 +39,7 @@ pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Ve
|
|||||||
.skip(TRACKS_PER_PAGE * page)
|
.skip(TRACKS_PER_PAGE * page)
|
||||||
.take(TRACKS_PER_PAGE)
|
.take(TRACKS_PER_PAGE)
|
||||||
{
|
{
|
||||||
let map = track.typemap().read().await;
|
let metadata = track.data::<Metadata>();
|
||||||
let metadata = map
|
|
||||||
.get::<MetadataMap>()
|
|
||||||
.expect("Could not get metadata map");
|
|
||||||
message.push_str(
|
message.push_str(
|
||||||
format!(
|
format!(
|
||||||
"* [{}]({})",
|
"* [{}]({})",
|
||||||
@@ -76,31 +74,34 @@ pub(crate) fn build_action_row(page: usize, n_pages: usize) -> Vec<Component> {
|
|||||||
custom_id: Some(format!("page:{}", page as i32 - 1)),
|
custom_id: Some(format!("page:{}", page as i32 - 1)),
|
||||||
style: ButtonStyle::Primary,
|
style: ButtonStyle::Primary,
|
||||||
label: Some("Previous page".to_string()),
|
label: Some("Previous page".to_string()),
|
||||||
emoji: Some(ReactionType::Unicode {
|
emoji: Some(EmojiReactionType::Unicode {
|
||||||
name: "⬅️".to_string(),
|
name: "⬅️".to_string(),
|
||||||
}),
|
}),
|
||||||
url: None,
|
url: None,
|
||||||
disabled: page == 0,
|
disabled: page == 0,
|
||||||
|
sku_id: None,
|
||||||
}),
|
}),
|
||||||
Component::Button(Button {
|
Component::Button(Button {
|
||||||
custom_id: Some(format!("page:{}", page)),
|
custom_id: Some(format!("page:{}", page)),
|
||||||
style: ButtonStyle::Primary,
|
style: ButtonStyle::Primary,
|
||||||
label: Some("Refresh".to_string()),
|
label: Some("Refresh".to_string()),
|
||||||
emoji: Some(ReactionType::Unicode {
|
emoji: Some(EmojiReactionType::Unicode {
|
||||||
name: "🔄".to_string(),
|
name: "🔄".to_string(),
|
||||||
}),
|
}),
|
||||||
url: None,
|
url: None,
|
||||||
disabled: false,
|
disabled: false,
|
||||||
|
sku_id: None,
|
||||||
}),
|
}),
|
||||||
Component::Button(Button {
|
Component::Button(Button {
|
||||||
custom_id: Some(format!("page:{}", page + 1)),
|
custom_id: Some(format!("page:{}", page + 1)),
|
||||||
style: ButtonStyle::Primary,
|
style: ButtonStyle::Primary,
|
||||||
label: Some("Next page".to_string()),
|
label: Some("Next page".to_string()),
|
||||||
emoji: Some(ReactionType::Unicode {
|
emoji: Some(EmojiReactionType::Unicode {
|
||||||
name: "➡️".to_string(),
|
name: "➡️".to_string(),
|
||||||
}),
|
}),
|
||||||
url: None,
|
url: None,
|
||||||
disabled: page >= n_pages - 1,
|
disabled: page >= n_pages - 1,
|
||||||
|
sku_id: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
})]
|
})]
|
||||||
@@ -153,8 +154,8 @@ pub(crate) async fn queue(
|
|||||||
.http
|
.http
|
||||||
.interaction(interaction.application_id)
|
.interaction(interaction.application_id)
|
||||||
.update_response(&interaction.token)
|
.update_response(&interaction.token)
|
||||||
.embeds(Some(&embeds))?
|
.embeds(Some(&embeds))
|
||||||
.components(Some(&action_row))?
|
.components(Some(&action_row))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ use twilight_model::gateway::payload::incoming::InteractionCreate;
|
|||||||
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
|
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
|
||||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
pub(crate) struct Handler {
|
pub(crate) struct Handler {
|
||||||
state: State,
|
state: State,
|
||||||
}
|
}
|
||||||
|
|||||||
98
src/main.rs
98
src/main.rs
@@ -12,18 +12,12 @@ mod utils;
|
|||||||
|
|
||||||
use crate::commands::get_chat_commands;
|
use crate::commands::get_chat_commands;
|
||||||
use dotenv::dotenv;
|
use dotenv::dotenv;
|
||||||
use futures::StreamExt;
|
|
||||||
use signal::signal_handler;
|
|
||||||
use songbird::{shards::TwilightMap, Songbird};
|
use songbird::{shards::TwilightMap, Songbird};
|
||||||
use state::StateRef;
|
use state::StateRef;
|
||||||
use std::{env, error::Error, str::FromStr, sync::Arc, time::Duration};
|
use std::{env, error::Error, str::FromStr, sync::Arc, time::Duration};
|
||||||
use tokio::select;
|
|
||||||
use tracing::{debug, info};
|
use tracing::{debug, info};
|
||||||
use twilight_cache_inmemory::InMemoryCache;
|
use twilight_cache_inmemory::InMemoryCache;
|
||||||
use twilight_gateway::{
|
use twilight_gateway::{Event, EventTypeFlags, Intents, Shard, StreamExt as _};
|
||||||
stream::{self, ShardEventStream},
|
|
||||||
Intents, Shard,
|
|
||||||
};
|
|
||||||
use twilight_http::Client as HttpClient;
|
use twilight_http::Client as HttpClient;
|
||||||
use twilight_model::id::Id;
|
use twilight_model::id::Id;
|
||||||
use twilight_standby::Standby;
|
use twilight_standby::Standby;
|
||||||
@@ -38,7 +32,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|||||||
|
|
||||||
info!("Starting up...");
|
info!("Starting up...");
|
||||||
|
|
||||||
let (mut shards, state) = {
|
let (shards, state) = {
|
||||||
let db = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
|
let db = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
|
||||||
let options = SqliteConnectOptions::from_str(&db)
|
let options = SqliteConnectOptions::from_str(&db)
|
||||||
.expect("could not create options")
|
.expect("could not create options")
|
||||||
@@ -71,7 +65,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|||||||
| Intents::MESSAGE_CONTENT;
|
| Intents::MESSAGE_CONTENT;
|
||||||
let config = twilight_gateway::Config::new(token.clone(), intents);
|
let config = twilight_gateway::Config::new(token.clone(), intents);
|
||||||
let shards: Vec<Shard> =
|
let shards: Vec<Shard> =
|
||||||
stream::create_recommended(&http, config, |_, builder| builder.build())
|
twilight_gateway::create_recommended(&http, config, |_, builder| builder.build())
|
||||||
.await?
|
.await?
|
||||||
.collect();
|
.collect();
|
||||||
let senders = TwilightMap::new(
|
let senders = TwilightMap::new(
|
||||||
@@ -105,45 +99,55 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|||||||
info!("Ready to receive events");
|
info!("Ready to receive events");
|
||||||
|
|
||||||
let handler = Handler::new(Arc::clone(&state));
|
let handler = Handler::new(Arc::clone(&state));
|
||||||
let mut stop_rx = signal_handler();
|
// let mut stop_rx = signal_handler();
|
||||||
let mut stream = ShardEventStream::new(shards.iter_mut());
|
let mut set = tokio::task::JoinSet::new();
|
||||||
loop {
|
|
||||||
select! {
|
|
||||||
biased;
|
|
||||||
_ = stop_rx.changed() => {
|
|
||||||
for guild in state.cache.iter().guilds() {
|
|
||||||
if let Some(user) = state.cache.current_user() {
|
|
||||||
if state.cache.voice_state(user.id, guild.id()).is_some() {
|
|
||||||
debug!("Leaving guild {:?}", guild.id());
|
|
||||||
state.songbird.leave(guild.id()).await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// need to grab next event to properly leave voice channels
|
|
||||||
stream.next().await;
|
|
||||||
break;
|
|
||||||
},
|
|
||||||
next = stream.next() => {
|
|
||||||
let event = match next {
|
|
||||||
Some((_, Ok(event))) => event,
|
|
||||||
Some((_, Err(source))) => {
|
|
||||||
tracing::warn!(?source, "error receiving event");
|
|
||||||
if source.is_fatal() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
None => break,
|
|
||||||
};
|
|
||||||
debug!("Event: {:?}", &event);
|
|
||||||
|
|
||||||
state.cache.update(&event);
|
for shard in shards {
|
||||||
state.standby.process(&event);
|
set.spawn(tokio::spawn(runner(shard, handler.clone(), state.clone())));
|
||||||
state.songbird.process(&event).await;
|
|
||||||
|
|
||||||
handler.act(event).await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
set.join_next().await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn runner(mut shard: Shard, handler: Handler, state: Arc<StateRef>) {
|
||||||
|
while let Some(item) = shard.next_event(EventTypeFlags::all()).await {
|
||||||
|
let event = match item {
|
||||||
|
Ok(event) => event,
|
||||||
|
Err(source) => {
|
||||||
|
tracing::warn!(?source, "error receiving event");
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
tokio::spawn({
|
||||||
|
let state = state.clone();
|
||||||
|
let handler = handler.clone();
|
||||||
|
async move {
|
||||||
|
handle_event(event, handler, state)
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|source| {
|
||||||
|
tracing::warn!(?source, "error handling event");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_event(
|
||||||
|
event: Event,
|
||||||
|
handler: Handler,
|
||||||
|
state: Arc<StateRef>,
|
||||||
|
) -> Result<(), Box<dyn Error>> {
|
||||||
|
state.standby.process(&event);
|
||||||
|
state.songbird.process(&event).await;
|
||||||
|
debug!("Event: {:?}", &event);
|
||||||
|
|
||||||
|
state.cache.update(&event);
|
||||||
|
state.standby.process(&event);
|
||||||
|
state.songbird.process(&event).await;
|
||||||
|
|
||||||
|
handler.act(event).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use songbird::{input::YoutubeDl, typemap::TypeMapKey};
|
use songbird::input::YoutubeDl;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -6,10 +6,5 @@ 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) src: YoutubeDl<'static>,
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct MetadataMap;
|
|
||||||
impl TypeMapKey for MetadataMap {
|
|
||||||
type Value = Metadata;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
use tokio::{
|
// use tokio::{
|
||||||
select,
|
// select,
|
||||||
signal::unix::{signal, SignalKind},
|
// signal::unix::{signal, SignalKind},
|
||||||
sync::watch,
|
// sync::watch,
|
||||||
};
|
// };
|
||||||
|
|
||||||
pub(crate) fn signal_handler() -> watch::Receiver<()> {
|
// pub(crate) fn signal_handler() -> watch::Receiver<()> {
|
||||||
let (stop_tx, stop_rx) = watch::channel(());
|
// let (stop_tx, stop_rx) = watch::channel(());
|
||||||
tokio::spawn(async move {
|
// tokio::spawn(async move {
|
||||||
let mut sigterm = signal(SignalKind::terminate()).unwrap();
|
// let mut sigterm = signal(SignalKind::terminate()).unwrap();
|
||||||
let mut sigint = signal(SignalKind::interrupt()).unwrap();
|
// let mut sigint = signal(SignalKind::interrupt()).unwrap();
|
||||||
loop {
|
// loop {
|
||||||
select! {
|
// select! {
|
||||||
_ = sigterm.recv() => println!("Receive SIGTERM"),
|
// _ = sigterm.recv() => println!("Receive SIGTERM"),
|
||||||
_ = sigint.recv() => println!("Receive SIGTERM"),
|
// _ = sigint.recv() => println!("Receive SIGTERM"),
|
||||||
};
|
// };
|
||||||
stop_tx.send(()).unwrap();
|
// stop_tx.send(()).unwrap();
|
||||||
}
|
// }
|
||||||
});
|
// });
|
||||||
stop_rx
|
// stop_rx
|
||||||
}
|
// }
|
||||||
|
|||||||
Reference in New Issue
Block a user