Compare commits

..

5 Commits
roles ... dev

Author SHA1 Message Date
Dandaedre faba5f1422 Update Jenkinsfile
Rust CI IdleFox passed all CI checks.
Gitea/idlefox/pipeline/head This commit looks good Details
2026-09-13 14:01:18 +02:00
Dandaedre 048be0e619 Update Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:49:51 +02:00
Dandaedre 3968fb97ff Update Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:44:32 +02:00
Dandaedre fec62385a0 Add Jenkinsfile
Rust CI IdleFox failed CI.
Gitea/idlefox/pipeline/head There was a failure building this commit Details
2026-09-13 13:18:22 +02:00
Dandaedre fca5e8ef7a Some typos 2025-01-17 23:58:02 +01:00
12 changed files with 781 additions and 695 deletions

326
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,326 @@
// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post
pipeline {
agent { label 'rust_no_docker' }
environment {
CARGO_TERM_COLOR = 'always'
RUST_BACKTRACE = '1'
// CI gets its own Cargo home. This prevents ~/.cargo/config*
// from injecting host-specific linker options.
CARGO_HOME = "${WORKSPACE}/.ci-cargo-home"
// Keep CI artifacts separate from local/project builds.
CARGO_TARGET_DIR = "${WORKSPACE}/target-ci"
// Explicitly use the native FreeBSD compiler/linker.
CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER = 'cc'
// Explicitly neutralize environment-provided Rust flags.
RUSTFLAGS = ''
CARGO_ENCODED_RUSTFLAGS = ''
}
stages {
stage('Checkout') {
steps {
checkout scm
sh '''
set -eu
git submodule sync --recursive
git submodule update --init --recursive
'''
}
}
stage('Setup Rust') {
steps {
sh '''
set -eu
if ! command -v rustup >/dev/null 2>&1; then
echo "ERROR: rustup is not installed on this worker." >&2
exit 1
fi
echo "Ensuring stable Rust is available..."
rustup toolchain install stable \
--profile minimal \
--component rustfmt \
--component clippy
rustup default stable
# ---------------------------------------------------------
# Prepare isolated Cargo environment
# ---------------------------------------------------------
rm -rf "${CARGO_HOME}"
mkdir -p "${CARGO_HOME}"
rm -rf "${CARGO_TARGET_DIR}"
mkdir -p "${CARGO_TARGET_DIR}"
# Cargo discovers .cargo/config* by walking upward from the
# current working directory. We therefore invoke Cargo from
# a neutral directory outside the repository.
CI_RUN_DIR="/tmp/idlefox-ci-${BUILD_NUMBER}"
rm -rf "${CI_RUN_DIR}"
mkdir -p "${CI_RUN_DIR}"
echo "${CI_RUN_DIR}" > .ci-run-dir
# ---------------------------------------------------------
# Information
# ---------------------------------------------------------
echo
echo "Rust:"
rustc --version
echo
echo "Cargo:"
cargo --version
echo
echo "rustfmt:"
rustfmt --version
echo
echo "Clippy:"
cargo clippy --version
echo
echo "Compiler:"
cc --version
echo
echo "Rust target:"
rustc -vV
echo
echo "Cargo home:"
echo "${CARGO_HOME}"
echo
echo "Cargo target directory:"
echo "${CARGO_TARGET_DIR}"
echo
echo "Neutral Cargo working directory:"
cat .ci-run-dir
echo
echo "Repository Cargo configuration files:"
find "${WORKSPACE}" \
-path '*/.cargo/config' \
-o \
-path '*/.cargo/config.toml' \
2>/dev/null || true
echo
echo "Any mold references in repository Cargo configuration:"
if [ -d "${WORKSPACE}/.cargo" ]; then
grep -Rni 'mold' "${WORKSPACE}/.cargo" || true
fi
echo
echo "CI linker:"
echo "${CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER}"
'''
}
}
stage('Format') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking Rust formatting..."
cargo fmt \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all \
-- \
--check
'''
}
}
stage('Check') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking all IdleFox targets..."
cargo check \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Test') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Running IdleFox tests..."
cargo test \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Clippy') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Running Clippy..."
cargo clippy \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--all-targets \
--all-features
'''
}
}
stage('Check Benchmarks') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Checking benchmark compilation..."
cargo check \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--benches \
--all-features
'''
}
}
stage('Build Release') {
steps {
sh '''
set -eu
CI_RUN_DIR="$(cat "${WORKSPACE}/.ci-run-dir")"
cd "${CI_RUN_DIR}"
echo "Building IdleFox release..."
cargo build \
--manifest-path "${WORKSPACE}/Cargo.toml" \
--release \
--all-features
echo
echo "Release build completed."
BINARY="${CARGO_TARGET_DIR}/release/idlefox"
if [ ! -f "${BINARY}" ]; then
echo "ERROR: expected release binary was not produced:"
echo "${BINARY}"
exit 1
fi
echo
echo "Release binary:"
ls -lh "${BINARY}"
echo
echo "Binary type:"
file "${BINARY}" || true
'''
}
}
}
post {
success {
publishChecks(
conclusion: 'SUCCESS',
name: 'Rust CI',
summary: 'IdleFox passed all CI checks.',
text: 'Formatting, compilation checks, tests, Clippy, benchmark compilation, and release build completed successfully using the native FreeBSD linker.',
title: 'Build Successful'
)
echo '✅ IdleFox passed all CI checks.'
}
failure {
publishChecks(
conclusion: 'FAILURE',
name: 'Rust CI',
summary: 'IdleFox failed CI.',
text: 'Formatting, compilation, tests, Clippy, benchmarks, or the release build failed. Check the Jenkins log.',
title: 'Build Failed'
)
echo '❌ IdleFox CI failed.'
}
unstable {
publishChecks(
conclusion: 'ACTION_REQUIRED',
name: 'Rust CI',
summary: 'IdleFox CI is unstable.',
text: 'The Jenkins build completed with an unstable status.',
title: 'Build Unstable'
)
echo '⚠️ IdleFox CI is unstable.'
}
always {
sh '''
echo "Cleaning IdleFox CI environment..."
if [ -f .ci-run-dir ]; then
CI_RUN_DIR="$(cat .ci-run-dir)"
rm -rf "${CI_RUN_DIR}"
fi
rm -f .ci-run-dir
rm -rf .ci-cargo-home
# Keep target-ci for now so Jenkins retains incremental
# compilation between builds. Uncomment to make every build
# completely clean:
#
# rm -rf target-ci
'''
}
}
}

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 69%"><title>test-coverage: 69%</title><linearGradient id="bms-8ba437738373524c" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-8ba437738373524c"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-8ba437738373524c)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#e05d44"/><rect width="122" height="18" fill="url(#bms-8ba437738373524c)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">69%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">69%</text></g></svg> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 88%"><title>test-coverage: 88%</title><linearGradient id="bms-7f01f1ef66d48313" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-7f01f1ef66d48313"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-7f01f1ef66d48313)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#fe7d37"/><rect width="122" height="18" fill="url(#bms-7f01f1ef66d48313)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">88%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">88%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -2,12 +2,12 @@
//! //!
//! This module provides a centralized configuration system for IdleFox, allowing you to load and manage your settings in an efficient and flexible manner. //! This module provides a centralized configuration system for IdleFox, allowing you to load and manage your settings in an efficient and flexible manner.
//! //!
//! The primary goal of this module is to provide a robust and reliable way to store and retrieve configuration data from the `.idlefox.toml` file. //! The primary goal of this module is to provide a robust and reliable way to store and retrieve configuration data from the `config.json` file.
//! If the file does not exist or cannot be loaded, it will automatically create a default version for you. //! If the file does not exist or cannot be loaded, it will automatically create a default version for you.
//! //!
//! ### Key Features //! ### Key Features
//! //!
//! * **Config Loading**: Seamlessly load your existing config from the `.idlefox.toml` file, ensuring that all settings are preserved and up-to-date. //! * **Config Loading**: Seamlessly load your existing config from the `config.json` file, ensuring that all settings are preserved and up-to-date.
//! * **Default Config Creation**: Automatically generate a default configuration if the specified file cannot be loaded or is missing. //! * **Default Config Creation**: Automatically generate a default configuration if the specified file cannot be loaded or is missing.
//! * **Legacy Data Import**: Safely import old data from outdated configurations to minimize disruptions during upgrades. //! * **Legacy Data Import**: Safely import old data from outdated configurations to minimize disruptions during upgrades.
//! * **Faulty Data Recovery**: Implement measures to recover from importing faulty data, ensuring that your IdleFox instance remains stable and functional. //! * **Faulty Data Recovery**: Implement measures to recover from importing faulty data, ensuring that your IdleFox instance remains stable and functional.

View File

@ -17,7 +17,7 @@
//! left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`. //! left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`.
//! The function uses the context provided to resolve any relative dates within the input string. //! The function uses the context provided to resolve any relative dates within the input string.
//! //!
//! - [`parse_single_date`]: This function parses a given input string representing a single date and returns a `NaiveDate`. //! - [parse_single_date]: This function parses a given input string representing a single date and returns a `NaiveDate`.
//! If there are any unparsed parts left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`. //! If there are any unparsed parts left after processing the input, they can be retrieved using the `unparsed` method on the returned `Result`.
//! The function uses the context provided to resolve any relative dates within the input string. //! The function uses the context provided to resolve any relative dates within the input string.
//! //!

437
src/io.rs Normal file
View File

@ -0,0 +1,437 @@
//! 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;
//! use idlefox::votes::EventHolder;
//!
//! #[tokio::main]
//! async fn main() {
//! let ctx = EventHolder::default();
//! discord_main_loop(ctx).await;
//! }
//! ```
//!
#![allow(dead_code)]
use crate::modules::handler;
use crate::votes::EventHolder;
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 {
/// The global event holder
event_holder: EventHolder,
}
/// 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
pub(crate) title: String,
/// Description of the event
pub(crate) description: String,
/// An optional serenity::RoleId to specify the role group concerned by the vote.
pub(crate) group: Option<serenity::RoleId>,
/// Optional hours describing the specific date of the event
pub(crate) hours: Option<String>,
/// Auto-Start date of the event (in human-readable format)
pub(crate) start_date: Option<String>,
/// Days not selected for the vote
pub(crate) non_days: Option<String>,
/// Days selected for the vote
pub(crate) days: Option<String>,
/// Date the event begins
pub(crate) date_begin: Option<String>,
/// Date the event ends
pub(crate) date_end: Option<String>,
/// An identifier for the vote
pub(crate) 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()
}
}
}
/// 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 date from which the vote can become active
#[name = "Date de début du vote"]
#[placeholder = "'ven', '10', '21 jan', vide pour la prochaine période de votes"]
start_date: Option<String>,
/// Days for which reactions should "not count"
#[name = "Jours non dispos"]
#[placeholder = "'lun', '30', '2 dec'"]
non_days: Option<String>,
// Max fields is 5 so the two below will have to be command-exclusive
// /// The time a which the event shall take place
// #[name = "Horaires"]
// #[placeholder = "'21h - 23h' par défaut"]
// hours: 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()),
start_date: Some("10 fev".to_owned()),
non_days: Some("10".to_owned()),
}
}
}
/// 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.title,
underlying_data.non_days
);
// 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 exist 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 cannot 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,
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 = "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,
start_date,
non_days,
identifier: VoteTypeIdentifier::WeeklyVote,
..Default::default()
};
let _ = ctx;
handler(rhubarb);
// TODO: Log and check that the handle does handle everything
// 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> {
handler(VoteContainer {
title,
group,
description,
hours,
days: Some(days),
start_date,
..Default::default()
});
let _ = ctx;
// TODO: Log and checks ?
// 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 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,
#[description = "Date (optionelle) de début du vote"] start_date: Option<String>,
) -> Result<(), GenericError> {
handler(VoteContainer {
title,
description,
start_date,
date_begin: Some(date_begin),
date_end: Some(date_end),
..Default::default()
});
let _ = ctx;
// TODO: Log and checks ?
// 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(event_holder: EventHolder) {
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 {
event_holder.discord_ctx.lock().await.replace(ctx.clone());
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(Data { event_holder })
})
})
.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())
);
assert!(find_role_from_str(None, arguments.to_vec()).is_none());
assert!(find_role_from_str(Some("Bob"), Vec::new()).is_none());
}
#[test]
fn create_container() {
VoteContainer::new(
"IO".to_string(),
"desc".to_string(),
VoteTypeIdentifier::WeeklyVote,
);
}
}

View File

@ -1,374 +0,0 @@
//! 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.
//!
//! ### 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.
#![allow(dead_code)]
use std::collections::HashSet;
use std::fmt::Write;
use crate::error_handling::IdleError;
use crate::io::utilities::find_list_groups;
use crate::{
io::{
Context, Data, GenericError, InputRoleName, RoleFound, RoleIdTuple, VoteContainer,
VoteTypeIdentifier, WeeklyVoteModal,
},
modules::handler,
votes::EventHolder,
};
use log::info;
use poise::serenity_prelude::EditMember;
use poise::{serenity_prelude as serenity, Modal};
/// 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> {
use crate::io::utilities::find_roleid;
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.title,
underlying_data.non_days
);
// 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_roleid(
&InputRoleName::StringName(underlying_data.group.unwrap()),
&guild.roles.iter().map(|(roleid,name)| (*roleid,name.name.as_str())).collect::<Vec<RoleIdTuple>>(),
)
.ok_or(IdleError::AcquiringDiscordGuild) // Maybe the guild doesn't exist or the match is too far or the group wasn't specified
// .and_then(|role_found| {
// guild
// .role_by_name(&role_found)
// .ok_or(IdleError::AcquiringDiscordGroup(role_found)) // Maybe somehow the group cannot 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: {}",e),
) // An inspect that could be used to signal something went wrong acquiring or applying the guild
.ok();
// TODO: Check this whole function
let serotoninenjoyer = VoteContainer {
title: underlying_data.title,
description: underlying_data.description,
group,
// hours: underlying_data.hours,
identifier: VoteTypeIdentifier::WeeklyVote,
..Default::default()
};
handler(serotoninenjoyer);
};
Ok(())
}
/// 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 = "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,
start_date,
non_days,
identifier: VoteTypeIdentifier::WeeklyVote,
..Default::default()
};
let _ = ctx;
handler(rhubarb);
// TODO: Log and check that the handle does handle everything
// 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> {
handler(VoteContainer {
title,
group,
description,
hours,
days: Some(days),
start_date,
..Default::default()
});
let _ = ctx;
// TODO: Log and checks ?
// 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 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,
#[description = "Date (optionelle) de début du vote"] start_date: Option<String>,
) -> Result<(), GenericError> {
handler(VoteContainer {
title,
description,
start_date,
date_begin: Some(date_begin),
date_end: Some(date_end),
..Default::default()
});
let _ = ctx;
// TODO: Log and checks ?
// ctx.say(format!(
// "{:?} ; {:?} ; {:?} ; {:?} ; {:?}",
// title, description, start_date, date_begin, date_end
// ))
// .await?;
Ok(())
}
/// Parent command for all vote handling
///
/// Can't be invoked, so left empty.
#[poise::command(
slash_command,
prefix_command,
subcommands("add_one", "remove_one", "add_many"),
subcommand_required
)]
pub async fn role(_: Context<'_>) -> Result<(), GenericError> {
Ok(())
}
/// Add one role from the list of all server roles.
///
/// Add the role the user chose among the list and returns
/// an ephemeral as confirmation. Will return "Missing Permissions"
/// if the role asked is above the Bot's own role.
#[poise::command(slash_command, prefix_command)]
async fn add_one(
ctx: Context<'_>,
#[description = "Role"] role: serenity::Role,
) -> Result<(), GenericError> {
if ctx
.author()
.has_role(ctx, ctx.guild_id().unwrap(), &role)
.await?
{
ctx.defer_ephemeral().await?;
ctx.reply(format!("You already have the role {}.", &role))
.await?;
} else {
ctx.http()
.add_member_role(
ctx.guild_id().unwrap(),
ctx.author().id,
role.id,
Some("Self requested."),
)
.await?;
ctx.defer_ephemeral().await?;
ctx.reply(format!("Successfully added role {}.", &role))
.await?;
}
Ok(())
}
// TODO: Add doc
#[poise::command(slash_command, prefix_command)]
async fn add_many(
ctx: Context<'_>,
#[description = "List of roles"] roles: String,
) -> Result<(), GenericError> {
let roles_found: HashSet<RoleFound> = find_list_groups(roles, &ctx.guild().unwrap().roles);
info!("Roles found : {:?}", roles_found);
let mut existing_roles = ctx
.http()
.get_member(ctx.guild_id().unwrap(), ctx.author().id)
.await?
.roles;
let mut not_found_roles = Vec::new();
for role in roles_found {
match role {
RoleFound::FoundId(role_id) => {
if !existing_roles.contains(&role_id) {
existing_roles.push(role_id);
}
}
RoleFound::NotFound(name) => not_found_roles.push(name),
}
}
ctx.guild_id()
.unwrap()
.edit_member(
ctx.http(),
ctx.author(),
EditMember::new().roles(&existing_roles),
)
.await?;
let mut status = format!("Your new roles are {:?}.", &existing_roles);
ctx.defer_ephemeral().await?;
if !not_found_roles.is_empty() {
write!(
status,
"\nThe following roles were not added as they couldn't be found {:?}.",
&not_found_roles
)?;
}
ctx.reply(status).await?;
Ok(())
}
/// Remove one role from the list of all server roles.
///
/// Removes the role the user chose among the list and returns
/// an ephemeral as confirmation. Will return "Missing Permissions"
/// if the role asked is above the Bot's own role.
#[poise::command(slash_command, prefix_command)]
async fn remove_one(
ctx: Context<'_>,
#[description = "Role"] role: serenity::Role,
) -> Result<(), GenericError> {
if ctx
.author()
.has_role(ctx, ctx.guild_id().unwrap(), &role)
.await?
{
ctx.http()
.remove_member_role(
ctx.guild_id().unwrap(),
ctx.author().id,
role.id,
Some("Self requested."),
)
.await?;
ctx.defer_ephemeral().await?;
ctx.reply(format!("Successfully removed role {}.", &role))
.await?;
} else {
ctx.defer_ephemeral().await?;
ctx.reply(format!("You do not have the role {}.", &role))
.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(event_holder: EventHolder) {
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(),
role(),
],
..Default::default()
})
.setup(|ctx, _ready, framework| {
Box::pin(async move {
event_holder.discord_ctx.lock().await.replace(ctx.clone());
poise::builtins::register_globally(ctx, &framework.options().commands).await?;
Ok(Data { event_holder })
})
})
.build();
let client = serenity::ClientBuilder::new(token, intents)
.framework(framework)
.await;
client.unwrap().start().await.unwrap();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_container() {
VoteContainer::new(
"IO".to_string(),
"desc".to_string(),
VoteTypeIdentifier::WeeklyVote,
);
}
}

View File

@ -1,181 +0,0 @@
//! The `ui` 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.
//!
//! It consists of several submodules:
//!
//! - `discord_calls`: Contains all functions that make direct calls to discord.
//! - `utilities`: Helper functions used in multiple places.
//!
//! # Functions
//!
//! The following functions are re-exported from the submodule `discord_calls`:
//!
//! - [discord_main_loop]: Starts the bot client and registers all command handlers.
//! - [create_new_vote]: Creates a new vote based on user input.
//!
//! # Examples
//!
//! ```no_run
//! use idlefox::io::discord_main_loop;
//! use idlefox::votes::EventHolder;
//!
//! #[tokio::main]
//! async fn main() {
//! let ctx = EventHolder::default();
//! discord_main_loop(ctx).await;
//! }
//! ```
//!
#![allow(dead_code)]
use crate::votes::EventHolder;
use poise::serenity_prelude::RoleId;
use poise::serenity_prelude::{self as serenity};
pub mod discord_calls;
pub(crate) mod utilities;
// Republish main function
pub use discord_calls::discord_main_loop;
/// User data, which is stored and accessible in all command invocations
pub struct Data {
/// The global event holder
event_holder: EventHolder,
}
/// 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 tuple used internally to hold a RoleId and it's associated name close together
///
/// Since a levenshtein function will be used on all members a HashMap cannot be used instead
type RoleIdTuple<'a> = (serenity::RoleId, &'a str);
/// Describes a role either found in the context.roles or not found
#[derive(Debug, Hash, Eq, PartialEq)]
pub(crate) enum RoleFound {
/// Indicates a role was found
FoundId(RoleId),
/// Indicates a role couldn't be found
NotFound(String),
}
/// An enum representing a parsed user input
///
/// This input can either be:
/// - A `@Role`, translated by discord into a pseudo-user-id
/// - A `String`, giving the role name supposedly matching an existing role
pub(crate) enum InputRoleName {
/// A string representing an existing role
StringName(String),
/// An user id
IDName(RoleId),
}
/// 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
pub(crate) title: String,
/// Description of the event
pub(crate) description: String,
/// An optional serenity::RoleId to specify the role group concerned by the vote.
pub(crate) group: Option<serenity::RoleId>,
/// Optional hours describing the specific date of the event
pub(crate) hours: Option<String>,
/// Auto-Start date of the event (in human-readable format)
pub(crate) start_date: Option<String>,
/// Days not selected for the vote
pub(crate) non_days: Option<String>,
/// Days selected for the vote
pub(crate) days: Option<String>,
/// Date the event begins
pub(crate) date_begin: Option<String>,
/// Date the event ends
pub(crate) date_end: Option<String>,
/// An identifier for the vote
pub(crate) 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()
}
}
}
/// 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 date from which the vote can become active
#[name = "Date de début du vote"]
#[placeholder = "'ven', '10', '21 jan', vide pour la prochaine période de votes"]
start_date: Option<String>,
/// Days for which reactions should "not count"
#[name = "Jours non dispos"]
#[placeholder = "'lun', '30', '2 dec'"]
non_days: Option<String>,
// Max fields is 5 so the two below will have to be command-exclusive
// /// The time a which the event shall take place
// #[name = "Horaires"]
// #[placeholder = "'21h - 23h' par défaut"]
// hours: 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()),
start_date: Some("10 fev".to_owned()),
non_days: Some("10".to_owned()),
}
}
}

View File

@ -1,102 +0,0 @@
//! Utilities functions used to help interact with discord API calls
//!
//! This module provides utility functions related to finding roles in Discord based on user input.
//! It includes functions that compare strings using the Levenshtein distance algorithm to find the closest match.
//!
use std::collections::{HashMap, HashSet};
use distance::levenshtein;
use poise::serenity_prelude::{Role, RoleId};
use super::{InputRoleName, RoleFound, RoleIdTuple};
/// Find a roleid from user input either by passing the roleid parsed or trying to find one from the list of roles given in the haystack
pub(super) fn find_roleid(needle: &InputRoleName, haystack: &[RoleIdTuple]) -> Option<RoleId> {
match needle {
InputRoleName::StringName(name) => find_roleid_from_str(name, haystack),
InputRoleName::IDName(role_id) => Some(*role_id),
}
}
/// Attempts to find the most closely matching RoleId from a list based on a provided group name.
///
/// This function takes a `needle` string and a vector of , and returns the closest match found.
/// If the input `needle` is None or the `haystack` vector is empty, the function will return None.
/// The search uses the Levenshtein distance algorithm to determine the similarity between strings.
///
/// # Arguments
///
/// * `needle` - An `Option<String>` representing the target group name for which a match should be found.
/// * `haystack` - A vector of `String`s containing role names to compare against the target group name.
pub(super) fn find_roleid_from_str(needle: &str, haystack: &[RoleIdTuple]) -> Option<RoleId> {
// We are hard-coding the maximum value above which we prefer returning None rather than a guess
let mut lowest = (None, 5);
for (roleid, role) in haystack {
let d = levenshtein(role, needle);
if d < lowest.1 {
lowest = (Some(roleid), d);
};
}
lowest.0.copied()
}
/// Find the list of groups that match the sting using the hashmap of existing role ids
///
/// TODO: This function includes a banlist of group that can't be matched no matter what
pub(super) fn find_list_groups(
roles: String,
hashmap_roles: &HashMap<RoleId, Role>,
) -> HashSet<RoleFound> {
// TODO: import banlist from config
// TODO: move this role prunning to before levenstein (find_role_from_str)
// let fetched_list_of_server_roles = ;
let list_of_roles: Vec<(RoleId, &str)> = hashmap_roles
.iter()
.map(|(&roleid, role)| (roleid, role.name.as_str()))
.collect();
// TODO: Use a parser to determine the wether it's an id or a String and use it instead of a split(",")
roles
.split(",")
.map(|role| match find_roleid_from_str(role, &list_of_roles) {
Some(role_id) => RoleFound::FoundId(role_id),
None => RoleFound::NotFound(role.to_string()),
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_find_roleid() {
let arguments = [
(RoleId::new(3), "hunters"),
(RoleId::new(4), "ffxiv_idle"),
(RoleId::new(5), "ffxiv_progfish"),
(RoleId::new(6), "ffxiv_minilvl"),
(RoleId::new(7), "dbd"),
(RoleId::new(8), "dnd"),
(RoleId::new(9), "r6"),
(RoleId::new(10), "apex"),
(RoleId::new(11), "boardgames"),
];
assert!(find_roleid_from_str("bodyoncetoldme", &arguments).is_none());
assert_eq!(
find_roleid_from_str("ffxivid", &arguments),
Some(RoleId::new(4))
);
assert_eq!(
find_roleid_from_str("hunte", &arguments),
Some(RoleId::new(3))
);
assert_eq!(
find_roleid_from_str("dbd", &arguments),
Some(RoleId::new(7))
);
assert_eq!(
find_roleid_from_str("ffxivpogfish", &arguments),
Some(RoleId::new(5))
);
assert!(find_roleid_from_str("Bob", &Vec::new()).is_none());
}
}

View File

@ -9,20 +9,20 @@
//! //!
#![warn(clippy::missing_docs_in_private_items)] #![warn(clippy::missing_docs_in_private_items)]
pub mod config; // Maybe in lib pub mod config; // Maybe in lib
pub mod date; // Definitely in lib pub mod date; // Definitely in lib
mod error_handling; // Likely in lib mod error_handling; // Likely in lib
pub mod ids; // Definitely in lib pub mod ids; // Definitely in lib
pub mod io; // Maybe in lib pub mod io; // Maybe in lib
mod modules; // Maybe in lib mod modules; // Maybe in lib
mod persistence; // Likely in lib mod persistence; // Likely in lib
mod server; // Maybe in lib mod server; // Maybe in lib
pub mod votes; // Likely in lib pub mod votes; // Likely in lib
mod watchdog; // Definitely in lib mod watchdog; // Definitely in lib
// // Re export // // Re export
// pub use votes::add_future_event; // pub use votes::add_future_event;
// pub use votes::launch_future_event; // pub use votes::launch_future_event;
//
pub use error_handling::IdleError; pub use error_handling::IdleError;
pub use watchdog::main_scheduler_loop; pub use watchdog::main_scheduler_loop;

View File

@ -6,6 +6,7 @@
#![warn(clippy::missing_docs_in_private_items)] #![warn(clippy::missing_docs_in_private_items)]
use idlefox::config::init_logger; use idlefox::config::init_logger;
use idlefox::io::discord_main_loop;
use idlefox::main_scheduler_loop; use idlefox::main_scheduler_loop;
use tokio::time; use tokio::time;
@ -24,5 +25,5 @@ async fn main() {
time::interval(time::Duration::from_secs(5)), time::interval(time::Duration::from_secs(5)),
event_context.clone(), event_context.clone(),
)); ));
idlefox::io::discord_main_loop(event_context).await; discord_main_loop(event_context).await;
} }

View File

@ -27,7 +27,7 @@ use poise::serenity_prelude::{self, CacheHttp, ChannelId};
#[cfg(not(tarpaulin_include))] // This loop is untestable instead the logic is kept to the minimal #[cfg(not(tarpaulin_include))] // This loop is untestable instead the logic is kept to the minimal
pub async fn main_scheduler_loop(mut interval: tokio::time::Interval, ev_ctx: EventHolder) { pub async fn main_scheduler_loop(mut interval: tokio::time::Interval, ev_ctx: EventHolder) {
loop { loop {
// fk_around(&ev_ctx).await; fk_around(&ev_ctx).await;
interval.tick().await; interval.tick().await;
// tokio::spawn(async {watchdog_update().await;}); // For async task // tokio::spawn(async {watchdog_update().await;}); // For async task
let ev = ev_ctx.clone(); let ev = ev_ctx.clone();

21
todo.md
View File

@ -1,21 +0,0 @@
# Refresh roles setup
Admin-only command
## Prepwork
- Retrieve all roles
- Separe them in groups of X (maximum per message)
- Make sure we know which messages to delete (probably will be a bot-only channel so all messages should be fine)
## Command execution
- Delete all messages (only the right ones)
- Repost all messages
- We need as many messages as will fit all the buttons
- (optional) last message "new roles XXX" with links to where the buttons are?
## Buttons
- One button per role
- Toggles role on-click
# Add / Remove roles
- /roles_add and /roles_remove with an option fed from list of roles
- if possible, as many options as people want
- /roles_list returns a list of all user roles