Adds a Todo, some basic logging and a couple of docs

This commit is contained in:
Dandaedre 2024-10-31 01:05:09 +01:00
parent 1513f25c76
commit 0e98907d38
7 changed files with 194 additions and 140 deletions

8
.gitignore vendored
View File

@ -14,16 +14,14 @@ Cargo.lock
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# Added by cargo
/target
# The discord token
.token
# The coverage report
tarpaulin-report.html
# The log files
*.log

View File

@ -14,6 +14,8 @@ serde = { version = "1.0.214", features = ["alloc", "derive"] }
thiserror = "1.0.65"
tracing = { version = "0.1.40", features = ["async-await", "std"] }
uuid = { version = "1.11.0", features = ["v4", "v7", "serde", "fast-rng"] }
simplelog = { version = "0.12.2", features = ["paris"] }
log = { version = "0.4.22", features = ["std"] }
[profile.dev]
debug = 0

10
TODO.md
View File

@ -3,3 +3,13 @@
[ ] Config recovery
[ ] Error testing framework
# Tasks
## Dan
[ ] Finish testing to reach 100% coverage
[ ] Implement Resilience & Recovery
## Vky
[ ] Write documentation for all functions in IO.rs
[ ] Replace the usage of print with the appropriate logging where needed
[ ] Create all module signature for queries

View File

@ -60,19 +60,19 @@ pub(crate) fn relative_date_to_date(
match match date.month {
Some(m) if m.number_from_month() >= context.month() => context
.with_month(m.number_from_month())
.ok_or(IdleError::DateError),
.ok_or(IdleError::DateParsing),
Some(_m) => context
.checked_add_months(Months::new(12))
.ok_or(IdleError::DateError),
.ok_or(IdleError::DateParsing),
None if date.day >= context.day() => Ok(context),
None => context
.checked_add_months(Months::new(1))
.ok_or(IdleError::DateError),
.ok_or(IdleError::DateParsing),
} {
Ok(new_base) => new_base
.with_day(date.day)
.ok_or(IdleError::DateError(date)),
Err(_) => Err(IdleError::DateError(date)),
.ok_or(IdleError::DateParsing(date)),
Err(_) => Err(IdleError::DateParsing(date)),
}
}

View File

