diff --git a/.gitignore b/.gitignore index 9fe30f2..20fb2a3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target /chombot/data.toml +tournament_updates.json diff --git a/Cargo.lock b/Cargo.lock index 653b54e..f0e3386 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -308,7 +308,10 @@ dependencies = [ "reqwest 0.13.5", "riichi_hand", "scraper", + "serde", + "serde_json", "slug", + "tempfile", "tokio", ] diff --git a/README.md b/README.md index 77bbbfd..986f912 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,9 @@ cargo run --bin chombot --release Please note that the working directory serves as a persistence storage for the bot's state, so the bot process must have write permissions for it. ### Creating channels -`/create_channel` creates a text channel in the current channel's category (or a chosen one), if both you and the bot could create it there. Its name suggestions come from the [EMA calendar](http://mahjong-europe.org/ranking/Calendar.html); picking a tournament names the channel like `🏆2026-02-kraków-hatsumi-taikai-2026` and sets the topic to `Kraków :: 14-15 lutego 2026 :: https://...`. +`/create_channel` creates a text channel in the current channel's category (or a chosen one), if both you and the bot could create it there. Its name suggestions come from the [EMA calendar](http://mahjong-europe.org/ranking/Calendar.html), latest TOURNAMENTS UPDATE first; picking a tournament names the channel like `🏆2026-02-kraków-hatsumi-taikai-2026` and sets the topic to `Kraków :: 14-15 lutego 2026 :: https://...`. + +Tournaments in TOURNAMENTS UPDATE posts are numbered with the server's `:1m:` … `:10m:` emotes (or 1️⃣ … 🔟); clicking a number creates that tournament's channel the same way. The bot keeps the posted updates in `tournament_updates.json` in its working directory. `/tournament_update_test` posts a test update. ### chombot-kcc In addition to the base version of Chombot, there is also an enhanced version called Chombot-kcc available. This is version tailored for the needs of Krakow Chombo Club and contains a few additional (possibly hermetic) features. diff --git a/chombot-common/Cargo.toml b/chombot-common/Cargo.toml index 37d97e9..a80176a 100644 --- a/chombot-common/Cargo.toml +++ b/chombot-common/Cargo.toml @@ -18,5 +18,10 @@ poise.workspace = true reqwest.workspace = true riichi_hand.workspace = true scraper.workspace = true +serde.workspace = true +serde_json.workspace = true slug.workspace = true tokio.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/chombot-common/src/chombot.rs b/chombot-common/src/chombot.rs index d82e216..8c7ff21 100644 --- a/chombot-common/src/chombot.rs +++ b/chombot-common/src/chombot.rs @@ -11,6 +11,7 @@ use riichi_hand::raster_renderer::martin_persson_tile_sets::MARTIN_PERSSON_TILE_ use riichi_hand::raster_renderer::{HandRenderError, RasterRenderer, RenderOptions, TileSet}; use crate::tournaments_watcher::cache::TournamentsCache; +use crate::tournaments_watcher::updates::TournamentUpdates; #[derive(Debug)] pub enum ChombotBaseError { @@ -60,12 +61,17 @@ pub enum TileStyle { #[derive(Default)] pub struct ChombotBase { tournaments: Arc, + tournament_updates: Arc, } impl ChombotBase { + /// `tournament_updates` should be shared with the tournaments watcher. #[must_use] - pub fn new() -> Self { - Self::default() + pub fn new(tournament_updates: Arc) -> Self { + Self { + tournaments: Arc::default(), + tournament_updates, + } } #[must_use] @@ -73,6 +79,11 @@ impl ChombotBase { &self.tournaments } + #[must_use] + pub fn tournament_updates(&self) -> &TournamentUpdates { + &self.tournament_updates + } + pub fn render_hand(hand: &str, tile_style: &TileStyle) -> ChombotResult { let tile_set: Box = match tile_style { TileStyle::Yellow => Box::new(&*YELLOW_FLUFFY_STUFF_TILE_SET), diff --git a/chombot-common/src/lib.rs b/chombot-common/src/lib.rs index c256bba..a0bbe6c 100644 --- a/chombot-common/src/lib.rs +++ b/chombot-common/src/lib.rs @@ -17,6 +17,7 @@ use crate::tournaments_watcher::ema::Tournaments; use crate::tournaments_watcher::notifier::{ TournamentWatcherChannelListProvider, TournamentsChannelMessageNotifier, }; +use crate::tournaments_watcher::updates::TournamentUpdates; pub mod channel_creator; pub mod chombot; @@ -26,6 +27,7 @@ pub mod discord_utils; pub mod scraping_utils; pub mod slash_commands; pub mod tournament_channel; +pub mod tournament_reactions; pub mod tournaments_watcher; pub trait ChombotPoiseUserData: Sync { @@ -34,12 +36,17 @@ pub trait ChombotPoiseUserData: Sync { pub type ChombotPoiseContext<'a, T> = Context<'a, T, anyhow::Error>; +/// With `reactions`, tournaments in the updates get numbered reactions that +/// create their channels (see [`tournament_reactions`]). pub fn start_tournaments_watcher( channel_list_provider: T, + updates: Arc, + reactions: bool, ctx: SerenityContext, tournaments: Arc, ) { - let notifier = TournamentsChannelMessageNotifier::new(channel_list_provider); + let notifier = + TournamentsChannelMessageNotifier::new(channel_list_provider, updates, reactions); tokio::spawn(async move { DataWatcher::new(notifier, || async { tournaments diff --git a/chombot-common/src/slash_commands/create_channel.rs b/chombot-common/src/slash_commands/create_channel.rs index 5332d43..5335e52 100644 --- a/chombot-common/src/slash_commands/create_channel.rs +++ b/chombot-common/src/slash_commands/create_channel.rs @@ -127,7 +127,12 @@ async fn autocomplete_tournament( return CreateAutocompleteResponse::new(); }; - let choices = matching_tournaments(&tournaments, partial) + let recent = ctx + .data() + .chombot() + .tournament_updates() + .recent_tournaments(); + let choices = matching_tournaments(&tournaments, &recent, partial) .into_iter() .map(|entry| { let label = choice_label(entry); @@ -137,9 +142,11 @@ async fn autocomplete_tournament( CreateAutocompleteResponse::new().set_choices(choices) } -/// Upcoming tournaments first, then the rest. +/// Tournaments from the most recent updates (`recent`) first, then upcoming +/// ones, then the rest. fn matching_tournaments<'a>( tournaments: &'a Tournaments, + recent: &[String], partial: &str, ) -> Vec<&'a TournamentEntry> { let partial = partial.trim().to_lowercase(); @@ -152,7 +159,13 @@ fn matching_tournaments<'a>( }) .unique_by(|entry| (&entry.name, &entry.place, &entry.date)) .collect(); - matching.sort_by_key(|entry| !entry.results_status.is_empty()); + matching.sort_by_key(|entry| { + let recent_rank = recent.iter().position(|name| *name == entry.name); + ( + recent_rank.unwrap_or(usize::MAX), + !entry.results_status.is_empty(), + ) + }); matching.truncate(AUTOCOMPLETE_MAX_CHOICES); matching } @@ -229,26 +242,27 @@ mod tests { } #[test] - fn suggests_upcoming_tournaments_first() { + fn suggests_recent_then_upcoming_tournaments() { let calendar = calendar(); - let suggest = |partial: &str| -> Vec { - matching_tournaments(&calendar, partial) + let suggest = |recent: &[&str], partial: &str| -> Vec { + let recent: Vec = recent.iter().map(|&name| name.to_owned()).collect(); + matching_tournaments(&calendar, &recent, partial) .into_iter() .map(choice_label) .collect() }; assert_eq!( - suggest(""), + suggest(&["Hatsumi Taikai 2027"], ""), vec![ + "Hatsumi Taikai 2027 (13-14 lutego 2027, Kraków)", "Pumpkin Tiles 2026 (31 października 2026, Erywań)", "Warsaw Riichi Cup (5 grudnia 2026, Warszawa)", - "Hatsumi Taikai 2027 (13-14 lutego 2027, Kraków)", "Pumpkin Tiles 2026 (10-11 października 2026, Tbilisi)", ] ); assert_eq!( - suggest("WARSAW"), + suggest(&[], "WARSAW"), vec!["Warsaw Riichi Cup (5 grudnia 2026, Warszawa)"] ); } diff --git a/chombot-common/src/slash_commands/mod.rs b/chombot-common/src/slash_commands/mod.rs index cc90774..c98033a 100644 --- a/chombot-common/src/slash_commands/mod.rs +++ b/chombot-common/src/slash_commands/mod.rs @@ -1,3 +1,4 @@ pub mod create_channel; pub mod hand; pub mod score; +pub mod tournament_update_test; diff --git a/chombot-common/src/slash_commands/tournament_update_test.rs b/chombot-common/src/slash_commands/tournament_update_test.rs new file mode 100644 index 0000000..9ca6180 --- /dev/null +++ b/chombot-common/src/slash_commands/tournament_update_test.rs @@ -0,0 +1,73 @@ +use std::time::Duration; + +use anyhow::Result; +use itertools::Itertools; + +use crate::tournaments_watcher::ema::{TournamentEntry, TournamentStatus, TournamentStatuses}; +use crate::tournaments_watcher::notifier::{TEST_MESSAGE_PREFIX, post_tournaments_update}; +use crate::{ChombotPoiseContext, ChombotPoiseUserData}; + +const FETCH_TIMEOUT: Duration = Duration::from_secs(20); + +/// Post a test TOURNAMENTS UPDATE with upcoming tournaments here. +#[poise::command( + slash_command, + guild_only, + default_member_permissions = "ADMINISTRATOR" +)] +pub async fn tournament_update_test( + ctx: ChombotPoiseContext<'_, T>, + #[description = "How many upcoming tournaments to list (default 3)"] + #[min = 1] + #[max = 20] + count: Option, +) -> Result<()> { + ctx.defer_ephemeral().await?; + let Some(tournaments) = ctx + .data() + .chombot() + .tournaments() + .get_within(FETCH_TIMEOUT) + .await + else { + ctx.say("Couldn't fetch the EMA calendar.").await?; + return Ok(()); + }; + let statuses = upcoming_as_new(&tournaments.0, count.unwrap_or(3).into()); + if statuses.0.is_empty() { + ctx.say("There are no upcoming tournaments on the EMA calendar.") + .await?; + return Ok(()); + } + + let all_reactions_added = post_tournaments_update( + ctx.serenity_context(), + ctx.data().chombot().tournament_updates(), + ctx.channel_id(), + TEST_MESSAGE_PREFIX, + &statuses, + true, + ) + .await?; + ctx.say(if all_reactions_added { + "Posted. Click a number to create that tournament's channel." + } else { + "Posted, but I couldn't add the reactions: I need the Add Reactions and Read Message \ + History permissions here." + }) + .await?; + Ok(()) +} + +fn upcoming_as_new(tournaments: &[TournamentEntry], count: usize) -> TournamentStatuses { + TournamentStatuses( + tournaments + .iter() + .filter(|entry| entry.results_status.is_empty()) + .unique_by(|entry| (&entry.name, &entry.place)) + .take(count) + .cloned() + .map(TournamentStatus::New) + .collect(), + ) +} diff --git a/chombot-common/src/tournament_reactions.rs b/chombot-common/src/tournament_reactions.rs new file mode 100644 index 0000000..5763e9c --- /dev/null +++ b/chombot-common/src/tournament_reactions.rs @@ -0,0 +1,116 @@ +use std::time::Duration; + +use anyhow::{Result, anyhow}; +use log::info; +use poise::serenity_prelude::{Context, CreateAllowedMentions, CreateMessage, Reaction, UserId}; + +use crate::ChombotPoiseUserData; +use crate::channel_creator::{ + ChannelCreation, ChannelName, TextChannelRequest, create_text_channel, decide_placement, +}; +use crate::tournament_channel::{tournament_channel_name, tournament_topic}; + +const TOURNAMENT_LOOKUP_TIMEOUT: Duration = Duration::from_secs(10); + +/// Creates a tournament's channel when its number is clicked under a +/// TOURNAMENTS UPDATE, like `/create_channel` run in the update's channel. +pub async fn handle_reaction_add( + ctx: &Context, + reaction: &Reaction, + data: &U, + bot_id: UserId, +) -> Result<()> { + let (Some(guild_id), Some(user_id)) = (reaction.guild_id, reaction.user_id) else { + return Ok(()); + }; + if user_id == bot_id { + return Ok(()); + } + let Some(posted) = data + .chombot() + .tournament_updates() + .tournament_for_reaction(reaction.message_id, &reaction.emoji) + else { + return Ok(()); + }; + + let member = match &reaction.member { + Some(member) => member.clone(), + None => guild_id.member(ctx, user_id).await?, + }; + let bot = guild_id.member(ctx, bot_id).await?; + let placement = guild_id + .to_guild_cached(ctx) + .map(|guild| { + let update_channel = guild.channels.get(&reaction.channel_id); + decide_placement(&guild, &member, &bot, None, update_channel) + }) + .ok_or_else(|| anyhow!("Guild {guild_id} is not cached"))?; + let placement = match placement { + Ok(placement) => placement, + Err(reason) => { + refuse(ctx, reaction, user_id, &reason).await; + return Ok(()); + } + }; + + let calendar = data + .chombot() + .tournaments() + .get_within(TOURNAMENT_LOOKUP_TIMEOUT) + .await; + let entry = posted.current_entry(calendar.as_ref().map_or(&[], |calendar| &calendar.0)); + let name = entry + .as_ref() + .and_then(tournament_channel_name) + .or_else(|| ChannelName::new(&posted.name)) + .ok_or_else(|| anyhow!("{:?} is not usable as a channel name", posted.name))?; + let creation = create_text_channel( + ctx, + guild_id, + TextChannelRequest { + name, + placement, + topic: entry.as_ref().map(tournament_topic), + audit_log_reason: &format!( + "Requested by {} via a TOURNAMENTS UPDATE reaction", + member.user.name + ), + }, + ) + .await?; + + let content = match creation { + ChannelCreation::Created(channel) => format!( + "<@{user_id}> created <#{}> for **{}**.", + channel.id, posted.name + ), + ChannelCreation::AlreadyExists(channel) => format!("<#{}> already exists.", channel.id), + }; + reaction + .channel_id + .send_message( + ctx, + CreateMessage::new() + .content(content) + .reference_message((reaction.channel_id, reaction.message_id)) + .allowed_mentions(CreateAllowedMentions::new()), + ) + .await?; + Ok(()) +} + +/// Removes the reaction and tells the member why in a DM, as far as Discord +/// allows (removing it needs Manage Messages; DMs may be closed). +async fn refuse(ctx: &Context, reaction: &Reaction, user_id: UserId, reason: &str) { + if let Err(err) = reaction.delete(ctx).await { + info!("Could not remove a refused tournament reaction: {err}"); + } + let dm = match user_id.create_dm_channel(ctx).await { + Ok(dm) => dm.say(ctx, reason).await.map(|_| ()), + Err(err) => Err(err), + }; + if let Err(err) = dm { + info!("Could not tell {user_id} why their tournament reaction was refused: {err}"); + } +} diff --git a/chombot-common/src/tournaments_watcher/ema.rs b/chombot-common/src/tournaments_watcher/ema.rs index 66a8c6c..751e19d 100644 --- a/chombot-common/src/tournaments_watcher/ema.rs +++ b/chombot-common/src/tournaments_watcher/ema.rs @@ -6,6 +6,7 @@ use anyhow::{anyhow, bail}; use itertools::Itertools; use reqwest::Url; use scraper::{ElementRef, Html, Selector}; +use serde::{Deserialize, Serialize}; use crate::data_watcher::WatchableData; use crate::scraping_utils::{cell_text, create_chombot_http_client, first_nonempty_text}; @@ -62,7 +63,7 @@ impl WatchableData for Tournaments { } } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TournamentEntry { pub name: String, pub url: String, @@ -96,6 +97,22 @@ pub enum TournamentStatus { } impl TournamentStatus { + #[must_use] + pub const fn new_entry(&self) -> Option<&TournamentEntry> { + match self { + Self::New(entry) => Some(entry), + Self::Changed(_) => None, + } + } + + #[must_use] + pub fn name(&self) -> &str { + match self { + Self::New(entry) => &entry.name, + Self::Changed(change) => &change.name, + } + } + #[must_use] fn for_entries( old_entry: Option<&TournamentEntry>, diff --git a/chombot-common/src/tournaments_watcher/mod.rs b/chombot-common/src/tournaments_watcher/mod.rs index 69b69ab..473699b 100644 --- a/chombot-common/src/tournaments_watcher/mod.rs +++ b/chombot-common/src/tournaments_watcher/mod.rs @@ -1,3 +1,4 @@ pub mod cache; pub mod ema; pub mod notifier; +pub mod updates; diff --git a/chombot-common/src/tournaments_watcher/notifier.rs b/chombot-common/src/tournaments_watcher/notifier.rs index b336e1f..5500786 100644 --- a/chombot-common/src/tournaments_watcher/notifier.rs +++ b/chombot-common/src/tournaments_watcher/notifier.rs @@ -5,15 +5,21 @@ use std::sync::Arc; use async_trait::async_trait; use log::error; -use poise::serenity_prelude::{ChannelId, Context}; +use poise::serenity_prelude::{Channel, ChannelId, Context, CreateMessage}; use tokio::sync::RwLock; +use crate::data::DISCORD_MESSAGE_SIZE_LIMIT; use crate::data_watcher::DataUpdateNotifier; -use crate::discord_utils::send_with_overflow; use crate::tournaments_watcher::ema::{TournamentStatus, TournamentStatuses, Tournaments}; +use crate::tournaments_watcher::updates::{ + NumberMarker, PostedTournament, PostedUpdate, TournamentUpdates, emote_numbering, + keycap_numbering, +}; const MESSAGE_PREFIX: &str = "**TOURNAMENTS UPDATE** (http://mahjong-europe.org/ranking/Calendar.html)\n\n"; +pub const TEST_MESSAGE_PREFIX: &str = + "**TOURNAMENTS UPDATE** (test; http://mahjong-europe.org/ranking/Calendar.html)\n\n"; #[async_trait] pub trait TournamentsUpdateNotifier { @@ -49,30 +55,132 @@ impl TournamentWatcherChannelListProvid pub struct TournamentsChannelMessageNotifier { channel_list_provider: T, + updates: Arc, + reactions: bool, } impl TournamentsChannelMessageNotifier { #[must_use] - pub const fn new(channel_list_provider: T) -> Self { + pub const fn new( + channel_list_provider: T, + updates: Arc, + reactions: bool, + ) -> Self { Self { channel_list_provider, + updates, + reactions, } } +} - #[must_use] - fn build_message(tournament_statuses: &TournamentStatuses) -> String { - format!("{}{}", MESSAGE_PREFIX, build_message(tournament_statuses)) +/// Returns whether all reactions could be added. +/// +/// With `reactions`, each tournament is numbered with the server's `:1m:` … +/// `:10m:` emotes (or 1️⃣ … 🔟) and gets the matching reaction, which creates +/// its channel. +pub async fn post_tournaments_update( + ctx: &Context, + updates: &TournamentUpdates, + channel_id: ChannelId, + header: &str, + statuses: &TournamentStatuses, + reactions: bool, +) -> anyhow::Result { + let numbering = if reactions { + Some(numbering_for(ctx, channel_id).await) + } else { + None + }; + + let mut all_reactions_added = true; + for message in build_messages(header, statuses, numbering.as_deref()) { + let sent = channel_id + .send_message(ctx, CreateMessage::new().content(&message.text)) + .await?; + let Some(numbering) = &numbering else { + continue; + }; + + updates.record(PostedUpdate { + message_id: sent.id, + tournaments: message + .statuses + .iter() + .map(|status| PostedTournament { + name: status.name().to_owned(), + entry: status.new_entry().cloned(), + }) + .collect(), + }); + for marker in &numbering[..message.statuses.len()] { + if let Err(why) = sent.react(ctx, marker.reaction.clone()).await { + error!("Could not add reactions to a Tournaments update: {why:?}"); + all_reactions_added = false; + break; + } + } } + + Ok(all_reactions_added) } -#[must_use] -fn build_message(tournaments: &TournamentStatuses) -> String { - let mut str = String::new(); - for diff in &tournaments.0 { - let _ = writeln!(str, "* {}", diff_as_message(diff)); +async fn numbering_for(ctx: &Context, channel_id: ChannelId) -> Vec { + let emotes = match channel_id.to_channel(ctx).await { + Ok(Channel::Guild(channel)) => channel.guild_id.emojis(ctx).await.unwrap_or_default(), + _ => Vec::new(), + }; + emote_numbering( + emotes + .iter() + .filter(|emote| emote.available) + .map(|emote| (emote.name.as_str(), emote.id, emote.animated)), + ) + .unwrap_or_else(keycap_numbering) +} + +#[derive(Default)] +struct UpdateMessage<'a> { + text: String, + statuses: Vec<&'a TournamentStatus>, +} + +/// Splits an update into messages within Discord's size limit and, when +/// numbered, with at most one tournament per number marker. +fn build_messages<'a>( + header: &str, + statuses: &'a TournamentStatuses, + numbering: Option<&[NumberMarker]>, +) -> Vec> { + let line = |status: &TournamentStatus, index: usize| { + let marker = numbering.map_or("*", |numbering| numbering[index].text.as_str()); + format!("{marker} {}\n", diff_as_message(status)) + }; + + let mut messages = Vec::new(); + let mut current = UpdateMessage { + text: header.to_owned(), + statuses: Vec::new(), + }; + for status in &statuses.0 { + if numbering.is_some_and(|numbering| current.statuses.len() == numbering.len()) { + messages.push(std::mem::take(&mut current)); + } + let mut text = line(status, current.statuses.len()); + if current.text.len() + text.len() > DISCORD_MESSAGE_SIZE_LIMIT + && !current.statuses.is_empty() + { + messages.push(std::mem::take(&mut current)); + text = line(status, 0); + } + current.text.push_str(&text); + current.statuses.push(status); + } + if !current.statuses.is_empty() { + messages.push(current); } - str + messages } #[must_use] @@ -137,8 +245,6 @@ impl DataUpdateNotifier { async fn notify(&self, diff: TournamentStatuses, ctx: &Context) { - let text = Self::build_message(&diff); - let channel_list: Vec = self .channel_list_provider .tournament_watcher_channels() @@ -146,7 +252,16 @@ impl DataUpdateNotifier 1); + assert!( + messages + .iter() + .all(|message| message.text.len() <= crate::data::DISCORD_MESSAGE_SIZE_LIMIT) ); } } diff --git a/chombot-common/src/tournaments_watcher/updates.rs b/chombot-common/src/tournaments_watcher/updates.rs new file mode 100644 index 0000000..a24ae2b --- /dev/null +++ b/chombot-common/src/tournaments_watcher/updates.rs @@ -0,0 +1,311 @@ +use std::fs; +use std::io::ErrorKind; +use std::path::PathBuf; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use itertools::Itertools; +use log::{error, warn}; +use poise::serenity_prelude::{EmojiId, MessageId, ReactionType}; +use serde::{Deserialize, Serialize}; + +use crate::tournaments_watcher::ema::TournamentEntry; + +const MAX_REMEMBERED_MESSAGES: usize = 50; +pub const MAX_NUMBERED: usize = 10; + +/// Numbers a tournament line in an update: the text the line starts with and +/// the matching reaction. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NumberMarker { + pub text: String, + pub reaction: ReactionType, +} + +fn emote_name(index: usize) -> String { + format!("{}m", index + 1) +} + +fn keycap(index: usize) -> String { + if index == 9 { + "\u{1f51f}".to_owned() + } else { + format!("{}\u{fe0f}\u{20e3}", index + 1) + } +} + +/// The server's `:1m:` … `:10m:` emotes, given as (name, ID, animated), if it +/// has all of them. +#[must_use] +pub fn emote_numbering<'a>( + emotes: impl IntoIterator, +) -> Option> { + let emotes: Vec<_> = emotes.into_iter().collect(); + (0..MAX_NUMBERED) + .map(|index| { + let name = emote_name(index); + let &(_, id, animated) = emotes.iter().find(|(candidate, ..)| *candidate == name)?; + let prefix = if animated { "a" } else { "" }; + Some(NumberMarker { + text: format!("<{prefix}:{name}:{id}>"), + reaction: ReactionType::Custom { + animated, + id, + name: Some(name), + }, + }) + }) + .collect() +} + +/// 1️⃣ … 🔟 +#[must_use] +pub fn keycap_numbering() -> Vec { + (0..MAX_NUMBERED) + .map(|index| NumberMarker { + text: keycap(index), + reaction: ReactionType::Unicode(keycap(index)), + }) + .collect() +} + +/// Which tournament a `:1m:` … `:10m:` or 1️⃣ … 🔟 reaction stands for. +#[must_use] +pub fn reaction_index(reaction: &ReactionType) -> Option { + match reaction { + ReactionType::Custom { + name: Some(name), .. + } => (0..MAX_NUMBERED).find(|&index| emote_name(index) == *name), + // Keycaps may arrive with or without the variation selector. + ReactionType::Unicode(emoji) => { + let strip = |text: &str| text.replace('\u{fe0f}', ""); + (0..MAX_NUMBERED).find(|&index| strip(&keycap(index)) == strip(emoji)) + } + _ => None, + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PostedTournament { + pub name: String, + /// Only new tournaments are posted with their full entry. + pub entry: Option, +} + +impl PostedTournament { + /// The tournament's current calendar entry, or the posted one if it's + /// gone. Tournaments can share a name, so entries are matched by place too. + #[must_use] + pub fn current_entry(&self, calendar: &[TournamentEntry]) -> Option { + let current = self.entry.as_ref().map_or_else( + || calendar.iter().find(|entry| entry.name == self.name), + |posted| { + calendar + .iter() + .find(|entry| entry.name == posted.name && entry.place == posted.place) + .or(Some(posted)) + }, + ); + current.cloned() + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PostedUpdate { + pub message_id: MessageId, + pub tournaments: Vec, +} + +/// The posted TOURNAMENTS UPDATE messages with numbered reactions, saved to a +/// file so they survive restarts. +#[derive(Debug, Default)] +pub struct TournamentUpdates { + path: Option, + updates: Mutex>, +} + +impl TournamentUpdates { + #[must_use] + pub fn load(path: impl Into) -> Self { + let path = path.into(); + let updates = match fs::read_to_string(&path) { + Ok(contents) => serde_json::from_str(&contents).unwrap_or_else(|err| { + warn!("Ignoring unreadable {}: {err}", path.display()); + Vec::new() + }), + Err(err) => { + if err.kind() != ErrorKind::NotFound { + warn!("Could not read {}: {err}", path.display()); + } + Vec::new() + } + }; + + Self { + path: Some(path), + updates: Mutex::new(updates), + } + } + + pub fn record(&self, update: PostedUpdate) { + let snapshot = { + let mut updates = self.lock(); + updates.push(update); + let excess = updates.len().saturating_sub(MAX_REMEMBERED_MESSAGES); + updates.drain(..excess); + updates.clone() + }; + + if let Some(path) = &self.path { + let result = serde_json::to_string_pretty(&snapshot) + .map_err(anyhow::Error::from) + .and_then(|contents| Ok(fs::write(path, contents)?)); + if let Err(err) = result { + error!("Could not save {}: {err}", path.display()); + } + } + } + + /// Tournament names, most recently posted first. + #[must_use] + pub fn recent_tournaments(&self) -> Vec { + self.lock() + .iter() + .rev() + .flat_map(|update| &update.tournaments) + .map(|tournament| tournament.name.clone()) + .unique() + .collect() + } + + #[must_use] + pub fn tournament_for_reaction( + &self, + message_id: MessageId, + reaction: &ReactionType, + ) -> Option { + let index = reaction_index(reaction)?; + self.lock() + .iter() + .find(|update| update.message_id == message_id)? + .tournaments + .get(index) + .cloned() + } + + fn lock(&self) -> MutexGuard<'_, Vec> { + self.updates.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +#[cfg(test)] +mod tests { + use tempfile::NamedTempFile; + + use super::*; + + fn custom(name: &str, id: u64) -> ReactionType { + ReactionType::Custom { + animated: false, + id: EmojiId::new(id), + name: Some(name.to_owned()), + } + } + + fn named(name: &str) -> PostedTournament { + PostedTournament { + name: name.to_owned(), + entry: None, + } + } + + #[test] + fn numbers_with_server_emotes_if_all_exist() { + let names: Vec = (1..=10).map(|n| format!("{n}m")).collect(); + let emotes: Vec<_> = names + .iter() + .zip(101..) + .map(|(name, id)| (name.as_str(), EmojiId::new(id), name == "3m")) + .collect(); + + let numbering = emote_numbering(emotes.iter().copied()).unwrap(); + assert_eq!(numbering[0].text, "<:1m:101>"); + assert_eq!(numbering[0].reaction, custom("1m", 101)); + assert_eq!(numbering[2].text, ""); + assert_eq!(numbering[9].text, "<:10m:110>"); + + assert_eq!(emote_numbering(emotes[..9].iter().copied()), None); + } + + #[test] + fn recognizes_numbered_reactions() { + assert_eq!(reaction_index(&custom("1m", 101)), Some(0)); + assert_eq!(reaction_index(&custom("10m", 110)), Some(9)); + assert_eq!(reaction_index(&custom("11m", 111)), None); + assert_eq!(reaction_index(&custom("1p", 6)), None); + let unicode = |emoji: &str| reaction_index(&ReactionType::Unicode(emoji.to_owned())); + assert_eq!(unicode("1\u{fe0f}\u{20e3}"), Some(0)); + assert_eq!(unicode("1\u{20e3}"), Some(0)); + assert_eq!(unicode("\u{1f51f}"), Some(9)); + assert_eq!(unicode("👍"), None); + } + + #[test] + fn remembers_posted_updates_across_restarts() { + let path = NamedTempFile::new().unwrap().into_temp_path(); + { + let updates = TournamentUpdates::load(path.to_path_buf()); + updates.record(PostedUpdate { + message_id: MessageId::new(10), + tournaments: vec![named("Old Cup"), named("Shared Cup")], + }); + updates.record(PostedUpdate { + message_id: MessageId::new(20), + tournaments: vec![named("New Cup"), named("Shared Cup")], + }); + } + + let updates = TournamentUpdates::load(path.to_path_buf()); + assert_eq!( + updates.recent_tournaments(), + vec!["New Cup", "Shared Cup", "Old Cup"] + ); + assert_eq!( + updates.tournament_for_reaction(MessageId::new(10), &custom("2m", 102)), + Some(named("Shared Cup")) + ); + assert_eq!( + updates.tournament_for_reaction(MessageId::new(10), &custom("3m", 103)), + None + ); + assert_eq!( + updates.tournament_for_reaction(MessageId::new(30), &custom("1m", 101)), + None + ); + } + + #[test] + fn picks_the_posted_tournament_among_namesakes() { + let entry = |place: &str| TournamentEntry { + name: "Pumpkin Tiles 2026".to_owned(), + url: String::new(), + rules: "Riichi".to_owned(), + date: "31 October 2026".to_owned(), + place: place.to_owned(), + approval_status: "OK".to_owned(), + registration_start: String::new(), + results_status: String::new(), + }; + let calendar = [entry("Tbilisi"), entry("Yerevan")]; + let posted = PostedTournament { + name: "Pumpkin Tiles 2026".to_owned(), + entry: Some(entry("Yerevan")), + }; + + assert_eq!(posted.current_entry(&calendar), Some(entry("Yerevan"))); + assert_eq!(posted.current_entry(&[]), Some(entry("Yerevan"))); + assert_eq!( + named("Pumpkin Tiles 2026").current_entry(&calendar), + Some(entry("Tbilisi")) + ); + } +} diff --git a/chombot-kcc/src/main.rs b/chombot-kcc/src/main.rs index 6e06ecd..22b4851 100644 --- a/chombot-kcc/src/main.rs +++ b/chombot-kcc/src/main.rs @@ -7,11 +7,16 @@ extern crate core; +use std::sync::Arc; + use anyhow::Error; use chombot_common::chombot::ChombotBase; use chombot_common::slash_commands::create_channel::create_channel; use chombot_common::slash_commands::hand::hand; use chombot_common::slash_commands::score::score; +use chombot_common::slash_commands::tournament_update_test::tournament_update_test; +use chombot_common::tournament_reactions::handle_reaction_add; +use chombot_common::tournaments_watcher::updates::TournamentUpdates; use chombot_common::{ChombotPoiseUserData, start_tournaments_watcher}; use clap::Parser; use log::{LevelFilter, error, info}; @@ -32,6 +37,7 @@ mod kcc3; mod slash_commands; const AT_EVERYONE_REACTIONS: [&str; 2] = ["Ichiangry", "Mikiknife"]; +const TOURNAMENT_UPDATES_PATH: &str = "tournament_updates.json"; pub struct PoiseUserData { pub chombot: ChombotBase, @@ -65,6 +71,14 @@ fn event_handler<'a>( framework_ctx: FrameworkContext<'a, PoiseUserData, Error>, event: &'a FullEvent, ) -> BoxFuture<'a, anyhow::Result<()>> { + if let FullEvent::ReactionAdd { add_reaction } = event { + return Box::pin(handle_reaction_add( + framework_ctx.serenity_context, + add_reaction, + framework_ctx.user_data, + framework_ctx.bot_id(), + )); + } if let FullEvent::Message { new_message } = event { let ctx = framework_ctx.serenity_context; return Box::pin(async move { @@ -106,6 +120,7 @@ fn get_command_list(args: &Arguments) -> Vec> { } if args.feature_create_channel { ret.push(create_channel()); + ret.push(tournament_update_test()); } ret @@ -119,7 +134,8 @@ async fn main() { let args = Arguments::parse(); let kcc3_client = get_kcc3_client(&args).unwrap(); - let chombot = ChombotBase::new(); + let tournament_updates = Arc::new(TournamentUpdates::load(TOURNAMENT_UPDATES_PATH)); + let chombot = ChombotBase::new(tournament_updates.clone()); let kcc_chombot = Chombot::new(kcc3_client); let framework = Framework::builder() @@ -137,6 +153,8 @@ async fn main() { )); start_tournaments_watcher( tournaments_watcher_channel_id, + tournament_updates, + args.feature_create_channel, ctx.clone(), chombot.tournaments().clone(), ); diff --git a/chombot/src/main.rs b/chombot/src/main.rs index 7a28594..beb0060 100644 --- a/chombot/src/main.rs +++ b/chombot/src/main.rs @@ -12,11 +12,14 @@ use chombot_common::chombot::ChombotBase; use chombot_common::slash_commands::create_channel::create_channel; use chombot_common::slash_commands::hand::hand; use chombot_common::slash_commands::score::score; +use chombot_common::slash_commands::tournament_update_test::tournament_update_test; +use chombot_common::tournament_reactions::handle_reaction_add; +use chombot_common::tournaments_watcher::updates::TournamentUpdates; use chombot_common::{ChombotPoiseUserData, start_tournaments_watcher}; use clap::Parser; use log::{LevelFilter, error, info}; -use poise::serenity_prelude::{ClientBuilder, GatewayIntents}; -use poise::{Command, Context, Framework, FrameworkOptions}; +use poise::serenity_prelude::{ClientBuilder, FullEvent, GatewayIntents}; +use poise::{BoxFuture, Command, Context, Framework, FrameworkContext, FrameworkOptions}; use tokio::sync::RwLock; use crate::args::Arguments; @@ -41,10 +44,35 @@ impl ChombotPoiseUserData for PoiseUserData { pub type PoiseContext<'a> = Context<'a, PoiseUserData, anyhow::Error>; fn get_command_list() -> Vec> { - vec![hand(), score(), tournament_watcher(), create_channel()] + vec![ + hand(), + score(), + tournament_watcher(), + create_channel(), + tournament_update_test(), + ] } const CONFIG_DATA_PATH: &str = "data.toml"; +const TOURNAMENT_UPDATES_PATH: &str = "tournament_updates.json"; + +fn event_handler<'a>( + framework_ctx: FrameworkContext<'a, PoiseUserData, Error>, + event: &'a FullEvent, +) -> BoxFuture<'a, anyhow::Result<()>> { + Box::pin(async move { + if let FullEvent::ReactionAdd { add_reaction } = event { + handle_reaction_add( + framework_ctx.serenity_context, + add_reaction, + framework_ctx.user_data, + framework_ctx.bot_id(), + ) + .await?; + } + Ok(()) + }) +} #[tokio::main] async fn main() { @@ -53,19 +81,23 @@ async fn main() { .init(); let args = Arguments::parse(); - let chombot = ChombotBase::new(); + let tournament_updates = Arc::new(TournamentUpdates::load(TOURNAMENT_UPDATES_PATH)); + let chombot = ChombotBase::new(tournament_updates.clone()); let config = ChombotConfig::load(CONFIG_DATA_PATH.into()).expect("Could not load config"); let config_ref = Arc::new(RwLock::new(config)); let framework = Framework::builder() .options(FrameworkOptions { commands: get_command_list(), + event_handler, ..Default::default() }) .setup(move |ctx, ready, framework| { Box::pin(async move { start_tournaments_watcher( config_ref.clone(), + tournament_updates, + true, ctx.clone(), chombot.tournaments().clone(), );