Fixed /join when switching channels, minor compatibility improvements

main
DaXcess 2022-11-05 18:15:23 +01:00
parent 2e6dde133b
commit 9798a178d7
3 changed files with 56 additions and 15 deletions

View File

@ -1,3 +1,4 @@
use log::trace;
use serenity::{ use serenity::{
builder::CreateApplicationCommand, builder::CreateApplicationCommand,
model::prelude::interaction::application_command::ApplicationCommandInteraction, model::prelude::interaction::application_command::ApplicationCommandInteraction,
@ -45,7 +46,7 @@ pub fn run(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutpu
let mut session_manager = data.get::<SessionManager>().unwrap().clone(); let mut session_manager = data.get::<SessionManager>().unwrap().clone();
// Check if another session is already active in this server // Check if another session is already active in this server
let session_opt = session_manager.get_session(guild.id).await; let mut session_opt = session_manager.get_session(guild.id).await;
if let Some(session) = &session_opt { if let Some(session) = &session_opt {
if let Some(owner) = session.get_owner().await { if let Some(owner) = session.get_owner().await {
@ -94,6 +95,17 @@ pub fn run(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutpu
defer_message(&ctx, &command, false).await; defer_message(&ctx, &command, false).await;
if let Some(session) = &session_opt {
trace!("{} != {}", session.get_channel_id(), channel_id);
if session.get_channel_id() != channel_id {
session.disconnect().await;
session_opt = None;
// Give serenity/songbird some time to register the disconnect
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
}
if let Some(session) = &session_opt { if let Some(session) = &session_opt {
if let Err(why) = session.update_owner(&ctx, command.user.id).await { if let Err(why) = session.update_owner(&ctx, command.user.id).await {
// Need to link first // Need to link first

View File

@ -11,7 +11,10 @@ use serenity::{
use crate::{ use crate::{
bot::commands::{respond_message, CommandOutput}, bot::commands::{respond_message, CommandOutput},
session::manager::SessionManager, session::manager::SessionManager,
utils::{embed::{EmbedBuilder, Status}, self}, utils::{
self,
embed::{EmbedBuilder, Status},
},
}; };
pub const NAME: &str = "playing"; pub const NAME: &str = "playing";
@ -81,7 +84,11 @@ pub fn run(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutpu
}; };
// Create title // Create title
let title = format!("{} - {}", pbi.get_artists().unwrap(), pbi.get_name().unwrap()); let title = format!(
"{} - {}",
pbi.get_artists().unwrap(),
pbi.get_name().unwrap()
);
// Create description // Create description
let mut description = String::new(); let mut description = String::new();
@ -100,7 +107,11 @@ pub fn run(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutpu
} }
description.push_str("\n:alarm_clock: "); description.push_str("\n:alarm_clock: ");
description.push_str(&format!("{} / {}", utils::time_to_str(position / 1000), utils::time_to_str(pbi.duration_ms / 1000))); description.push_str(&format!(
"{} / {}",
utils::time_to_str(position / 1000),
utils::time_to_str(pbi.duration_ms / 1000)
));
// Get owner of session // Get owner of session
let owner = match utils::discord::get_user(&ctx, owner).await { let owner = match utils::discord::get_user(&ctx, owner).await {
@ -116,7 +127,10 @@ pub fn run(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutpu
&command, &command,
EmbedBuilder::new() EmbedBuilder::new()
.title("[INTERNAL ERROR] Cannot get track info") .title("[INTERNAL ERROR] Cannot get track info")
.description(format!("Could not find user with id {}\nThis is an issue with the bot!", owner)) .description(format!(
"Could not find user with id {}\nThis is an issue with the bot!",
owner
))
.status(Status::Error) .status(Status::Error)
.build(), .build(),
true, true,
@ -136,18 +150,15 @@ pub fn run(ctx: Context, command: ApplicationCommandInteraction) -> CommandOutpu
.kind(InteractionResponseType::ChannelMessageWithSource) .kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|message| { .interaction_response_data(|message| {
message message
.embed(|embed| .embed(|embed| embed
embed .author(|author| author
.author(|author|
author
.name("Currently Playing") .name("Currently Playing")
.icon_url("https://www.freepnglogos.com/uploads/spotify-logo-png/file-spotify-logo-png-4.png") .icon_url("https://www.freepnglogos.com/uploads/spotify-logo-png/file-spotify-logo-png-4.png")
) )
.title(title) .title(title)
.url(format!("https://open.spotify.com/{}/{}", audio_type, spotify_id.to_base62().unwrap())) .url(format!("https://open.spotify.com/{}/{}", audio_type, spotify_id.to_base62().unwrap()))
.description(description) .description(description)
.footer(|footer| .footer(|footer| footer
footer
.text(&owner.name) .text(&owner.name)
.icon_url(owner.face()) .icon_url(owner.face())
) )

View File

@ -4,14 +4,16 @@ use dotenv::dotenv;
use log::*; use log::*;
use serenity::{framework::StandardFramework, prelude::GatewayIntents, Client}; use serenity::{framework::StandardFramework, prelude::GatewayIntents, Client};
use songbird::SerenityInit; use songbird::SerenityInit;
use std::{env, process::exit}; use std::{any::Any, env, process::exit};
use tokio::signal::unix::SignalKind;
use crate::{ use crate::{
bot::commands::CommandManager, database::Database, session::manager::SessionManager, bot::commands::CommandManager, database::Database, session::manager::SessionManager,
stats::StatsManager, stats::StatsManager,
}; };
#[cfg(unix)]
use tokio::signal::unix::SignalKind;
mod audio; mod audio;
mod bot; mod bot;
mod consts; mod consts;
@ -103,8 +105,14 @@ async fn main() {
let shard_manager = client.shard_manager.clone(); let shard_manager = client.shard_manager.clone();
let cache = client.cache_and_http.cache.clone(); let cache = client.cache_and_http.cache.clone();
let mut term: Option<Box<dyn Any + Send>>;
#[cfg(unix)] #[cfg(unix)]
let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate()).unwrap(); {
term = Some(Box::new(
tokio::signal::unix::signal(SignalKind::terminate()).unwrap(),
));
}
// Background tasks // Background tasks
tokio::spawn(async move { tokio::spawn(async move {
@ -134,7 +142,17 @@ async fn main() {
break; break;
} }
_ = sigterm.recv() => { _ = async {
match term {
Some(ref mut term) => {
let term = term.downcast_mut::<tokio::signal::unix::Signal>().unwrap();
term.recv().await
}
_ => None
}
}, if term.is_some() => {
info!("Received terminate signal, shutting down..."); info!("Received terminate signal, shutting down...");
shard_manager.lock().await.shutdown_all().await; shard_manager.lock().await.shutdown_all().await;