diff --git a/README.md b/README.md index 0234f91..f59f085 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,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. + ### 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. @@ -42,6 +45,7 @@ Chombot-kcc requires more config values defined as environment variables. Those * `KCC3_URL` - the URL of the [kcc3 instance](https://github.com/riichi/kcc3) that you want to use with Chombot. The official instance is `https://fanpai.chombo.club`. * `KCC3_TOKEN` - the API token for kcc3 that can be obtained via kcc3 admin page. * `FEATURE_PASTA` - `true` if you want to enable the `/pasta` command (extremely hermetic!). +* `FEATURE_CREATE_CHANNEL` - `true` if you want to enable [`/create_channel`](#creating-channels). Example: @@ -57,6 +61,7 @@ export FEATURE_CHOMBOHALL_REMINDER=true export CHOMBOHALL_REMINDER_CHANNEL_ID=54321 export CHOMBOHALL_REMINDER_MESSAGE="Reminder: chombohall tomorrow at 20:00!" export FEATURE_PASTA=true +export FEATURE_CREATE_CHANNEL=true cargo run --bin chombot-kcc --release ``` diff --git a/chombot-common/src/channel_creator.rs b/chombot-common/src/channel_creator.rs new file mode 100644 index 0000000..e912822 --- /dev/null +++ b/chombot-common/src/channel_creator.rs @@ -0,0 +1,334 @@ +use anyhow::Result; +use poise::serenity_prelude::{ + CacheHttp, ChannelId, ChannelType, CreateChannel, Guild, GuildChannel, GuildId, Member, +}; + +pub const CHANNEL_NAME_MAX_LENGTH: usize = 100; +const CHANNEL_TOPIC_MAX_LENGTH: usize = 1024; + +/// A text channel name normalized the way Discord does it, so that existing +/// channels can be found by name. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ChannelName(String); + +impl ChannelName { + #[must_use] + pub fn new(raw: &str) -> Option { + let mut name = String::with_capacity(raw.len()); + let mut pending_separator = false; + for c in raw.chars() { + if is_separator(c) { + pending_separator = true; + } else if !is_dropped(c) { + if pending_separator && !name.is_empty() { + name.push('-'); + } + pending_separator = false; + name.extend(c.to_lowercase()); + } + } + + let name = truncate_chars(&name, CHANNEL_NAME_MAX_LENGTH); + let name = name.trim_end_matches('-'); + (!name.is_empty()).then(|| Self(name.to_owned())) + } + + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// Whitespace, punctuation and en/em dash (`–`, `—`) characters: become `-`. +const fn is_separator(c: char) -> bool { + c.is_whitespace() + || matches!(c, '-' | '\u{2013}' | '\u{2014}') + || (c.is_ascii_punctuation() && c != '_' && !is_dropped(c)) +} + +/// Control and quote (including `‘`, `’`, `“`, `”`) characters: removed. +const fn is_dropped(c: char) -> bool { + c.is_control() + || matches!( + c, + '\'' | '"' | '`' | '\u{2018}' | '\u{2019}' | '\u{201C}' | '\u{201D}' + ) +} + +pub struct TextChannelRequest<'a> { + pub name: ChannelName, + pub placement: Placement, + pub topic: Option, + pub audit_log_reason: &'a str, +} + +pub enum ChannelCreation { + Created(GuildChannel), + AlreadyExists(GuildChannel), +} + +/// Creates a text channel, unless one with the same name already exists in +/// the same category. +pub async fn create_text_channel( + cache_http: impl CacheHttp, + guild_id: GuildId, + request: TextChannelRequest<'_>, +) -> Result { + let category = match request.placement { + Placement::InCategory(category) => Some(category), + Placement::OutsideAnyCategory => None, + }; + let channels = guild_id.channels(cache_http.http()).await?; + if let Some(existing) = find_text_channel(channels.values(), &request.name, category) { + return Ok(ChannelCreation::AlreadyExists(existing.clone())); + } + + let mut builder = CreateChannel::new(request.name.as_str()) + .kind(ChannelType::Text) + .audit_log_reason(request.audit_log_reason); + if let Some(category) = category { + builder = builder.category(category); + } + if let Some(topic) = request.topic { + builder = builder.topic(truncate_chars(&topic, CHANNEL_TOPIC_MAX_LENGTH)); + } + + let channel = guild_id.create_channel(cache_http, builder).await?; + Ok(ChannelCreation::Created(channel)) +} + +fn find_text_channel<'a>( + channels: impl IntoIterator, + name: &ChannelName, + category: Option, +) -> Option<&'a GuildChannel> { + channels.into_iter().find(|channel| { + matches!(channel.kind, ChannelType::Text | ChannelType::News) + && channel.parent_id == category + && channel.name == name.as_str() + }) +} + +/// The category of `channel`, or of its parent channel if it's a thread. +fn default_category(guild: &Guild, channel: &GuildChannel) -> Option { + if matches!( + channel.kind, + ChannelType::PublicThread | ChannelType::PrivateThread | ChannelType::NewsThread + ) { + guild.channels.get(&channel.parent_id?)?.parent_id + } else { + channel.parent_id + } +} + +fn can_create_channels_in(guild: &Guild, member: &Member, category: Option<&GuildChannel>) -> bool { + category + .map_or_else( + || guild.member_permissions(member), + |category| guild.user_permissions_in(category, member), + ) + .manage_channels() +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Placement { + InCategory(ChannelId), + OutsideAnyCategory, +} + +/// Where to create a new channel. +/// +/// That's `requested`, or else the category of `current_channel`, if both the +/// member and the bot could create a channel there; otherwise an error +/// explaining to the member why not. +pub fn decide_placement( + guild: &Guild, + author: &Member, + bot: &Member, + requested: Option, + current_channel: Option<&GuildChannel>, +) -> Result { + let category_id = + requested.or_else(|| current_channel.and_then(|channel| default_category(guild, channel))); + let category = match category_id.map(|id| guild.channels.get(&id)) { + Some(None) => return Err("I couldn't find that category.".to_owned()), + Some(category) => category, + None => None, + }; + let place = category.map_or_else( + || "outside a category".to_owned(), + |category| format!("in the **{}** category", category.name), + ); + + if !can_create_channels_in(guild, author, category) { + Err(format!( + "You don't have permission to create channels {place}, so I can't do it for you." + )) + } else if !can_create_channels_in(guild, bot, category) { + Err(format!( + "I don't have the Manage Channels permission {place}." + )) + } else { + Ok(category_id.map_or(Placement::OutsideAnyCategory, Placement::InCategory)) + } +} + +#[must_use] +pub fn truncate_chars(text: &str, max_chars: usize) -> String { + text.chars().take(max_chars).collect() +} + +#[cfg(test)] +mod tests { + use poise::serenity_prelude::{ + PermissionOverwrite, PermissionOverwriteType, Permissions, Role, RoleId, UserId, + }; + + use super::*; + + fn name(raw: &str) -> Option { + ChannelName::new(raw).map(|name| name.0) + } + + #[test] + fn normalizes_names() { + assert_eq!( + name("Kraków Riichi Open 2026").as_deref(), + Some("kraków-riichi-open-2026") + ); + assert_eq!( + name("ERMC 2026 (Copenhagen) / Tom's -- Cup").as_deref(), + Some("ermc-2026-copenhagen-toms-cup") + ); + assert_eq!(name("🀄 ŁÓDŹ_CUP").as_deref(), Some("🀄-łódź_cup")); + assert_eq!(name("!!! ''"), None); + + let long = name(&format!("{} tail", "a".repeat(99))).unwrap(); + assert_eq!(long, "a".repeat(99)); + } + + fn channel(id: u64, kind: ChannelType, parent: Option) -> GuildChannel { + let mut channel = GuildChannel::default(); + channel.id = ChannelId::new(id); + channel.kind = kind; + channel.name = format!("channel-{id}"); + channel.parent_id = parent.map(ChannelId::new); + channel + } + + #[test] + fn finds_existing_channel_in_same_category_only() { + let channels = [ + channel(1, ChannelType::Text, Some(100)), + channel(2, ChannelType::Voice, None), + ]; + let find = |raw: &str, category: Option| { + find_text_channel( + &channels, + &ChannelName::new(raw).unwrap(), + category.map(ChannelId::new), + ) + .map(|channel| channel.id.get()) + }; + + assert_eq!(find("Channel 1", Some(100)), Some(1)); + assert_eq!(find("channel-1", None), None); + assert_eq!(find("channel-2", None), None); + } + + const ORGANIZERS: u64 = 2000; + const TOURNAMENTS: u64 = 100; + const MODS: u64 = 200; + + /// Organizers may manage channels only in the tournaments category. + fn guild() -> Guild { + let mut tournaments = channel(TOURNAMENTS, ChannelType::Category, None); + tournaments.name = "Turnieje".to_owned(); + tournaments.permission_overwrites = vec![PermissionOverwrite { + allow: Permissions::MANAGE_CHANNELS, + deny: Permissions::empty(), + kind: PermissionOverwriteType::Role(RoleId::new(ORGANIZERS)), + }]; + + let mut guild = Guild::default(); + guild.id = GuildId::new(1); + guild.owner_id = UserId::new(999); + guild.roles = [1, ORGANIZERS] + .map(|id| { + let mut role = Role::default(); + role.id = RoleId::new(id); + (role.id, role) + }) + .into(); + guild.channels = [ + tournaments, + channel(MODS, ChannelType::Category, None), + channel(10, ChannelType::Text, Some(TOURNAMENTS)), + channel(11, ChannelType::Text, None), + ] + .map(|channel| (channel.id, channel)) + .into(); + guild + } + + fn member(user_id: u64, roles: &[u64]) -> Member { + let mut member = Member::default(); + member.user.id = UserId::new(user_id); + member.roles = roles.iter().copied().map(RoleId::new).collect(); + member + } + + #[test] + fn places_channel_where_member_and_bot_may_create_it() { + let guild = guild(); + let general = &guild.channels[&ChannelId::new(10)]; + let lobby = &guild.channels[&ChannelId::new(11)]; + let thread = channel(12, ChannelType::PublicThread, Some(10)); + let organizer = member(5, &[ORGANIZERS]); + let bot = member(6, &[ORGANIZERS]); + let owner = member(999, &[]); + let tournaments = Placement::InCategory(ChannelId::new(TOURNAMENTS)); + let place = + |author: &Member, bot: &Member, requested: Option, current: &GuildChannel| { + decide_placement( + &guild, + author, + bot, + requested.map(ChannelId::new), + Some(current), + ) + }; + + assert_eq!(place(&organizer, &bot, None, general), Ok(tournaments)); + assert_eq!(place(&organizer, &bot, None, &thread), Ok(tournaments)); + assert_eq!( + place(&organizer, &bot, Some(TOURNAMENTS), lobby), + Ok(tournaments) + ); + assert_eq!( + place(&organizer, &bot, None, lobby), + Err( + "You don't have permission to create channels outside a category, so I can't do \ + it for you." + .to_owned() + ) + ); + assert_eq!( + place(&owner, &owner, None, lobby), + Ok(Placement::OutsideAnyCategory) + ); + assert!(place(&organizer, &bot, Some(MODS), general).is_err()); + assert!(place(&member(7, &[]), &bot, None, general).is_err()); + assert_eq!( + place(&organizer, &member(8, &[]), None, general), + Err( + "I don't have the Manage Channels permission in the **Turnieje** category." + .to_owned() + ) + ); + assert_eq!( + place(&organizer, &bot, Some(999), general), + Err("I couldn't find that category.".to_owned()) + ); + } +} diff --git a/chombot-common/src/lib.rs b/chombot-common/src/lib.rs index 5bbf0ee..c436ed2 100644 --- a/chombot-common/src/lib.rs +++ b/chombot-common/src/lib.rs @@ -15,6 +15,7 @@ use crate::tournaments_watcher::notifier::{ TournamentWatcherChannelListProvider, TournamentsChannelMessageNotifier, }; +pub mod channel_creator; pub mod chombot; pub mod data; pub mod data_watcher; diff --git a/chombot-common/src/slash_commands/create_channel.rs b/chombot-common/src/slash_commands/create_channel.rs new file mode 100644 index 0000000..d56abb0 --- /dev/null +++ b/chombot-common/src/slash_commands/create_channel.rs @@ -0,0 +1,91 @@ +use anyhow::{Result, anyhow}; +use poise::CreateReply; +use poise::serenity_prelude::{ChannelId, GuildId}; + +use crate::channel_creator::{ + ChannelCreation, ChannelName, Placement, TextChannelRequest, create_text_channel, + decide_placement, +}; +use crate::{ChombotPoiseContext, ChombotPoiseUserData}; + +/// Create a text channel. +#[poise::command( + slash_command, + guild_only, + default_member_permissions = "MANAGE_CHANNELS" +)] +pub async fn create_channel( + ctx: ChombotPoiseContext<'_, T>, + #[description = "Channel name"] + #[max_length = 100] + name: String, + #[description = "Category to create the channel in (default: this channel's category)"] + #[channel_types("Category")] + category: Option, + #[description = "Channel topic"] + #[max_length = 1024] + topic: Option, +) -> Result<()> { + let guild_id = ctx.guild_id().ok_or_else(|| anyhow!("Guild ID is None"))?; + let Some(name) = ChannelName::new(&name) else { + ctx.send( + CreateReply::default() + .content("That name doesn't contain any characters usable in a channel name.") + .ephemeral(true), + ) + .await?; + return Ok(()); + }; + let placement = match placement(ctx, guild_id, category).await? { + Ok(placement) => placement, + Err(reason) => { + ctx.send(CreateReply::default().content(reason).ephemeral(true)) + .await?; + return Ok(()); + } + }; + + ctx.defer().await?; + let creation = create_text_channel( + ctx.serenity_context(), + guild_id, + TextChannelRequest { + name, + placement, + topic, + audit_log_reason: &format!("Requested by {} via /create_channel", ctx.author().name), + }, + ) + .await?; + + let reply = match creation { + ChannelCreation::Created(channel) => format!("Created <#{}>.", channel.id), + ChannelCreation::AlreadyExists(channel) => format!("<#{}> already exists.", channel.id), + }; + ctx.say(reply).await?; + Ok(()) +} + +async fn placement( + ctx: ChombotPoiseContext<'_, T>, + guild_id: GuildId, + requested: Option, +) -> Result> { + let author = ctx + .author_member() + .await + .ok_or_else(|| anyhow!("Could not get the invoking member"))? + .into_owned(); + let bot = guild_id + .member(ctx.serenity_context(), ctx.framework().bot_id()) + .await?; + let current_channel = match requested { + Some(_) => None, + None => ctx.guild_channel().await, + }; + + let placement = ctx + .guild() + .map(|guild| decide_placement(&guild, &author, &bot, requested, current_channel.as_ref())); + placement.ok_or_else(|| anyhow!("Guild {guild_id} is not cached")) +} diff --git a/chombot-common/src/slash_commands/mod.rs b/chombot-common/src/slash_commands/mod.rs index 0a2b525..cc90774 100644 --- a/chombot-common/src/slash_commands/mod.rs +++ b/chombot-common/src/slash_commands/mod.rs @@ -1,2 +1,3 @@ +pub mod create_channel; pub mod hand; pub mod score; diff --git a/chombot-kcc/.env.example b/chombot-kcc/.env.example index a7283e9..16e556d 100644 --- a/chombot-kcc/.env.example +++ b/chombot-kcc/.env.example @@ -9,3 +9,4 @@ FEATURE_KCC3=true KCC3_URL=https://fanpai.chombo.club KCC3_TOKEN= FEATURE_PASTA=true +FEATURE_CREATE_CHANNEL=false diff --git a/chombot-kcc/src/args.rs b/chombot-kcc/src/args.rs index 19f097a..7af4cc2 100644 --- a/chombot-kcc/src/args.rs +++ b/chombot-kcc/src/args.rs @@ -46,4 +46,8 @@ pub struct Arguments { /// Enable fancy text generator slash command #[arg(long, env, default_value_t = true)] pub feature_fancy_text: bool, + + /// Enable the `/create_channel` command + #[arg(long, env, default_value_t = false)] + pub feature_create_channel: bool, } diff --git a/chombot-kcc/src/main.rs b/chombot-kcc/src/main.rs index 68b71a5..35b68d0 100644 --- a/chombot-kcc/src/main.rs +++ b/chombot-kcc/src/main.rs @@ -9,6 +9,7 @@ extern crate core; 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::{ChombotPoiseUserData, start_tournaments_watcher}; @@ -103,6 +104,9 @@ fn get_command_list(args: &Arguments) -> Vec> { if args.feature_fancy_text { ret.push(slash_commands::fancy_text::fancy_text()); } + if args.feature_create_channel { + ret.push(create_channel()); + } ret } diff --git a/chombot/src/main.rs b/chombot/src/main.rs index 4346e8c..b6821a9 100644 --- a/chombot/src/main.rs +++ b/chombot/src/main.rs @@ -9,6 +9,7 @@ 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::{ChombotPoiseUserData, start_tournaments_watcher}; @@ -40,7 +41,7 @@ impl ChombotPoiseUserData for PoiseUserData { pub type PoiseContext<'a> = Context<'a, PoiseUserData, anyhow::Error>; fn get_command_list() -> Vec> { - vec![hand(), score(), tournament_watcher()] + vec![hand(), score(), tournament_watcher(), create_channel()] } const CONFIG_DATA_PATH: &str = "data.toml";