Reformatted the dice roll buttons

This commit is contained in:
2024-12-20 15:47:49 -05:00
parent 8ac0e59b8c
commit 642e2c8d66
10 changed files with 104 additions and 74 deletions

View File

@@ -82,12 +82,10 @@ async fn oauth_callback(
// Validate the state // Validate the state
let mut oauth_states = state.oauth_states.lock().await; let mut oauth_states = state.oauth_states.lock().await;
match query.state { match query.state {
Some(oauth_state) => { Some(oauth_state) => match oauth_states.get(&oauth_state) {
match oauth_states.get(&oauth_state) { Some(_) => oauth_states.remove(&oauth_state),
Some(_) => oauth_states.remove(&oauth_state), None => return Err(StatusCode::UNAUTHORIZED.into()),
None => return Err(StatusCode::UNAUTHORIZED.into()), },
}
}
None => return Err(StatusCode::UNAUTHORIZED)?, None => return Err(StatusCode::UNAUTHORIZED)?,
}; };

View File

@@ -44,11 +44,7 @@ impl Session {
let session_id = self.session_id.clone(); let session_id = self.session_id.clone();
let session_ttl = get_session_ttl(); let session_ttl = get_session_ttl();
redis redis
.set_ex( .set_ex(session_id, serde_json::to_string(self)?, session_ttl as u64)
session_id,
serde_json::to_string(self)?,
session_ttl as u64,
)
.await?; .await?;
Ok(()) Ok(())
} }

View File

@@ -72,11 +72,9 @@ fn find_voice_channel(
.and_then(|voice_state| voice_state.channel_id) .and_then(|voice_state| voice_state.channel_id)
{ {
Some(channel) => Ok(channel), Some(channel) => Ok(channel),
None => { None => Err(SirenError::new(
Err(SirenError::new( 400,
400, "User is not in a voice channel".to_string(),
"User is not in a voice channel".to_string(), )),
))
}
} }
} }

View File

@@ -35,7 +35,7 @@ pub async fn run(ctx: &Context, command: &CommandInteraction) {
log::debug!("<{guild_id}> Paused the track"); log::debug!("<{guild_id}> Paused the track");
edit_response(&ctx, &command, "Pausing the track".to_string()).await; edit_response(&ctx, &command, "Pausing the track".to_string()).await;
} }
Err(err) => edit_response(&ctx, &command, format!("Failed to pause: {}", err)).await Err(err) => edit_response(&ctx, &command, format!("Failed to pause: {}", err)).await,
} }
} }
@@ -44,7 +44,12 @@ pub async fn pause_track(manager: &Arc<Songbird>, guild_id: &GuildId) -> SirenRe
let handler = handler_lock.lock().await; let handler = handler_lock.lock().await;
match handler.queue().current() { match handler.queue().current() {
Some(track) => track.pause()?, Some(track) => track.pause()?,
None => return Err(Error { status: 404, details: "No track is currently playing".to_string() }) None => {
return Err(Error {
status: 404,
details: "No track is currently playing".to_string(),
})
}
} }
}; };

View File

@@ -37,7 +37,7 @@ pub async fn run(ctx: &Context, command: &CommandInteraction) {
log::debug!("<{guild_id}> Resumed the track"); log::debug!("<{guild_id}> Resumed the track");
edit_response(&ctx, &command, "resuming the track".to_string()).await; edit_response(&ctx, &command, "resuming the track".to_string()).await;
} }
Err(err) => edit_response(&ctx, &command, format!("Failed to resume: {}", err)).await Err(err) => edit_response(&ctx, &command, format!("Failed to resume: {}", err)).await,
} }
} }
@@ -46,7 +46,12 @@ pub async fn resume_track(manager: &Arc<Songbird>, guild_id: &GuildId) -> SirenR
let handler = handler_lock.lock().await; let handler = handler_lock.lock().await;
match handler.queue().current() { match handler.queue().current() {
Some(track) => track.play()?, Some(track) => track.play()?,
None => return Err(Error { status: 404, details: "No track is currently playing".to_string() }) None => {
return Err(Error {
status: 404,
details: "No track is currently playing".to_string(),
})
}
} }
}; };

View File

@@ -1,2 +1,2 @@
pub mod roll;
pub mod request_roll; pub mod request_roll;
pub mod roll;

View File