@ -2,6 +2,7 @@
//!
//!
#![allow(dead_code)]
use poise::serenity_prelude;
use thiserror::Error;
use crate::date::PartialDate;
@ -14,9 +15,13 @@ use crate::date::PartialDate;
pub enum IdleError {
/// Error republished when encountering an unrecoverable state in the API
#[error("An unrecoverable error occured while interfacing with the Discord API")]
DiscordAPIError,
GenericDiscordAPI,
/// Error sent when a date given by the user doesn't make sense (aka dec 32, feb 30 etc)
#[error("An error happened while tring to make sense of the date {0:?}")]
DateError(PartialDate),
DateParsing(PartialDate),
/// A generic error when handling discord API calls
#[error("An error occured while processing a Discord API call")]
SerenityAPI(#[from] serenity_prelude::Error),
}
#[cfg(test)]

141
src/io.rs
View File

@ -4,6 +4,147 @@
//! All recv and send functions to discord
//! Helper function for advanced checks
use poise::serenity_prelude as serenity;
/// 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>;
// // Displays your or another user's account creation date
// // Dummy command from poise documentation
// #[poise::command(slash_command, prefix_command)]
// async fn how_old(
// ctx: Context<'_>,
// #[description = "Selected user"] user: Option<serenity::User>,
// ) -> Result<(), Error> {
// let u = user.as_ref().unwrap_or_else(|| ctx.author());
// let response = format!("{}'s account was created at {}", u.name, u.created_at());
// ctx.say(response).await?;
// Ok(())
// }
/// The result of a vote creation
#[derive(Debug, poise::Modal)]
#[allow(dead_code)] // fields only used for Debug print
#[name = "Créer un nouveau Vote"]
struct VoteCreation {
/// The title of the event
#[name = "Titre"]
#[placeholder = "Titre de votre événement"]
title: String,
/// The name of the event
#[name = "Nom du jeu"]
#[placeholder = "'FFXIV', 'MHW', 'D&D'..."]
short_name: Option<String>,
/// The group that shall be tagged by the bot
#[name = "Groupe"]
#[placeholder = "groupe (sans le @)"]
group: Option<String>,
/// The description of the event
#[paragraph]
#[name = "Description"]
#[placeholder = "petite description de votre événement"]
description: String,
/// The time a which the event shall take place
#[name = "Horaires"]
#[placeholder = "'21h - 23h' par défaut"]
hours: 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>,
}
#[poise::command(slash_command)]
pub async fn vote_modal(
ctx: poise::ApplicationContext<'_, Data, GenericError>,
) -> Result<(), GenericError> {
use poise::Modal as _;
let data = VoteCreation::execute(ctx).await?;
println!("Got data: {:?}", data);
if let Some(unwrapped_data) = data {
let group = unwrapped_data.group.unwrap_or("".into());
let title = unwrapped_data.title;
let description = unwrapped_data.description;
let short_name = unwrapped_data.short_name.unwrap_or("".into());
let hours = unwrapped_data.hours.unwrap_or("".into());
let reply = poise::CreateReply::default().content(format!(
"@{} **{}**\n{}\n{}, {}",
group, title, description, short_name, hours
));
ctx.send(reply).await?;
};
Ok(())
}
/// List of choices for all the roles
#[derive(Debug, poise::ChoiceParameter)]
pub enum ListOfRoles {
// TODO: This needs to be a list of all guildRoles under Users (included)
#[name = "hunters"]
Hunters,
}
// 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)]
pub async fn vote_command(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Nom du jeu"] short_name: Option<String>,
#[description = "Groupe"] group: ListOfRoles,
#[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> {
ctx.say(format!(
"{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
title, short_name, group, description, hours, start_date, non_days
))
.await?;
Ok(())
}
/// TODO: Fill doc
#[poise::command(prefix_command, slash_command)]
pub async fn component_modal(ctx: Context<'_>) -> Result<(), GenericError> {
let reply = {
let components = vec![serenity::CreateActionRow::Buttons(vec![
serenity::CreateButton::new("open_modal")
.label("Open modal")
.style(poise::serenity_prelude::ButtonStyle::Success),
])];
poise::CreateReply::default()
.content("Click the button below to open the modal")
.components(components)
};
ctx.send(reply).await?;
while let Some(mci) = serenity::ComponentInteractionCollector::new(ctx.serenity_context())
.timeout(std::time::Duration::from_secs(120))
.filter(move |mci| mci.data.custom_id == "open_modal")
.await
{
let data =
poise::execute_modal_on_component_interaction::<VoteCreation>(ctx, mci, None, None)
.await?;
println!("Got data: {:?}", data);
}
Ok(())
}
#[cfg(test)]
mod tests {
// use super::*;

View File

@ -5,6 +5,12 @@
// This line is here to force the use of extensive documentation
#![warn(clippy::missing_docs_in_private_items)]
use io::{component_modal, vote_command, vote_modal, Data};
use log::LevelFilter;
use simplelog::{
debug, error, info, ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger,
};
mod config;
mod date;
mod error_handling;
@ -17,138 +23,30 @@ mod votes;
mod watchdog;
use poise::serenity_prelude as serenity;
// use poise::{serenity_prelude as serenity, CreateReply};
struct Data {} // User data, which is stored and accessible in all command invocations
type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, Data, Error>;
// // Displays your or another user's account creation date
// // Dummy command from poise documentation
// #[poise::command(slash_command, prefix_command)]
// async fn how_old(
// ctx: Context<'_>,
// #[description = "Selected user"] user: Option<serenity::User>,
// ) -> Result<(), Error> {
// let u = user.as_ref().unwrap_or_else(|| ctx.author());
// let response = format!("{}'s account was created at {}", u.name, u.created_at());
// ctx.say(response).await?;
// Ok(())
// }
#[derive(Debug, poise::Modal)]
#[allow(dead_code)] // fields only used for Debug print
#[name = "Créer un nouveau Vote"]
struct VoteCreation {
#[name = "Titre"]
#[placeholder = "Titre de votre événement"]
title: String,
#[name = "Nom du jeu"]
#[placeholder = "'FFXIV', 'MHW', 'D&D'..."]
short_name: Option<String>,
#[name = "Groupe"]
#[placeholder = "groupe (sans le @)"]
group: Option<String>,
#[paragraph]
#[name = "Description"]
#[placeholder = "petite description de votre événement"]
description: String,
#[name = "Horaires"]
#[placeholder = "'21h - 23h' par défaut"]
hours: 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>,
}
// vote_modal
#[poise::command(slash_command)]
pub async fn vote_modal(ctx: poise::ApplicationContext<'_, Data, Error>) -> Result<(), Error> {
use poise::Modal as _;
let data = VoteCreation::execute(ctx).await?;
println!("Got data: {:?}", data);
if let Some(unwrapped_data) = data {
let group = unwrapped_data.group.unwrap_or("".into());
let title = unwrapped_data.title;
let description = unwrapped_data.description;
let short_name = unwrapped_data.short_name.unwrap_or("".into());
let hours = unwrapped_data.hours.unwrap_or("".into());
let reply = poise::CreateReply::default().content(format!(
"@{} **{}**\n{}\n{}, {}",
group, title, description, short_name, hours
));
ctx.send(reply).await?;
};
Ok(())
}
// List of choices for all the roles
#[derive(Debug, poise::ChoiceParameter)]
pub enum ListOfRoles {
// This needs to be a list of all guildRoles under Users (included)
#[name = "hunters"]
Hunters,
}
// vote_command
#[poise::command(prefix_command, slash_command)]
pub async fn vote_command(
ctx: Context<'_>,
#[description = "Titre"] title: String,
#[description = "Nom du jeu"] short_name: Option<String>,
#[description = "Groupe"] group: ListOfRoles,
#[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<(), Error> {
ctx.say(format!(
"{:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?} ; {:?}",
title, short_name, group, description, hours, start_date, non_days
))
.await?;
Ok(())
}
#[poise::command(prefix_command, slash_command)]
pub async fn component_modal(ctx: crate::Context<'_>) -> Result<(), Error> {
let reply = {
let components = vec![serenity::CreateActionRow::Buttons(vec![
serenity::CreateButton::new("open_modal")
.label("Open modal")
.style(poise::serenity_prelude::ButtonStyle::Success),
])];
poise::CreateReply::default()
.content("Click the button below to open the modal")
.components(components)
};
ctx.send(reply).await?;
while let Some(mci) = serenity::ComponentInteractionCollector::new(ctx.serenity_context())
.timeout(std::time::Duration::from_secs(120))
.filter(move |mci| mci.data.custom_id == "open_modal")
.await
{
let data =
poise::execute_modal_on_component_interaction::<VoteCreation>(ctx, mci, None, None)
.await?;
println!("Got data: {:?}", data);
}
Ok(())
}
use std::fs::File;
#[cfg(not(tarpaulin_include))]
#[tokio::main]
async fn main() {
CombinedLogger::init(vec![
TermLogger::new(
LevelFilter::Warn,
Config::default(),
TerminalMode::Mixed,
ColorChoice::Auto,
),
WriteLogger::new(
LevelFilter::Info,
Config::default(),
// TODO: Maybe add la date du jour de lancement ?
File::create("idlefox.log").unwrap(),
),
])
.unwrap();
error!("Bright red error");
info!("This only appears in the log file");
debug!("This level is currently not enabled for any logger");
// use human_ids::generate;
// use std::{env, time::Instant};