Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 Cargo.lock

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

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ 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.
`/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://...`.

### 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
1 change: 1 addition & 0 deletions chombot-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ poise.workspace = true
reqwest.workspace = true
riichi_hand.workspace = true
scraper.workspace = true
slug.workspace = true
tokio.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 @@ -9,6 +9,8 @@ use riichi_hand::raster_renderer::fluffy_stuff_tile_sets::{
use riichi_hand::raster_renderer::martin_persson_tile_sets::MARTIN_PERSSON_TILE_SET;
use riichi_hand::raster_renderer::{HandRenderError, RasterRenderer, RenderOptions, TileSet};

use crate::tournaments_watcher::cache::TournamentsCache;

#[derive(Debug)]
pub enum ChombotBaseError {
HandParserError(HandParseError),
Expand Down Expand Up @@ -55,12 +57,21 @@ pub enum TileStyle {
}

#[derive(Default)]
pub struct ChombotBase {}
pub struct ChombotBase {
tournaments: TournamentsCache,
}

impl ChombotBase {
#[must_use]
pub const fn new() -> Self {
Self {}
Self {
tournaments: TournamentsCache::new(),
}
}

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

pub fn render_hand(hand: &str, tile_style: &TileStyle) -> ChombotResult<RgbaImage> {
Expand Down
1 change: 1 addition & 0 deletions chombot-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub mod data_watcher;
pub mod discord_utils;
pub mod scraping_utils;
pub mod slash_commands;
pub mod tournament_channel;
pub mod tournaments_watcher;

pub trait ChombotPoiseUserData: Sync {
Expand Down
198 changes: 189 additions & 9 deletions chombot-common/src/slash_commands/create_channel.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,46 @@
use std::time::Duration;

use anyhow::{Result, anyhow};
use itertools::Itertools;
use poise::CreateReply;
use poise::serenity_prelude::{ChannelId, GuildId};
use poise::serenity_prelude::{AutocompleteChoice, ChannelId, CreateAutocompleteResponse, GuildId};

use crate::channel_creator::{
ChannelCreation, ChannelName, Placement, TextChannelRequest, create_text_channel,
decide_placement,
CHANNEL_NAME_MAX_LENGTH, ChannelCreation, ChannelName, Placement, TextChannelRequest,
create_text_channel, decide_placement, truncate_chars,
};
use crate::tournament_channel::{
polish_city, polish_date, tournament_channel_name, tournament_topic,
};
use crate::tournaments_watcher::ema::{TournamentEntry, Tournaments};
use crate::{ChombotPoiseContext, ChombotPoiseUserData};

/// Create a text channel.
const AUTOCOMPLETE_MAX_CHOICES: usize = 25;
/// Discord waits 3 seconds for autocomplete suggestions.
const AUTOCOMPLETE_TIMEOUT: Duration = Duration::from_millis(2500);
const TOURNAMENT_LOOKUP_TIMEOUT: Duration = Duration::from_secs(10);

/// Create a text channel, e.g. for an upcoming EMA tournament.
#[poise::command(
slash_command,
guild_only,
default_member_permissions = "MANAGE_CHANNELS"
)]
pub async fn create_channel<T: ChombotPoiseUserData>(
ctx: ChombotPoiseContext<'_, T>,
#[description = "Channel name"]
#[description = "Channel name; start typing to pick an EMA tournament"]
#[autocomplete = "autocomplete_tournament"]
#[max_length = 100]
name: String,
#[description = "Category to create the channel in (default: this channel's category)"]
#[channel_types("Category")]
category: Option<ChannelId>,
#[description = "Channel topic"]
#[description = "Channel topic (defaults to the tournament's place, date and website)"]
#[max_length = 1024]
topic: Option<String>,
) -> Result<()> {
let guild_id = ctx.guild_id().ok_or_else(|| anyhow!("Guild ID is None"))?;
let Some(name) = ChannelName::new(&name) else {
let Some(plain_name) = ChannelName::new(&name) else {
ctx.send(
CreateReply::default()
.content("That name doesn't contain any characters usable in a channel name.")
Expand All @@ -46,13 +59,23 @@ pub async fn create_channel<T: ChombotPoiseUserData>(
};

ctx.defer().await?;
let tournament = ctx
.data()
.chombot()
.tournaments()
.get_within(TOURNAMENT_LOOKUP_TIMEOUT)
.await
.and_then(|tournaments| find_tournament(&tournaments, &name, &plain_name).cloned());
let creation = create_text_channel(
ctx.serenity_context(),
guild_id,
TextChannelRequest {
name,
name: tournament
.as_ref()
.and_then(tournament_channel_name)
.unwrap_or(plain_name),
placement,
topic,
topic: topic.or_else(|| tournament.as_ref().map(tournament_topic)),
audit_log_reason: &format!("Requested by {} via /create_channel", ctx.author().name),
},
)
Expand Down Expand Up @@ -89,3 +112,160 @@ async fn placement<T: ChombotPoiseUserData>(
.map(|guild| decide_placement(&guild, &author, &bot, requested, current_channel.as_ref()));
placement.ok_or_else(|| anyhow!("Guild {guild_id} is not cached"))
}

async fn autocomplete_tournament<T: ChombotPoiseUserData>(
ctx: ChombotPoiseContext<'_, T>,
partial: &str,
) -> CreateAutocompleteResponse {
let Some(tournaments) = ctx
.data()
.chombot()
.tournaments()
.get_within(AUTOCOMPLETE_TIMEOUT)
.await
else {
return CreateAutocompleteResponse::new();
};

let choices = matching_tournaments(&tournaments, partial)
.into_iter()
.map(|entry| {
let label = choice_label(entry);
AutocompleteChoice::new(label.clone(), label)
})
.collect();
CreateAutocompleteResponse::new().set_choices(choices)
}

/// Upcoming tournaments first, then the rest.
fn matching_tournaments<'a>(
tournaments: &'a Tournaments,
partial: &str,
) -> Vec<&'a TournamentEntry> {
let partial = partial.trim().to_lowercase();
let mut matching: Vec<&TournamentEntry> = tournaments
.0
.iter()
.filter(|entry| {
entry.name.to_lowercase().contains(&partial)
|| entry.place.to_lowercase().contains(&partial)
})
.unique_by(|entry| (&entry.name, &entry.place, &entry.date))
.collect();
matching.sort_by_key(|entry| !entry.results_status.is_empty());
matching.truncate(AUTOCOMPLETE_MAX_CHOICES);
matching
}

/// E.g. `Hatsumi Taikai 2026 (14-15 lutego 2026, Kraków)`. Picking a
/// suggestion submits its label, which tells namesakes apart.
fn choice_label(entry: &TournamentEntry) -> String {
let details = [polish_date(&entry.date), polish_city(&entry.place)]
.into_iter()
.filter(|detail| !detail.is_empty())
.join(", ");
let label = if details.is_empty() {
entry.name.clone()
} else {
format!("{} ({details})", entry.name)
};
truncate_chars(&label, CHANNEL_NAME_MAX_LENGTH)
}

/// The tournament with the label `name`, or else named `name`, preferring
/// one without results yet.
fn find_tournament<'a>(
tournaments: &'a Tournaments,
name: &str,
channel_name: &ChannelName,
) -> Option<&'a TournamentEntry> {
let by_label = tournaments
.0
.iter()
.find(|entry| choice_label(entry) == name.trim());
let mut by_name = tournaments
.0
.iter()
.filter(|entry| ChannelName::new(&entry.name).as_ref() == Some(channel_name));

by_label.or_else(|| {
by_name
.clone()
.find(|entry| entry.results_status.is_empty())
.or_else(|| by_name.next())
})
}

#[cfg(test)]
mod tests {
use super::*;

fn entry(name: &str, date: &str, place: &str, results: &str) -> TournamentEntry {
TournamentEntry {
name: name.to_owned(),
url: String::new(),
rules: "Riichi".to_owned(),
date: date.to_owned(),
place: place.to_owned(),
approval_status: "OK".to_owned(),
registration_start: String::new(),
results_status: results.to_owned(),
}
}

fn calendar() -> Tournaments {
Tournaments(vec![
entry(
"Pumpkin Tiles 2026",
"10-11 October 2026",
"Tbilisi",
"EMA waiting for results !",
),
entry("Pumpkin Tiles 2026", "31 October 2026", "Yerevan", ""),
entry("Warsaw Riichi Cup", "5 December 2026", "Warsaw", ""),
entry("Warsaw Riichi Cup", "5 December 2026", "Warsaw", ""),
entry("Hatsumi Taikai 2027", "13-14 February 2027", "Krakow", ""),
])
}

#[test]
fn suggests_upcoming_tournaments_first() {
let calendar = calendar();
let suggest = |partial: &str| -> Vec<String> {
matching_tournaments(&calendar, partial)
.into_iter()
.map(choice_label)
.collect()
};

assert_eq!(
suggest(""),
vec![
"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"),
vec!["Warsaw Riichi Cup (5 grudnia 2026, Warszawa)"]
);
}

#[test]
fn finds_picked_or_typed_tournament() {
let calendar = calendar();
let find = |name: &str| {
find_tournament(&calendar, name, &ChannelName::new(name).unwrap())
.map(|entry| entry.place.as_str())
};

assert_eq!(
find("Pumpkin Tiles 2026 (10-11 października 2026, Tbilisi)"),
Some("Tbilisi")
);
assert_eq!(find("pumpkin tiles 2026"), Some("Yerevan"));
assert_eq!(find("Something else"), None);
}
}
Loading
Loading