songbird music support init

This commit is contained in:
2024-01-30 15:17:36 +01:00
parent edcf79cf8c
commit a5a9779cb9
9 changed files with 3226 additions and 4 deletions

2992
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,13 @@ name = "lyra"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
dotenv = "0.15.0"
reqwest = "0.11.23"
serenity = "0.12.0"
songbird = { version = "0.4.0", features = ["builtin-queue", "serenity"] }
symphonia = "0.5.3"
tokio = { version = "1.35.1", features = ["macros", "rt-multi-thread", "signal"] }
tracing = "0.1.40"
tracing-futures = "0.2.5"
tracing-subscriber = "0.3.18"

8
src/commands/misc.rs Normal file
View File

@@ -0,0 +1,8 @@
use serenity::model::channel::Message;
use serenity::Result as SerenityResult;
pub fn check_msg(result: SerenityResult<Message>) {
if let Err(why) = result {
println!("Error sending message: {:?}", why);
}
}

2
src/commands/mod.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod music;
pub mod misc;

View File

@@ -0,0 +1,41 @@
use serenity::model::prelude::*;
use serenity::prelude::*;
use serenity::framework::standard::macros::command;
use serenity::framework::standard::CommandResult;
use crate::commands::misc::check_msg;
#[command]
#[only_in(guilds)]
async fn deafen(ctx: &Context, msg: &Message) -> CommandResult {
let guild_id = msg.guild_id.unwrap();
let manager = songbird::get(ctx)
.await
.expect("Client placed at init")
.clone();
let handler_lock = match manager.get(guild_id) {
Some(handler) => handler,
None => {
check_msg(msg.reply(ctx, "Not in a voice channel").await);
return Ok(())
}
};
let mut handler = handler_lock.lock().await;
if handler.is_deaf() {
check_msg(msg.channel_id.say(&ctx.http, "Already deafened").await);
}
else {
if let Err(err) = handler.deafen(true).await {
check_msg(msg.channel_id.say(&ctx.http, format!("Failed: {:?}", err)).await);
}
check_msg(msg.channel_id.say(&ctx.http, "Deafened").await);
}
Ok(())
}

View File

@@ -0,0 +1,61 @@
use serenity::async_trait;
use serenity::model::prelude::*;
use serenity::prelude::*;
use serenity::framework::standard::macros::command;
use serenity::framework::standard::CommandResult;
use songbird::events::{Event, EventContext, EventHandler as VoiceEventHandler, TrackEvent};
use crate::commands::misc::check_msg;
#[command]
#[only_in(guilds)]
async fn join(ctx: &Context, msg: &Message) -> CommandResult {
let (guild_id, channel_id) = {
let guild = msg.guild(&ctx.cache).unwrap();
let channel_id = guild
.voice_states
.get(&msg.author.id)
.and_then(|voice_state| voice_state.channel_id);
(guild.id, channel_id)
};
let connect_to = match channel_id {
Some(channel) => channel,
None => {
check_msg(msg.reply(ctx, "Not in a voice channel").await);
return Ok(());
}
};
let manager = songbird::get(ctx)
.await
.expect("Songbird Voice placed at init")
.clone();
if let Ok(handler_lock) = manager.join(guild_id, connect_to).await {
let mut handler = handler_lock.lock().await;
handler.add_global_event(TrackEvent::Error.into(), TrackErrorNotifier);
}
Ok(())
}
struct TrackErrorNotifier;
#[async_trait]
impl VoiceEventHandler for TrackErrorNotifier {
async fn act(&self, ctx: &EventContext<'_>) -> Option<Event> {
if let EventContext::Track(track_list) = ctx {
for (state, handle) in *track_list {
println!(
"Track {:?} had an error: {:?}",
handle.uuid(),
state.playing
);
}
}
None
}
}

View File

@@ -0,0 +1,32 @@
use serenity::framework::standard::macros::command;
use serenity::framework::standard::CommandResult;
use serenity::model::prelude::*;
use serenity::prelude::*;
use crate::commands::misc::check_msg;
#[command]
#[only_in(guilds)]
async fn leave(ctx: &Context, msg: &Message) -> CommandResult {
let guild_id = msg.guild_id.unwrap();
let manager = songbird::get(ctx)
.await
.expect("Client placed in at init.")
.clone();
let has_handler = manager.get(guild_id).is_some();
if has_handler {
if let Err(err) = manager.remove(guild_id).await {
check_msg(msg.channel_id.say(&ctx.http, format!("Failed: {:?}", err)).await);
}
check_msg(msg.channel_id.say(&ctx.http, "Left voice channel").await);
}
else {
check_msg(msg.reply(ctx, "Not in a voice channel").await);
}
Ok(())
}

View File

@@ -0,0 +1,3 @@
pub mod join;
pub mod deafen;
pub mod leave;

View File

@@ -1,3 +1,79 @@
fn main() { use songbird::SerenityInit;
println!("Hello, world!");
use reqwest::Client as HttpClient;
use serenity::client::Context;
use serenity::{
async_trait,
client::{Client, EventHandler},
framework::{
standard::{
macros::group,
Configuration,
},
StandardFramework,
},
model::gateway::Ready,
prelude::{GatewayIntents, TypeMapKey},
};
mod commands;
use crate::commands::music::join::*;
use crate::commands::music::deafen::*;
use crate::commands::music::leave::*;
struct HttpKey;
impl TypeMapKey for HttpKey {
type Value = HttpClient;
}
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, _: Context, ready: Ready) {
println!("{} is connected!", ready.user.name);
}
}
#[group]
#[commands(
join, deafen, leave
)]
struct General;
#[tokio::main]
async fn main() {
dotenv::dotenv().expect("Failed to load .env file.");
tracing_subscriber::fmt::init();
let token =
std::env::var("DISCORD_TOKEN").expect("Environment variable `DISCORD_TOKEN` not found!");
let prefix = std::env::var("PREFIX").expect("Environment variable `PREFIX` not found!");
let framework = StandardFramework::new().group(&GENERAL_GROUP);
framework.configure(Configuration::new().prefix(prefix));
let intents = GatewayIntents::non_privileged() | GatewayIntents::MESSAGE_CONTENT;
let mut client = Client::builder(&token, intents)
.event_handler(Handler)
.framework(framework)
.register_songbird()
.type_map_insert::<HttpKey>(HttpClient::new())
.await
.expect("Error creating client");
tokio::spawn(async move {
let _ = client
.start()
.await
.map_err(|why| println!("Client ended: {:?}", why));
});
let _signal_err = tokio::signal::ctrl_c().await;
println!("Recieved Ctrl-C, shutting down.");
} }