Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/target
/chombot/data.toml
tournament_updates.json
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions chombot-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
15 changes: 13 additions & 2 deletions chombot-common/src/chombot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -60,19 +61,29 @@ pub enum TileStyle {
#[derive(Default)]
pub struct ChombotBase {
tournaments: Arc<TournamentsCache>,
tournament_updates: Arc<TournamentUpdates>,
}

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<TournamentUpdates>) -> Self {
Self {
tournaments: Arc::default(),
tournament_updates,
}
}

#[must_use]
pub const fn tournaments(&self) -> &Arc<TournamentsCache> {
&self.tournaments
}

#[must_use]
pub fn tournament_updates(&self) -> &TournamentUpdates {
&self.tournament_updates
}

pub fn render_hand(hand: &str, tile_style: &TileStyle) -> ChombotResult<RgbaImage> {
let tile_set: Box<dyn TileSet> = match tile_style {
TileStyle::Yellow => Box::new(&*YELLOW_FLUFFY_STUFF_TILE_SET),
Expand Down
9 changes: 8 additions & 1 deletion chombot-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand All @@ -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<T: TournamentWatcherChannelListProvider + 'static>(
channel_list_provider: T,
updates: Arc<TournamentUpdates>,
reactions: bool,
ctx: SerenityContext,
tournaments: Arc<TournamentsCache>,
) {
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
Expand Down
32 changes: 23 additions & 9 deletions chombot-common/src/slash_commands/create_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,12 @@ async fn autocomplete_tournament<T: ChombotPoiseUserData>(
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);
Expand All @@ -137,9 +142,11 @@ async fn autocomplete_tournament<T: ChombotPoiseUserData>(
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();
Expand All @@ -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
}
Expand Down Expand Up @@ -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<String> {
matching_tournaments(&calendar, partial)
let suggest = |recent: &[&str], partial: &str| -> Vec<String> {
let recent: Vec<String> = 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)"]
);
}
Expand Down
1 change: 1 addition & 0 deletions chombot-common/src/slash_commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod create_channel;
pub mod hand;
pub mod score;
pub mod tournament_update_test;
73 changes: 73 additions & 0 deletions chombot-common/src/slash_commands/tournament_update_test.rs
Original file line number Diff line number Diff line change
@@ -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<T: ChombotPoiseUserData>(
ctx: ChombotPoiseContext<'_, T>,
#[description = "How many upcoming tournaments to list (default 3)"]
#[min = 1]
#[max = 20]
count: Option<u8>,
) -> 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(),
)
}
116 changes: 116 additions & 0 deletions chombot-common/src/tournament_reactions.rs
Original file line number Diff line number Diff line change
@@ -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<U: ChombotPoiseUserData>(
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}");
}
}
Loading
Loading