idlefox/src/io.rs

448 lines
16 KiB
Rust

//! Functions to handle I/O operations with Discord.
//!
//! This module contains functions for interacting with the Discord API,
//! including receiving and sending messages, reactions, and managing channels and guilds. It also includes
//! helper functions for performing advanced checks and validations on received data.
//! ### Notes:
//! - The code provided uses the Serenity and Poise frameworks to create a Discord bot that can interact with users through commands and modals.
//! - The `discord_main_loop()` function starts the bot client and registers all command handlers, while the other functions handle specific tasks related to vote creation.
//! - The `VoteCreation` struct is designed to be filled in by users through a modal form or text command arguments. It can then be used to create a new vote within the guild.
//!
//! ### Example usage:
//!
//! ```no_run
//! use idlefox::io::discord_main_loop;
//!
//! #[tokio::main]
//! async fn main() {
//! discord_main_loop().await;
//! }
//! ```
//!
#![allow(dead_code)]
use crate::modules::handler;
use distance::levenshtein;
use poise::serenity_prelude::{self as serenity};
use poise::Modal as _;
use crate::error_handling::IdleError;
/// User data, which is stored and accessible in all command invocations
pub struct Data {}
/// A generic temporary serenity error
type GenericError = Box<dyn std::error::Error + Send + Sync>;
/// The context (in a discord sence) of a message
type Context<'a> = poise::Context<'a, Data, GenericError>;
/// A `VoteContainer` holds the details of a vote that is to be created.
///
/// This struct aggregates all the necessary data describing this event within a Discord guild (server).
/// Generic object that is used to transfer vote data to other parts of the code.
#[derive(Default)]
pub struct VoteContainer {
/// The title of the event
title: String,
/// Description of the event
description: String,
/// An optional serenity::RoleId to specify the role group concerned by the vote.
group: Option<serenity::RoleId>,
/// Optional hours describing the specific date of the event
hours: Option<String>,
/// Short name, used in voting titles
short_name: Option<String>,
/// Auto-Start date of the event (in human-readable format)
start_date: Option<String>,
/// Days not selected for the vote
non_days: Option<String>, // TODO: What ?
/// Days selected for the vote
days: String, // TODO: What ?
/// Date the event begins
date_begin: String,
/// Date the event ends
date_end: String,
/// An identifier for the vote
identifier: VoteTypeIdentifier,
}
/// Only title, description and identifier are mandatory
impl VoteContainer {
pub fn new(title: String, description: String, identifier: VoteTypeIdentifier) -> Self {
Self {
title,
description,
identifier,
..Default::default()
}
}
}
// /// Default is None
// impl Default for VoteContainer {
// fn default() -> Self {
// Self {
// title: "".to_string(),
// description: "".to_string(),
// group: None,
// hours: None,
// short_name: None,
// start_date: None,
// non_days: None,
// days: "".to_string(),
// date_begin: "".to_string(),
// date_end: "".to_string(),
// identifier: VoteTypeIdentifier::Uninitialised,
// }
// }
// }
/// Identifies the type of the vote being created.
///
/// This enum represents different types of votes, such as regular weekly votes,
/// short-term votes, and long-term votes. It also serves as an indicator when a vote type
/// hasn't been initialized yet.
#[derive(Default)]
pub enum VoteTypeIdentifier {
// Represents a recurring weekly vote, with the list of days voted upon being one week
WeeklyVote,
/// Represents a short-term vote, that can be of any length and can be cast at any time without any form or plan.
ShortVote,
/// Represents a long-term vote, where the list of days voted upon extends beyond a week.
LongVote,
/// Indicates that the vote type has not been set yet, should only be used by default and is not a valid value.
#[default]
Uninitialised,
}
/// The result of a vote creation.
///
/// This struct is used to store and display the results of creating a new vote via a discord modal form.
#[derive(Debug, poise::Modal)]
#[allow(dead_code)] // fields only used for Debug print
#[name = "Créer un nouveau Vote"]
pub(crate) struct WeeklyVoteModal {
/// The title of the event
#[name = "Titre"]
#[placeholder = "Titre de votre événement"]
title: String,
/// The description of the event
#[paragraph]
#[name = "Description"]
#[placeholder = "petite description de votre événement"]
description: String,
/// The group that will be tagged by the bot
#[name = "Groupe"]
#[placeholder = "groupe (sans le @)"]
group: Option<String>,
/// The time a which the event shall take place
#[name = "Horaires"]
#[placeholder = "'21h - 23h' par défaut"]
hours: Option<String>,
/// The name of the event
#[name = "Nom du jeu"]
#[placeholder = "'FFXIV', 'MHW', 'D&D'..."]
short_name: Option<String>,
// Max fields is 5 so the two below will have to be command-exclusive
// #[name = "Date de début du vote"]
// #[placeholder = "'ven', '10', '21 jan', vide pour la prochaine période de votes"]
// start_date: Option<String>,
// #[name = "Jours non dispos"]
// #[placeholder = "'lun', '30', '2 dec'"]
// non_days: Option<String>,
}
#[cfg(test)] // This default implementation only exists during testing
impl Default for WeeklyVoteModal {
fn default() -> Self {
WeeklyVoteModal {
title: "The base test vote".into(),
description: "Dummy vote".into(),
group: Some("Base group".into()),
hours: Some("21h - 23".into()),
short_name: Some("Base vote".into()),
}
}
}
/// Creates a Discord Modal for a user-friendly vote creation form.
///
/// This function triggers the creation of a modal that allows users to input details about an event they would like to organize.
/// The input fields are predefined and include the title, short name of the game or event, group to tag, description,
/// and hours at which the event will take place.
#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call
#[poise::command(slash_command)]
pub async fn vote_modal(
ctx: poise::ApplicationContext<'_, Data, GenericError>,
) -> Result<(), GenericError> {
let data = WeeklyVoteModal::execute(ctx).await?;
if let Some(underlying_data) = data {
log::info!(
"@{:?} **{:?}**\n{:?}\n{:?}, {:?}",
underlying_data.group,
underlying_data.title,
underlying_data.description,
underlying_data.short_name,
underlying_data.hours
);
log::info!("{:?}", &ctx);
// This whole shenennigan only exists to find a group as specified by text and if so apply it
// However many steps can subtly break and cannot be truly accounted for
let guild = ctx
.guild()
.ok_or_else(|| IdleError::AcquiringDiscordGuild)?; // Maybe the guild cannot be retrieved from the context, such as in a DM
let group = find_role_from_str(
underlying_data.group.as_deref(),
guild.roles.values().map(|v| v.name.as_str()).collect(),
)
.ok_or(IdleError::AcquiringDiscordGuild) // Maybe the guild doesn't exits or the match is too far or the group wasn't specified
.and_then(|role_found: String| {
guild
.role_by_name(&role_found)
.ok_or(IdleError::AcquiringDiscordGroup(role_found)) // Maybe somehow the group canno't be acquired by that name
.map(|v| v.id)
})
.inspect_err(
|e| /* Do something when an error occurs*/ log::error!("An error occured when selecting groups from {:?}: {}",&underlying_data.group,e),
) // An inspect that could be used to signal something went wrong acquiring or applying the guild
.ok();
let serotoninenjoyer = VoteContainer {
title: underlying_data.title,
description: underlying_data.description,
group,
hours: underlying_data.hours,
short_name: underlying_data.short_name,
identifier: VoteTypeIdentifier::WeeklyVote,
..Default::default()
};
handler(serotoninenjoyer);
// let reply = poise::CreateReply::default().content(format!(
// "@{} **{}**\n{}\n{}, {}",
// group, title, description, short_name, hours
// ));
// ctx.send(reply).await?;
};
Ok(())
}
/// Attempts to find the most closely matching role from a list based on a provided group name.
///
/// This function takes a `group` string and a vector of role names, and returns the closest match found.
/// If the input `group` is None or the `roles` vector is empty, the function will return None.
/// The search uses the Levenshtein distance algorithm to determine the similarity between strings.
///
/// # Arguments
///
/// * `group` - An `Option<String>` representing the target group name for which a match should be found.
/// * `roles` - A vector of `String`s containing role names to compare against the target group name.
fn find_role_from_str(group: Option<&str>, roles: Vec<&str>) -> Option<String> {
if group.is_none() || roles.is_empty() {
return None;
}
let group = group.unwrap();
// We are hard-coding the maximum value above which we prefer returning None rather than a guess
let mut lowest = (None, 5);
for role in roles {
let d = levenshtein(role, group);
if d < lowest.1 {
lowest = (Some(role), d);
};
}
lowest.0.map(|s| s.to_owned())
}
// /// List of choices for all the roles.
// ///
// /// This enum is used to define a set of predefined choices that users can select from when creating a new vote.
// /// Each choice represents a role within the guild, and it can be referred to using the enum variant name.
// #[derive(Debug, poise::ChoiceParameter)]
// pub enum ListOfRoles {
// // TODO: This needs to be a list of all guildRoles under Users (included)
// // TODO: This needs to be fetched dynamically from the server
// /// placeholder for a role
// #[name = "hunters"]
// Hunters,
// }
/// Text command for extensive vote creation
// Since this is a discord command and not a real rust command, this many arguments is "normal"
#[allow(clippy::too_many_arguments)]
#[poise::command(prefix_command, slash_command)]
#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call
pub async fn vote_command(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Nom du jeu"] short_name: Option<String>,
#[description = "Groupe"] group: Option<serenity::RoleId>,
#[description = "Description"] description: String,
#[description = "Horaires"] hours: Option<String>,
#[description = "Date de début du vote"] start_date: Option<String>,
#[description = "Jours non dispos"] non_days: Option<String>,
) -> Result<(), GenericError> {
let rhubarb = VoteContainer {
title,
description,
// group,
hours,
short_name,
start_date,
non_days,
identifier: VoteTypeIdentifier::WeeklyVote,
..Default::default()
};
handler(rhubarb);
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, short_name, group, description, hours, start_date, non_days
// ))
// .await?;
Ok(())
}
/// Text command for the creation of exeptional votes ; outside normal voting windows.
///
/// This text command is composed of optional group, hours and start_date ; and compulsory title, description and days. days will indicate which days of the week after the start_date will be available for voting.
// Since this is a discord command and not a real rust command, this many arguments is "normal"
#[allow(clippy::too_many_arguments)]
#[poise::command(prefix_command, slash_command)]
#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call
pub async fn short_vote(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Groupe"] group: Option<serenity::RoleId>,
#[description = "Description"] description: String,
#[description = "Horaires"] hours: Option<String>,
#[description = "Jours"] days: String,
#[description = "Date de début du vote"] start_date: Option<String>,
) -> Result<(), GenericError> {
let aortavalve = VoteContainer {
title,
group,
description,
hours,
days,
start_date,
..Default::default()
};
handler(aortavalve);
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, group, description, hours, start_date, days
// ))
// .await?;
Ok(())
}
/// Text command for the creation of long votes
///
/// Text command for the creation of votes that span on a very long period to decide on dates for larger-scale events.
/// Takes mandatory title, description, beginning and end date and optional starting date for the vote.
#[allow(clippy::too_many_arguments)] // As this is not a real command by a discord command, there isn't really that many arguments
#[poise::command(prefix_command, slash_command)]
#[cfg(not(tarpaulin_include))] // Async function only called by a foreign call
pub async fn long_vote(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Description"] description: String,
#[description = "Date de début du vote"] start_date: Option<String>,
#[description = "Date de début de la période de l'événement"] date_begin: String,
#[description = "Date de fin de la période de l'événement"] date_end: String,
) -> Result<(), GenericError> {
let cartoy = VoteContainer {
title,
description,
start_date,
date_begin,
date_end,
..Default::default()
};
handler(cartoy);
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, description, start_date, date_begin, date_end
// ))
// .await?;
Ok(())
}
/// The main discord interaction loop
///
/// Registers all functions and starts a bot client
// As an async loop it is untestable by nature, however this loop aims to stay as simple as possible to be "self testing"
#[cfg(not(tarpaulin_include))]
pub async fn discord_main_loop() {
let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
let intents = serenity::GatewayIntents::non_privileged();
let framework = poise::Framework::builder()
.options(poise::FrameworkOptions {
commands: vec![vote_command(), vote_modal(), short_vote(), long_vote()],
..Default::default()
})
.setup(|ctx, _ready, framework| {
Box::pin(async move {
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(Data {})
})
})
.build();
let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;
client.unwrap().start().await.unwrap();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_levenshtein() {
let arguments = [
"hunters",
"ffxiv_idle",
"ffxiv_progfish",
"ffxiv_minilvl",
"dbd",
"dnd",
"r6",
"apex",
"boardgames",
];
// println!("{:?}", arguments);
// println!(
// "{:?}",
// find_role_from_str(Some("bodyoncetoldme"), arguments.to_vec())
// );
assert!(find_role_from_str(Some("bodyoncetoldme"), arguments.to_vec()).is_none());
assert_eq!(
find_role_from_str(Some("ffxivid"), arguments.to_vec()),
Some("ffxiv_idle".to_string())
);
assert_eq!(
find_role_from_str(Some("hunte"), arguments.to_vec()),
Some("hunters".to_string())
);
assert_eq!(
find_role_from_str(Some("dbd"), arguments.to_vec()),
Some("dbd".to_string())
);
assert_eq!(
find_role_from_str(Some("ffxivpogfish"), arguments.to_vec()),
Some("ffxiv_progfish".to_string())
);
}
}