Formatting code

This commit is contained in:
Benjamin Sherriff
2024-05-12 09:05:59 -04:00
parent c971c55aa3
commit 1de68f86ae
46 changed files with 1109 additions and 609 deletions

View File

@@ -4,7 +4,9 @@ use log::{debug, warn};
use reqwest::Url;
use serenity::client::Cache;
use serenity::model::application::interaction::{InteractionResponseType, application_command::ApplicationCommandInteraction};
use serenity::model::application::interaction::{
InteractionResponseType, application_command::ApplicationCommandInteraction,
};
use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User;
use serenity::prelude::*;
@@ -21,33 +23,60 @@ pub mod skip;
pub mod stop;
pub mod volume;
pub async fn join_by_user(cache: &Arc<Cache>, manager: Arc<Songbird>, guild_id_option: &Option<GuildId>, user: &User) -> Result<(), ServiceError> {
pub async fn join_by_user(
cache: &Arc<Cache>,
manager: Arc<Songbird>,
guild_id_option: &Option<GuildId>,
user: &User,
) -> Result<(), ServiceError> {
let guild_id = match guild_id_option {
Some(g) => g,
None => return Err(ServiceError { status: 422, message: format!("{}", "No guild ID set") })
None => {
return Err(ServiceError {
status: 422,
message: format!("{}", "No guild ID set"),
})
}
};
let channel_id = match find_voice_channel(cache, &guild_id, &user) {
Ok(channel) => channel,
Err(err) => return Err(ServiceError { status: 500, message: err.to_string() })
Err(err) => {
return Err(ServiceError {
status: 500,
message: err.to_string(),
})
}
};
join(manager, guild_id, &channel_id).await
}
pub async fn join(manager: Arc<Songbird>, guild_id: &GuildId, channel_id: &ChannelId) -> Result<(), ServiceError> {
pub async fn join(
manager: Arc<Songbird>,
guild_id: &GuildId,
channel_id: &ChannelId,
) -> Result<(), ServiceError> {
debug!("<{}> Joining channel {}", guild_id.0, channel_id.0);
let (_handle_lock, success) = manager.join(guild_id.to_owned(), channel_id.to_owned()).await;
let (_handle_lock, success) = manager
.join(guild_id.to_owned(), channel_id.to_owned())
.await;
match success {
Ok(s) => Ok(s),
Err(err) => {
warn!("Failed to join channel: {:?}", err);
Err(ServiceError { status: 500, message: err.to_string() })
Err(ServiceError {
status: 500,
message: err.to_string(),
})
}
}
}
pub async fn leave(manager: Arc<Songbird>, guild_id_option: &Option<GuildId>) -> Result<(), String> {
pub async fn leave(
manager: Arc<Songbird>,
guild_id_option: &Option<GuildId>,
) -> Result<(), String> {
let guild_id = match guild_id_option {
Some(g) => g,
None => {
@@ -58,39 +87,72 @@ pub async fn leave(manager: Arc<Songbird>, guild_id_option: &Option<GuildId>) ->
if manager.get(*guild_id).is_some() {
debug!("<{}> Disconnecting from channel", guild_id.0);
if let Err(e) = manager.remove(*guild_id).await {
return Err(format!("{}", e))
return Err(format!("{}", e));
}
}
Ok(())
}
fn find_voice_channel(cache: &Arc<Cache>, guild_id: &GuildId, user: &User) -> Result<ChannelId, String> {
fn find_voice_channel(
cache: &Arc<Cache>,
guild_id: &GuildId,
user: &User,
) -> Result<ChannelId, String> {
let guild = match guild_id.to_guild_cached(cache.to_owned()) {
Some(g) => g,
None => return Err(format!("Guild not found"))
None => return Err(format!("Guild not found")),
};
match guild.voice_states.get(&user.id).and_then(|voice_state| voice_state.channel_id) {
match guild
.voice_states
.get(&user.id)
.and_then(|voice_state| voice_state.channel_id)
{
Some(channel) => Ok(channel),
None => return Err(format!("User is not in a voice channel"))
None => return Err(format!("User is not in a voice channel")),
}
}
pub async fn create_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<(), SerenityError> {
command.create_interaction_response(&ctx.http, |response: &mut serenity::builder::CreateInteractionResponse<'_>| {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|message: &mut serenity::builder::CreateInteractionResponseData<'_>| message.content(content))
}).await
pub async fn create_response(
ctx: &Context,
command: &ApplicationCommandInteraction,
content: String,
) -> Result<(), SerenityError> {
command
.create_interaction_response(
&ctx.http,
|response: &mut serenity::builder::CreateInteractionResponse<'_>| {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(
|message: &mut serenity::builder::CreateInteractionResponseData<'_>| {
message.content(content)
},
)
},
)
.await
}
pub async fn edit_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<serenity::model::channel::Message, SerenityError> {
command.edit_original_interaction_response(&ctx.http, |response: &mut serenity::builder::EditInteractionResponse| {
response.content(content)
}).await
pub async fn edit_response(
ctx: &Context,
command: &ApplicationCommandInteraction,
content: String,
) -> Result<serenity::model::channel::Message, SerenityError> {
command
.edit_original_interaction_response(
&ctx.http,
|response: &mut serenity::builder::EditInteractionResponse| response.content(content),
)
.await
}
pub async fn add_song(call: Arc<Mutex<Call>>, url: &str, lazy: bool, volume: Option<f32>) -> Result<Metadata, SongbirdError> {
pub async fn add_song(
call: Arc<Mutex<Call>>,
url: &str,
lazy: bool,
volume: Option<f32>,
) -> Result<Metadata, SongbirdError> {
let source = Restartable::ytdl(url.to_owned(), lazy).await?;
let mut handler = call.lock().await;
let track: Input = source.into();
@@ -115,9 +177,10 @@ pub fn get_playlist_urls(url: &str) -> Result<Vec<PlaylistItem>, ServiceError> {
None
} else {
Some(
serde_json::from_slice::<PlaylistItem>(line.as_bytes()).map_err(
|err| ServiceError { status: 500, message: err.to_string() }
)
serde_json::from_slice::<PlaylistItem>(line.as_bytes()).map_err(|err| ServiceError {
status: 500,
message: err.to_string(),
}),
)
}
})
@@ -134,11 +197,16 @@ pub fn get_playlist_urls(url: &str) -> Result<Vec<PlaylistItem>, ServiceError> {
fn is_valid_url(url: &str) -> (bool, bool) {
Url::parse(url).ok().map_or((false, false), |valid_url| {
let is_playlist: bool = valid_url.query_pairs().find(|(key, _)| key == "list").map_or(false, |_| true);
let is_playlist: bool = valid_url
.query_pairs()
.find(|(key, _)| key == "list")
.map_or(false, |_| true);
(true, is_playlist)
})
}
pub async fn get_songbird(ctx: &Context) -> Arc<Songbird> {
songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization")
songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialization")
}

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -40,4 +42,4 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("pause").description("Pause the current track")
}
}

View File

@@ -10,7 +10,10 @@ use siren::ServiceError;
use songbird::{EventHandler, Songbird};
use crate::bot::ytdlp::PlaylistItem;
use crate::bot::{guilds::QueryGuild, commands::audio::{leave, get_playlist_urls, add_song, get_songbird}};
use crate::bot::{
guilds::QueryGuild,
commands::audio::{leave, get_playlist_urls, add_song, get_songbird},
};
use super::{create_response, edit_response, is_valid_url, join_by_user};
@@ -22,20 +25,23 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
Some(s) => s.to_owned(),
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
if let Err(why) =
create_response(&ctx, &command, format!("Track option is missing")).await
{
error!("Failed to create response message: {}", why);
}
return;
}
}
},
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await
{
error!("Failed to create response message: {}", why);
}
return;
}
}
},
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
@@ -52,12 +58,14 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
let manager = get_songbird(ctx).await;
match join_by_user(&ctx.cache, manager,&command.guild_id, &command.user).await {
match join_by_user(&ctx.cache, manager, &command.guild_id, &command.user).await {
Ok(_) => {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -76,15 +84,17 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
if let Err(why) = edit_response(&ctx, &command, message).await {
error!("Failed to edit response message: {}", why);
}
},
}
Err(err) => {
warn!("Failed to play track: {}", err);
if let Err(why) = edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await {
if let Err(why) =
edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await
{
error!("Failed to edit response message: {}", why);
}
}
};
},
}
Err(err) => {
warn!("{}", err);
if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await {
@@ -94,7 +104,11 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
}
pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: String) -> Result<i32, ServiceError> {
pub async fn play_track(
manager: Arc<Songbird>,
guild_id: GuildId,
track_url: String,
) -> Result<i32, ServiceError> {
let mut track_count = 0;
if let Some(handler_lock) = manager.get(guild_id) {
let is_queue_empty = {
@@ -105,7 +119,10 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
let valid = is_valid_url(&track_url);
if !valid.0 {
warn!("Invalid track url: {}", track_url);
return Err(ServiceError { status: 422, message: format!("Invalid track url: {}", track_url) })
return Err(ServiceError {
status: 422,
message: format!("Invalid track url: {}", track_url),
});
}
let mut playlist_items: Vec<PlaylistItem> = Vec::new();
if valid.1 {
@@ -113,7 +130,10 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
Ok(items) => items,
Err(err) => {
warn!("Failed to get playlist urls: {}", err);
return Err(ServiceError { status: 422, message: err.to_string() })
return Err(ServiceError {
status: 422,
message: err.to_string(),
});
}
};
} else {
@@ -122,26 +142,42 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
url: track_url,
title: "".to_string(),
duration: 0,
playlist_index: 0
playlist_index: 0,
};
playlist_items.push(playlist_item);
}
for item in playlist_items {
match add_song(handler_lock.clone(), &item.url, is_queue_empty, Some(guild.volume as f32 / 100.0)).await {
match add_song(
handler_lock.clone(),
&item.url,
is_queue_empty,
Some(guild.volume as f32 / 100.0),
)
.await
{
Ok(added_song) => {
let track_title = added_song.title.unwrap();
debug!("Added track: {}", track_title);
let mut handler = handler_lock.lock().await;
handler.remove_all_global_events();
handler.add_global_event(songbird::Event::Track(songbird::TrackEvent::End), TrackEndNotifier { guild_id, call: manager.clone() });
handler.add_global_event(
songbird::Event::Track(songbird::TrackEvent::End),
TrackEndNotifier {
guild_id,
call: manager.clone(),
},
);
track_count += 1;
},
}
Err(err) => {
warn!("Failed to add song: {}", err);
if let Err(why) = leave(manager, &Some(guild_id)).await {
error!("Failed to leave voice channel: {}", why);
}
return Err(ServiceError { status: 422, message: err.to_string() })
return Err(ServiceError {
status: 422,
message: err.to_string(),
});
}
}
}
@@ -150,17 +186,21 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("play").description("Plays the given track").create_option(|option| { option
.name("track")
.description("The track to be played")
.kind(serenity::model::prelude::command::CommandOptionType::String)
.required(true)
})
command
.name("play")
.description("Plays the given track")
.create_option(|option| {
option
.name("track")
.description("The track to be played")
.kind(serenity::model::prelude::command::CommandOptionType::String)
.required(true)
})
}
struct TrackEndNotifier {
pub call: std::sync::Arc<songbird::Songbird>,
pub guild_id: serenity::model::id::GuildId
pub guild_id: serenity::model::id::GuildId,
}
#[async_trait]

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -39,5 +41,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("resume").description("Resume the current track")
}
command
.name("resume")
.description("Resume the current track")
}

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -40,4 +42,4 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("skip").description("Skip the current track")
}
}

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -34,5 +36,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("stop").description("Stop the current track and clear the queue")
}
command
.name("stop")
.description("Stop the current track and clear the queue")
}

