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
let mut oauth_states = state.oauth_states.lock().await;
match query.state {
Some(oauth_state) => {
match oauth_states.get(&oauth_state) {
Some(_) => oauth_states.remove(&oauth_state),
None => return Err(StatusCode::UNAUTHORIZED.into()),
}
}
Some(oauth_state) => match oauth_states.get(&oauth_state) {
Some(_) => oauth_states.remove(&oauth_state),
None => return Err(StatusCode::UNAUTHORIZED.into()),
},
None => return Err(StatusCode::UNAUTHORIZED)?,
};

View File

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

View File

@@ -72,11 +72,9 @@ fn find_voice_channel(
.and_then(|voice_state| voice_state.channel_id)
{
Some(channel) => Ok(channel),
None => {
Err(SirenError::new(
400,
"User is not in a voice channel".to_string(),
))
}
None => Err(SirenError::new(
400,
"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");
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;
match handler.queue().current() {
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");
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;
match handler.queue().current() {
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 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 crate::bot::chat::{create_message_response, edit_response};
use crate::bot::commands::fun::roll::parse_dice;
@@ -19,39 +22,40 @@ pub async fn run(ctx: &Context, command: &CommandInteraction) {
.options
.iter()
.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());
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
.data
.options
.get(0)
.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());
match dice_result {
Ok(dice) => {
// let roll_button = CreateButton::new(format!("request_dice_roll|{}|{}|{}|{}|{}", dice.0, dice.1, dice.2, command.user.id.get(), hidden))
// .label("Roll")
// .style(ButtonStyle::Primary);
// let action_row = CreateActionRow::Buttons(vec![roll_button]);
//
// let embed = CreateEmbed::new()
// .title("🎲 Dice roll request! 🎲".to_string())
// .color(0x00FF00)
// .description(format!("{} Requested a dice roll of {}", command.user.mention(), dice_string));
//
// 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 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]);
@@ -74,22 +78,22 @@ pub fn register() -> CreateCommand {
CreateCommand::new("requestroll")
.description("Request a dice roll from a user")
.add_option(
CreateCommandOption::new(CommandOptionType::String, "dice", "Dice to roll")
.required(true),
CreateCommandOption::new(CommandOptionType::String, "dice", "Dice to roll").required(true),
)
.add_option(
CreateCommandOption::new(
CommandOptionType::Mentionable,
"user",
"User to receive the dice roll request"
"User to receive the dice roll request",
)
.required(true),
.required(true),
)
.add_option(
CreateCommandOption::new(
CommandOptionType::Boolean,
"hidden",
"Hide the dice roll from the user (Default: False")
.required(false),
"hidden",
"Hide the dice roll from the user (Default: False",
)
.required(false),
)
}

View File

@@ -62,14 +62,7 @@ pub async fn run(ctx: &Context, command: &CommandInteraction) {
)
.await;
}
None => {
edit_response(
&ctx,
&command,
format!("🎲 {}\n-# {}", total, response),
)
.await
}
None => edit_response(&ctx, &command, format!("🎲 {}\n-# {}", total, response)).await,
};
}
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
let a = a_or_an(&number_to_words(total));
let embed = CreateEmbed::new()
@@ -109,7 +108,8 @@ pub fn format_roll(count: u32, sides: u32, modifier: i32) -> String {
format!("-{}", modifier)
} else {
"".to_string()
})
}
)
}
pub fn roll_dice(count: u32, sides: u32, modifier: i32) -> i32 {

View File

@@ -1,6 +1,9 @@
use std::env;
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::model::gateway::Ready;
use serenity::model::channel::Message;
@@ -175,7 +178,10 @@ impl EventHandler for BotHandler {
let custom_id = &component.data.custom_id;
if custom_id.starts_with("request_dice_roll") {
// 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);
};
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 roller_id = component.user.id;
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();
let message;
if hidden {
message = format!("Results sent to {}", user_id.mention());
// Prepare the message based on visibility
let new_message = if hidden {
// For hidden rolls, only reveal "results sent" to the requester
format!("🎲 Results sent to {}\n-# {}", user_id.mention(), response)
} 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 {
log::error!("Could not handle dice click: {}", custom_id);
}

View File

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