@@ -1,4 +1,7 @@
use serenity::all::{ButtonStyle, CommandInteraction, CommandOptionType, Context, CreateActionRow, CreateButton, CreateCommand, CreateCommandOption, CreateMessage, Mentionable, UserId}; use serenity::all::{
ButtonStyle, CommandInteraction, CommandOptionType, Context, CreateActionRow, CreateButton,
CreateCommand, CreateCommandOption, CreateMessage, Mentionable, UserId,
};
use serenity::builder::CreateEmbed; use serenity::builder::CreateEmbed;
use crate::bot::chat::{create_message_response, edit_response}; use crate::bot::chat::{create_message_response, edit_response};
use crate::bot::commands::fun::roll::parse_dice; use crate::bot::commands::fun::roll::parse_dice;
@@ -19,39 +22,40 @@ pub async fn run(ctx: &Context, command: &CommandInteraction) {
.options .options
.iter() .iter()
.find(|opt| opt.name == "user") .find(|opt| opt.name == "user")
.and_then(|o| o.value.as_mentionable()).unwrap(); .and_then(|o| o.value.as_mentionable())
.unwrap();
let user_id = UserId::new(user.get()); let user_id = UserId::new(user.get());
create_message_response(ctx, &command, format!("Sending request to {}", user_id.mention()), true).await; create_message_response(
ctx,
&command,
format!("Sending request to {}", user_id.mention()),
true,
)
.await;
let dice_string = command let dice_string = command
.data .data
.options .options
.get(0) .get(0)
.and_then(|o| o.value.as_str()) .and_then(|o| o.value.as_str())
.map(|s| s.split_whitespace().collect::<String>()).unwrap(); .map(|s| s.split_whitespace().collect::<String>())
.unwrap();
let dice_result = parse_dice(dice_string.as_str()); let dice_result = parse_dice(dice_string.as_str());
match dice_result { match dice_result {
Ok(dice) => { Ok(dice) => {
// let roll_button = CreateButton::new(format!("request_dice_roll|{}|{}|{}|{}|{}", dice.0, dice.1, dice.2, command.user.id.get(), hidden)) let roll_button = CreateButton::new(format!(
// .label("Roll") "request_dice_roll|{}|{}|{}|{}|{}",
// .style(ButtonStyle::Primary); dice.0,
// let action_row = CreateActionRow::Buttons(vec![roll_button]); dice.1,
// dice.2,
// let embed = CreateEmbed::new() command.user.id.get(),
// .title("🎲 Dice roll request! 🎲".to_string()) hidden
// .color(0x00FF00) ))
// .description(format!("{} Requested a dice roll of {}", command.user.mention(), dice_string)); .label(format!("🎲 Roll {} 🎲", dice_string)) // The label you want on the button
// .style(ButtonStyle::Primary);
// let message = CreateMessage::new()
// .embed(embed)
// .components(vec![action_row]);
let roll_button = CreateButton::new(format!("request_dice_roll|{}|{}|{}|{}|{}", dice.0, dice.1, dice.2, command.user.id.get(), hidden))
.label(format!("🎲 Roll {} 🎲", dice_string)) // The label you want on the button
.style(ButtonStyle::Primary);
let action_row = CreateActionRow::Buttons(vec![roll_button]); let action_row = CreateActionRow::Buttons(vec![roll_button]);
@@ -74,22 +78,22 @@ pub fn register() -> CreateCommand {
CreateCommand::new("requestroll") CreateCommand::new("requestroll")
.description("Request a dice roll from a user") .description("Request a dice roll from a user")
.add_option( .add_option(
CreateCommandOption::new(CommandOptionType::String, "dice", "Dice to roll") CreateCommandOption::new(CommandOptionType::String, "dice", "Dice to roll").required(true),
.required(true),
) )
.add_option( .add_option(
CreateCommandOption::new( CreateCommandOption::new(
CommandOptionType::Mentionable, CommandOptionType::Mentionable,
"user", "user",
"User to receive the dice roll request" "User to receive the dice roll request",
) )
.required(true), .required(true),
) )
.add_option( .add_option(
CreateCommandOption::new( CreateCommandOption::new(
CommandOptionType::Boolean, CommandOptionType::Boolean,
"hidden", "hidden",
"Hide the dice roll from the user (Default: False") "Hide the dice roll from the user (Default: False",
.required(false), )
.required(false),
) )
} }

View File

@@ -62,14 +62,7 @@ pub async fn run(ctx: &Context, command: &CommandInteraction) {
) )
.await; .await;
} }
None => { None => edit_response(&ctx, &command, format!("🎲 {}\n-# {}", total, response)).await,
edit_response(
&ctx,
&command,
format!("🎲 {}\n-# {}", total, response),
)
.await
}
}; };
} }
Err(why) => { Err(why) => {
@@ -78,7 +71,13 @@ pub async fn run(ctx: &Context, command: &CommandInteraction) {
} }
} }
pub async fn send_roll_message(ctx: &Context, total: i32, user_id: UserId, roller_id: UserId, dice_string: &str) { pub async fn send_roll_message(
ctx: &Context,
total: i32,
user_id: UserId,
roller_id: UserId,
dice_string: &str,
) {
// Create the dice roll embed // Create the dice roll embed
let a = a_or_an(&number_to_words(total)); let a = a_or_an(&number_to_words(total));
let embed = CreateEmbed::new() let embed = CreateEmbed::new()
@@ -109,7 +108,8 @@ pub fn format_roll(count: u32, sides: u32, modifier: i32) -> String {
format!("-{}", modifier) format!("-{}", modifier)
} else { } else {
"".to_string() "".to_string()
}) }
)
} }
pub fn roll_dice(count: u32, sides: u32, modifier: i32) -> i32 { pub fn roll_dice(count: u32, sides: u32, modifier: i32) -> i32 {

View File

@@ -1,6 +1,9 @@
use std::env; use std::env;
use std::sync::{Arc, OnceLock}; use std::sync::{Arc, OnceLock};
use serenity::all::{CreateEmbed, CreateInteractionResponse, CreateInteractionResponseMessage, EditInteractionResponse, Interaction, ResumedEvent, UserId}; use serenity::all::{
CreateEmbed, CreateInteractionResponse, CreateInteractionResponseMessage,
EditInteractionResponse, Interaction, ResumedEvent, UserId,
};
use serenity::async_trait; use serenity::async_trait;
use serenity::model::gateway::Ready; use serenity::model::gateway::Ready;
use serenity::model::channel::Message; use serenity::model::channel::Message;
@@ -175,7 +178,10 @@ impl EventHandler for BotHandler {
let custom_id = &component.data.custom_id; let custom_id = &component.data.custom_id;
if custom_id.starts_with("request_dice_roll") { if custom_id.starts_with("request_dice_roll") {
// Acknowledge the interaction // Acknowledge the interaction
if let Err(err) = component.create_response(ctx.http.clone(), CreateInteractionResponse::Acknowledge).await { if let Err(err) = component
.create_response(ctx.http.clone(), CreateInteractionResponse::Acknowledge)
.await
{
log::error!("Could not create dice response: {}", err); log::error!("Could not create dice response: {}", err);
}; };
let parts = custom_id.split('|').collect::<Vec<&str>>(); let parts = custom_id.split('|').collect::<Vec<&str>>();
@@ -188,15 +194,36 @@ impl EventHandler for BotHandler {
let user_id = UserId::from(parts[4].parse::<u64>().unwrap()); let user_id = UserId::from(parts[4].parse::<u64>().unwrap());
let roller_id = component.user.id; let roller_id = component.user.id;
let hidden: bool = parts[5].parse().unwrap(); let hidden: bool = parts[5].parse().unwrap();
send_roll_message(&ctx, result, user_id, roller_id, &response).await;
component.delete_response(ctx.http.clone()).await.ok(); // Prepare the message based on visibility
let message; let new_message = if hidden {
if hidden { // For hidden rolls, only reveal "results sent" to the requester
message = format!("Results sent to {}", user_id.mention()); format!("🎲 Results sent to {}\n-# {}", user_id.mention(), response)
} else { } else {
message = format!("🎲 You rolled {} {}\n-# {}", a_or_an(&number_to_words(result)), result, response); // For public rolls, show the roll result
format!(
"🎲 You rolled {} {}\n-# {}",
a_or_an(&number_to_words(result)),
result,
response
)
};
// Edit the message to update the text and remove buttons
if let Err(err) = component
.edit_response(
ctx.http.clone(),
EditInteractionResponse::new()
.content(new_message)
.components(Vec::new()),
)
.await
{
log::error!("Could not update dice roll message: {}", err);
} }
user_dm(&ctx, &component.user.id, message).await;
// Send message to the requester
send_roll_message(&ctx, result, user_id, roller_id, &response).await;
} else { } else {
log::error!("Could not handle dice click: {}", custom_id); log::error!("Could not handle dice click: {}", custom_id);
} }

View File

@@ -14,10 +14,7 @@ pub struct Error {
impl Error { impl Error {
pub fn new(status: u16, details: String) -> Self { pub fn new(status: u16, details: String) -> Self {
Self { Self { status, details }
status,
details,
}
} }
pub fn not_found(details: String) -> Self { pub fn not_found(details: String) -> Self {