View File

@@ -19,20 +19,23 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
Some(p) => p as i32,
None => {
warn!("Unable to get volume option as a string");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
if let Err(why) =
create_response(&ctx, &command, format!("Volume option is missing")).await
{
error!("Failed to create response message: {}", why);
}
return;
}
}
},
None => {
warn!("Missing volume option value");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await
{
error!("Failed to create response message: {}", why);
}
return;
}
}
},
None => {
warn!("Missing volume option");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
@@ -51,7 +54,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -59,7 +64,8 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
};
let manager = get_songbird(ctx).await;
set_volume(manager, guild_id, volume).await;
if let Err(why) = edit_response(&ctx, &command, format!("Setting the volume to {}", volume)).await {
if let Err(why) = edit_response(&ctx, &command, format!("Setting the volume to {}", volume)).await
{
error!("Failed to set the volume: {}", why);
}
}
@@ -79,10 +85,14 @@ pub async fn set_volume(manager: Arc<Songbird>, guild_id: GuildId, volume: i32)
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("volume").description("Set the audio player volume").create_option(|option| { option
command
.name("volume")
.description("Volume between 0 and 100")
.kind(serenity::model::prelude::command::CommandOptionType::Integer)
.required(true)
})
}
.description("Set the audio player volume")
.create_option(|option| {
option
.name("volume")
.description("Volume between 0 and 100")
.kind(serenity::model::prelude::command::CommandOptionType::Integer)
.required(true)
})
}

View File

@@ -26,31 +26,34 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
},
];
match QueryMessage::get_all(&QueryFilters {
by_guild_id: Some(guild_id.0 as i64),
by_channel_id: Some(channel_id.0 as i64),
by_user_id: Some(author_id.0 as i64),
..Default::default()
}, 100, 1) {
match QueryMessage::get_all(
&QueryFilters {
by_guild_id: Some(guild_id.0 as i64),
by_channel_id: Some(channel_id.0 as i64),
by_user_id: Some(author_id.0 as i64),
..Default::default()
},
100,
1,
) {
Ok(m) => {
for message in m {
messages.push(
ChatCompletionMessage {
role: GPTRole::User,
content: format!("{}", message.request)
}
);
messages.push(
ChatCompletionMessage {
role: GPTRole::Assistant,
content: format!("{}", message.response)
}
);
messages.push(ChatCompletionMessage {
role: GPTRole::User,
content: format!("{}", message.request),
});
messages.push(ChatCompletionMessage {
role: GPTRole::Assistant,
content: format!("{}", message.response),
});
}
},
Err(err) => warn!("Could not load previous messages: {}", err)
}
Err(err) => warn!("Could not load previous messages: {}", err),
};
messages.push(ChatCompletionMessage { role: GPTRole::User, content: parsed_content.clone() });
messages.push(ChatCompletionMessage {
role: GPTRole::User,
content: parsed_content.clone(),
});
let request = ChatCompletionRequest {
model: oai.default_model.clone(),
@@ -61,14 +64,18 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
max_tokens: Some(oai.max_tokens),
presence_penalty: Some(0.6),
frequency_penalty: Some(0.0),
user: Some(msg.author.name.clone())
user: Some(msg.author.name.clone()),
};
// Get the thread channel ID
let thread_name = generate_thread_name(oai, &parsed_content, 99).await;
let response_channel = match msg.channel_id.create_private_thread(&ctx.http, |thread| {
thread.name(thread_name).kind(ChannelType::PublicThread)
}).await {
let response_channel = match msg
.channel_id
.create_private_thread(&ctx.http, |thread| {
thread.name(thread_name).kind(ChannelType::PublicThread)
})
.await
{
Ok(c) => {
let allow = Permissions::SEND_MESSAGES;
let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
@@ -80,9 +87,7 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
let _ = c.create_permission(&ctx.http, &overwrite).await;
c.id
}
Err(_) => {
channel_id
}
Err(_) => channel_id,
};
let typing = response_channel.start_typing(&ctx.http).unwrap();
@@ -144,7 +149,10 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
async fn generate_thread_name(oai: &OAI, s: &str, max_chars: usize) -> String {
let message = ChatCompletionMessage {
role: GPTRole::User,
content: format!("---\n{}\n---\nSummarize the message above into a concise Discord thread title", s)
content: format!(
"---\n{}\n---\nSummarize the message above into a concise Discord thread title",
s
),
};
let request = ChatCompletionRequest {
model: oai.default_model.clone(),
@@ -155,13 +163,14 @@ async fn generate_thread_name(oai: &OAI, s: &str, max_chars: usize) -> String {
max_tokens: Some(oai.max_tokens),
presence_penalty: Some(0.6),
frequency_penalty: Some(0.0),
user: None
user: None,
};
// Truncate the response to the max number of characters
let mut response = match s.char_indices().nth(max_chars) {
None => s,
Some((idx, _)) => &s[..idx]
}.to_string();
Some((idx, _)) => &s[..idx],
}
.to_string();
// Set the response to the OAI response
match oai.chat_completion(request).await {
Ok(r) => {

View File

@@ -0,0 +1 @@

View File

@@ -1,6 +1,6 @@
pub mod audio;
pub mod help;
pub mod chat;
pub mod help;
pub mod ping;
pub mod schedule;
pub mod roll;
pub mod schedule;

View File

@@ -1,5 +1,8 @@
use log::debug;
use serenity::{model::prelude::interaction::application_command::CommandDataOption, builder::CreateApplicationCommand};
use serenity::{
model::prelude::interaction::application_command::CommandDataOption,
builder::CreateApplicationCommand,
};
pub fn run(_options: &[CommandDataOption]) -> String {
debug!("Ping command executed");
@@ -8,4 +11,4 @@ pub fn run(_options: &[CommandDataOption]) -> String {
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("ping").description("Replies with pong")
}
}

View File

@@ -1,6 +1,12 @@
use log::{error, warn};
use rand::Rng;
use serenity::{builder::CreateApplicationCommand, client::Context, model::application::{command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction}};
use serenity::{
builder::CreateApplicationCommand,
client::Context,
model::application::{
command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction,
},
};
use crate::bot::commands::audio::edit_response;
@@ -49,10 +55,17 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
total += roll;
rolls.push(roll);
}
let response = format!("{}d{}{} = {}",
let response = format!(
"{}d{}{} = {}",
count,
sides,
if modifier > 0 { format!("+{}", modifier) } else if modifier < 0 { format!("-{}", modifier) } else { "".to_string() },
sides,
if modifier > 0 {
format!("+{}", modifier)
} else if modifier < 0 {
format!("-{}", modifier)
} else {
"".to_string()
},
total + (modifier as u32)
);
if let Err(why) = edit_response(&ctx, &command, response).await {
@@ -60,13 +73,12 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
}
Err(why) => {
if let Err(why) = edit_response(&ctx, &command, format!("Invalid dice string: {}", why)).await {
if let Err(why) = edit_response(&ctx, &command, format!("Invalid dice string: {}", why)).await
{
error!("Failed to create response message: {}", why);
}
}
}
}
fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
@@ -74,9 +86,9 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
let count = match parts.next() {
Some(c) => match c.parse::<u32>() {
Ok(n) => n,
Err(_) => return Err(format!("Invalid dice count: {}", c))
Err(_) => return Err(format!("Invalid dice count: {}", c)),
},
None => return Err(format!("Invalid dice string: {}", dice))
None => return Err(format!("Invalid dice string: {}", dice)),
};
let mut positive_modifier = true;
let mut parts = match parts.next() {
@@ -91,8 +103,8 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
} else {
p.split("+")
}
},
None => return Err(format!("Invalid dice string: {}", dice))
}
None => return Err(format!("Invalid dice string: {}", dice)),
};
let sides = match parts.next() {
Some(s) => match s.parse::<u32>() {
@@ -103,9 +115,9 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
return Err(format!("Invalid dice sides: {}", s));
}
}
Err(_) => return Err(format!("Invalid dice sides: {}", s))
Err(_) => return Err(format!("Invalid dice sides: {}", s)),
},
None => return Err(format!("Invalid dice string: {}", dice))
None => return Err(format!("Invalid dice string: {}", dice)),
};
let modifier = match parts.next() {
Some(m) => match m.parse::<i32>() {
@@ -115,20 +127,23 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
} else {
n * -1
}
},
Err(_) => return Err(format!("Invalid dice modifier: {}", m))
}
Err(_) => return Err(format!("Invalid dice modifier: {}", m)),
},
None => 0
None => 0,
};
Ok((count, sides, modifier))
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("roll").description("Rolls D&D dice").create_option(|option| {
option
.name("dice")
.description("Dice to roll")
.kind(CommandOptionType::String)
.required(true)
})
}
command
.name("roll")
.description("Rolls D&D dice")
.create_option(|option| {
option
.name("dice")
.description("Dice to roll")
.kind(CommandOptionType::String)
.required(true)
})
}

View File

@@ -0,0 +1 @@