diff --git a/ROADMAP.md b/ROADMAP.md index 6a68dbe..18afce9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -115,6 +115,7 @@ Plan (backward compatible with the existing file): - `tools/weather_art.rs`: sky by condition, detail tiles, 24-hour chart with chance of rain, 5-day ranges. The place name stays off the picture on purpose. - `emojis.rs`: application emojis from `assets/emojis/dz_*.png` (SVG sources beside them), uploaded at startup if missing, swapped in for the plain emoji on every button through `ui::emoji_button` and `games::btn`. `assets/emojis` must be copied when deploying. - `commands/info_art.rs`: `userinfo` (banner, status, role chips in role colours), `serverinfo` (members and boost meters), `channelinfo` (a colour per channel type) and `roleinfo`. The mention and ID stay as text under each picture. `richest` and Who Knows use `cardart::chart`; `pager::start_drawn` pages through drawn pictures. +- `commands/info_copy.rs`: the buttons under info cards open a private message with values in code blocks. Long lists (every role, channel, emoji, member, permission) go on pages instead of being cut short. Button ids carry what they need (`ii:::`), so they survive restarts. - `/queue` stays text: it's a private, self-deleting list of clickable links. A download's finished message is the video or file itself, so it gets no card. - Download progress stays text: it updates too often to upload pictures, and uploads would compete with the download. - Security pass: powerful roles are refused in role menus and autoroles (`State::role_gives_power`), redirects are checked at every hop, HSTS, Game Boy page frameable only by Discord. Not done: rate limits, Forgejo on its own subdomain, narrower invite permissions, `cargo audit` (not installed). diff --git a/src/commands/info.rs b/src/commands/info.rs index d02f9cb..0162308 100644 --- a/src/commands/info.rs +++ b/src/commands/info.rs @@ -7,6 +7,7 @@ //! Banners and accent colours need an extra API call per user; results are cached for 10 minutes so //! repeated lookups are instant and don't burn rate limits. use super::info_art as art; +use super::info_copy as copy; use super::media::fetch_picture; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; @@ -133,7 +134,7 @@ pub fn display_name(state: &State, guild: Option>, u: &User) -> } /// The picture shown for someone: server avatar, else their own, else the default one. -fn display_avatar(state: &State, guild: Option>, u: &User, size: u32) -> String { +pub(crate) fn display_avatar(state: &State, guild: Option>, u: &User, size: u32) -> String { if let Some(a) = guild.and_then(|g| state.cache.member(g, u.id)).and_then(|m| m.avatar()) { let ext = if a.is_animated() { "gif" } else { "png" }; return format!("https://cdn.discordapp.com/guilds/{}/users/{}/avatars/{a}.{ext}?size={size}", guild.unwrap(), u.id); @@ -141,7 +142,7 @@ fn display_avatar(state: &State, guild: Option>, u: &User, size: global_avatar(u, size) } -fn global_avatar(u: &User, size: u32) -> String { +pub(crate) fn global_avatar(u: &User, size: u32) -> String { match &u.avatar { Some(a) => format!("https://cdn.discordapp.com/avatars/{}/{a}.{}?size={size}", u.id, if a.is_animated() { "gif" } else { "png" }), None => ui::avatar_url(u.id, None), @@ -190,15 +191,16 @@ async fn user_card(state: &State, user: &User, guild: Option>) - if !badges.is_empty() { tiles.push(("Badges".to_string(), badges.join(", "))); } + let in_server = member.is_some(); if let Some((g, m)) = member { if let Some(j) = m.joined_at() { tiles.insert(1, ("Joined".to_string(), art::when(j.as_secs()))); } let mut roles: Vec<(i64, Id)> = m.roles().iter().filter_map(|r| state.cache.role(*r).map(|x| (x.position, *r))).collect(); roles.sort_by_key(|(p, _)| std::cmp::Reverse(*p)); - more_roles = roles.len().saturating_sub(20); + more_roles = roles.len().saturating_sub(40); #[allow(deprecated)] - let rows: Vec<(String, Option<[u8; 3]>)> = roles.iter().take(20).filter_map(|(_, r)| state.cache.role(*r).map(|x| (x.name.clone(), (x.color != 0).then(|| [(x.color >> 16) as u8, (x.color >> 8) as u8, x.color as u8])))).collect(); + let rows: Vec<(String, Option<[u8; 3]>)> = roles.iter().take(40).filter_map(|(_, r)| state.cache.role(*r).map(|x| (x.name.clone(), (x.color != 0).then(|| [(x.color >> 16) as u8, (x.color >> 8) as u8, x.color as u8])))).collect(); role_rows = rows; if let Some(n) = m.nick() { tiles.push(("Nickname".to_string(), n.to_string())); @@ -239,12 +241,16 @@ async fn user_card(state: &State, user: &User, guild: Option>) - None => None, }; let bytes = art::user(&art::User { accent, name: display_name(state, guild, user), handle: format!("@{}", user.name), avatar: fetch_picture(state, &avatar).await, banner, status, tiles, roles: role_rows, more_roles, permissions }); - let mut buttons = vec![link_button("Avatar", &avatar)]; - if let Some(b) = &banner_url { - buttons.push(link_button("Banner", b)); + let mut actions = vec![("ids", "IDs"), ("names", "Names"), ("avatar", "Avatar")]; + if banner_url.is_some() { + actions.push(("banner", "Banner")); } - let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@{}> · ID `{}`", user.id, user.id)).row(buttons).build(); - (card, bytes) + if in_server { + actions.extend([("roles", "Roles"), ("perms", "Permissions")]); + } + actions.push(("dates", "Dates")); + let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@{}> · ID `{}`", user.id, user.id)); + (copy::rows(card, "user", user.id.get(), &actions).build(), bytes) } async fn userinfo(ctx: Arc) -> Result<()> { @@ -316,18 +322,16 @@ async fn server_card(state: &State, guild: Id) -> Result<(Component banner: match &banner { Some(b) => fetch_picture(state, b).await, None => None }, members: total as u64, bots: bots as u64, online: online as u64, boosts: boosts, boosters: boosters as u64, }); - let mut card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("Owner <@{owner}> · ID `{guild}`")); - let mut buttons = vec![]; - if let Some(i) = &icon { - buttons.push(link_button("Icon", i)); + let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("Owner <@{owner}> · ID `{guild}`")); + let mut actions = vec![("ids", "IDs"), ("roles", "Roles"), ("channels", "Channels"), ("emojis", "Emojis"), ("stickers", "Stickers")]; + if icon.is_some() { + actions.push(("icon", "Icon")); } - if let Some(b) = &banner { - buttons.push(link_button("Banner", b)); + if banner.is_some() { + actions.push(("banner", "Banner")); } - if !buttons.is_empty() { - card = card.row(buttons); - } - Ok((card.build(), bytes)) + actions.extend([("features", "Features"), ("dates", "Dates")]); + Ok((copy::rows(card, "server", guild.get(), &actions).build(), bytes)) } async fn serverinfo(ctx: Arc) -> Result<()> { @@ -381,9 +385,21 @@ async fn channelinfo(ctx: Arc) -> Result<()> { can.push("send"); } tiles.push(("Everyone can".to_string(), if can.is_empty() { "Nothing".to_string() } else { let t = can.join(", "); t[..1].to_uppercase() + &t[1..] })); + let has_topic = topic.as_deref().is_some_and(|t| !t.is_empty()); let bytes = art::channel(&art::Channel { accent, symbol, name: c.name.clone().unwrap_or_else(|| "?".to_string()), kind: kind.to_string(), topic, tiles, inside }); - let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<#{id}> · ID `{id}`")).build(); - ctx.reply_file(card, art::FILE, bytes).await + let card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<#{id}> · ID `{id}`")); + let mut actions = vec![("ids", "IDs"), ("links", "Links"), ("perms", "Permissions")]; + if has_topic { + actions.push(("topic", "Topic")); + } + if is_voice { + actions.push(("people", "In voice")); + } + if c.kind == ChannelType::GuildCategory { + actions.push(("channels", "Channels")); + } + actions.push(("dates", "Dates")); + ctx.reply_file(copy::rows(card, "channel", id.get(), &actions).build(), art::FILE, bytes).await } async fn roleinfo(ctx: Arc) -> Result<()> { @@ -413,10 +429,16 @@ async fn roleinfo(ctx: Arc) -> Result<()> { if role.managed { tiles.push(("Managed by".to_string(), "An integration".to_string())); } + let has_icon = icon.is_some(); let picture = match &icon { Some(i) => fetch_picture(&ctx.state, i).await, None => None }; let bytes = art::role(&art::Role { accent: role.color, name: role.name.clone(), icon: picture, tiles, permissions: perms }); - let card = Card::new(Some(if role.color != 0 { role.color } else { BLURPLE })).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@&{id}> · ID `{id}`")).build(); - ctx.reply_file(card, art::FILE, bytes).await + let card = Card::new(Some(if role.color != 0 { role.color } else { BLURPLE })).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@&{id}> · ID `{id}`")); + let mut actions = vec![("ids", "IDs"), ("colour", "Colour"), ("members", "Members"), ("perms", "Permissions")]; + if has_icon { + actions.push(("icon", "Icon")); + } + actions.push(("dates", "Dates")); + ctx.reply_file(copy::rows(card, "role", id.get(), &actions).build(), art::FILE, bytes).await } // ---- avatar & banner ----------------------------------------------------------------------- diff --git a/src/commands/info_copy.rs b/src/commands/info_copy.rs new file mode 100644 index 0000000..ff71d31 --- /dev/null +++ b/src/commands/info_copy.rs @@ -0,0 +1,330 @@ +//! The buttons under the info cards. Each opens a private message with the values in code blocks, ready to copy, and +//! nothing is cut short: long lists go on pages instead. `ii:::` holds everything a button needs, so +//! they keep working after a restart. +use super::info::{created_at, display_avatar, display_name, full_user, global_avatar, perm_list, user_of}; +use crate::cardart::date; +use crate::converters::thousands; +use crate::state::State; +use crate::ui::{button, escape, truncate, Card}; +use crate::{interact, pager}; +use std::sync::Arc; +use std::time::Duration; +use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_model::channel::message::component::{Button, ButtonStyle}; +use twilight_model::channel::permission_overwrite::PermissionOverwriteType; +use twilight_model::guild::Permissions; +use twilight_model::id::marker::{ChannelMarker, GuildMarker, RoleMarker, UserMarker}; +use twilight_model::id::Id; + +const PER_PAGE: usize = 20; +/// Discord allows 4000 characters of text in a message; this leaves room for the heading. +const PAGE_TEXT: usize = 3600; + +/// The buttons for a card, five to a row. `actions` are (action, label). +pub fn rows(card: Card, kind: &str, id: u64, actions: &[(&str, &str)]) -> Card { + actions.chunks(5).fold(card, |card, chunk| card.row(chunk.iter().map(|(action, label)| -> Button { button(&format!("ii:{kind}:{action}:{id}"), label, ButtonStyle::Secondary) }).collect())) +} + +/// Keep a value from breaking out of its code block. +fn fence(value: &str) -> String { + value.replace("```", "'''") +} + +/// A private card of labelled values, each in its own code block. +fn values(title: &str, items: &[(String, String)]) -> twilight_model::channel::message::Component { + let body: Vec = items.iter().map(|(label, value)| format!("**{}**\n```\n{}\n```", escape(label), fence(value))).collect(); + Card::new(None).text(&format!("### {}", escape(title))).text(&body.join("\n")).build() +} + +async fn show(state: &State, i: &Interaction, title: &str, items: &[(&str, String)]) { + let items: Vec<(String, String)> = items.iter().map(|(a, b)| (a.to_string(), b.clone())).collect(); + interact::private_card(state, i, values(title, &items)).await; +} + +/// Split lines into pages short enough for one Discord message. +fn paged(lines: &[String]) -> Vec { + let mut pages: Vec> = vec![vec![]]; + let mut length = 0; + for line in lines { + if pages.last().is_some_and(|p| p.len() >= PER_PAGE) || (length + line.chars().count() > PAGE_TEXT && length > 0) { + pages.push(vec![]); + length = 0; + } + length += line.chars().count() + 1; + if let Some(page) = pages.last_mut() { + page.push(line); + } + } + pages.iter().map(|p| p.join("\n")).collect() +} + +/// A list of any length, on pages. +async fn list(state: &State, i: &Interaction, owner: u64, title: &str, lines: Vec, empty: &str) { + if lines.is_empty() { + return interact::private_text(state, i, empty).await; + } + let total = lines.len(); + let pages: Vec = paged(&lines).iter().map(|page| pager::fixed(Card::new(None).text(&format!("### {} · {}\n{page}", escape(title), thousands(total as u64))))).collect(); + interact::private_card(state, i, pager::register(owner, pages, Duration::from_secs(600))).await; +} + +fn id_line(id: impl std::fmt::Display, text: &str) -> String { + format!("`{id}` {}", escape(&truncate(text, 70))) +} + +fn stamp(unix: i64) -> String { + format!("") +} + +fn dated(label: &str, unix: i64) -> (String, String) { + (format!("{label}, {}", date(unix)), stamp(unix)) +} + +fn colour_text(colour: u32) -> String { + format!("#{colour:06X}") +} + +pub async fn on_component(state: &Arc, i: &Interaction) { + let Some(InteractionData::MessageComponent(d)) = i.data.as_ref() else { return }; + let mut parts = d.custom_id.split(':').skip(1); + let (Some(kind), Some(action), Some(id)) = (parts.next(), parts.next(), parts.next().and_then(|p| p.parse::().ok())) else { return }; + let Some(presser) = i.author().map(|u| u.id.get()) else { return }; + let guild = i.guild_id; + match kind { + "user" => { + let Some(uid) = Id::::new_checked(id) else { return }; + user(state, i, presser, guild, uid, action).await; + } + "server" => { + if let Some(g) = guild.filter(|g| g.get() == id) { + server(state, i, presser, g, action).await; + } + } + "channel" => { + if let (Some(g), Some(c)) = (guild, Id::::new_checked(id)) { + channel(state, i, presser, g, c, action).await; + } + } + "role" => { + if let (Some(g), Some(r)) = (guild, Id::::new_checked(id)) { + role(state, i, presser, g, r, action).await; + } + } + _ => {} + } +} + +async fn user(state: &State, i: &Interaction, presser: u64, guild: Option>, id: Id, action: &str) { + let Ok(u) = user_of(state, id).await else { return interact::private_text(state, i, "I can't find that person any more.").await }; + let member = guild.and_then(|g| state.cache.member(g, id).map(|m| (g, m.roles().to_vec(), m.nick().map(str::to_string), m.joined_at().map(|t| t.as_secs()), m.premium_since().map(|t| t.as_secs())))); + match action { + "ids" => { + let mut items = vec![("User ID", id.to_string()), ("Mention", format!("<@{id}>"))]; + if let Some(g) = guild { + items.push(("Server ID", g.to_string())); + } + show(state, i, "IDs", &items).await; + } + "names" => { + let mut items = vec![("Username", u.name.clone()), ("Shown as here", display_name(state, guild, &u))]; + if let Some(g) = &u.global_name { + items.push(("Display name", g.clone())); + } + if let Some(n) = member.as_ref().and_then(|m| m.2.clone()) { + items.push(("Server nickname", n)); + } + show(state, i, "Names", &items).await; + } + "avatar" => { + let mut items = vec![("Avatar link", global_avatar(&u, 4096))]; + let shown = display_avatar(state, guild, &u, 4096); + if shown != items[0].1 { + items.push(("Server avatar link", shown)); + } + show(state, i, "Avatar", &items).await; + } + "banner" => { + let full = full_user(state, id).await; + let mut items = vec![]; + if let Some(b) = full.as_ref().and_then(|f| f.banner.as_ref()) { + items.push(("Banner link", b.replace("size=1024", "size=4096"))); + } + if let Some(a) = full.as_ref().and_then(|f| f.accent) { + items.push(("Profile colour", colour_text(a))); + } + if items.is_empty() { + return interact::private_text(state, i, "They have no banner.").await; + } + show(state, i, "Banner", &items).await; + } + "roles" => { + let mut roles: Vec<(i64, Id, String)> = member.iter().flat_map(|m| m.1.iter()).filter_map(|r| state.cache.role(*r).map(|x| (x.position, *r, x.name.clone()))).collect(); + roles.sort_by_key(|r| std::cmp::Reverse(r.0)); + list(state, i, presser, "Roles", roles.iter().map(|r| id_line(r.1, &r.2)).collect(), "They have no roles here.").await; + } + "perms" => { + let Some(g) = guild else { return }; + let perms = state.guild_permissions(g, id); + let lines = if perms.contains(Permissions::ADMINISTRATOR) { vec!["Administrator, so every permission".to_string()] } else { perm_list(perms) }; + list(state, i, presser, "Permissions", lines.iter().map(|p| escape(p)).collect(), "They have no permissions here.").await; + } + "dates" => { + let mut items = vec![dated("Account created", created_at(id.get()))]; + if let Some(j) = member.as_ref().and_then(|m| m.3) { + items.push(dated("Joined this server", j)); + } + if let Some(b) = member.as_ref().and_then(|m| m.4) { + items.push(dated("Boosting since", b)); + } + interact::private_card(state, i, values("Dates, as Discord timestamps", &items)).await; + } + _ => {} + } +} + +async fn server(state: &State, i: &Interaction, presser: u64, id: Id, action: &str) { + let cache = &state.cache; + let Some((owner, icon, banner, features)) = cache.guild(id).map(|g| ( + g.owner_id(), + g.icon().map(|i| format!("https://cdn.discordapp.com/icons/{id}/{i}.{}?size=4096", if i.is_animated() { "gif" } else { "png" })), + g.banner().map(|b| format!("https://cdn.discordapp.com/banners/{id}/{b}.png?size=4096")), + g.features().map(|f| format!("{f:?}")).collect::>(), + )) else { return }; + match action { + "ids" => show(state, i, "IDs", &[("Server ID", id.to_string()), ("Owner ID", owner.to_string()), ("Owner mention", format!("<@{owner}>"))]).await, + "icon" => show(state, i, "Icon", &[("Icon link", icon.unwrap_or_default())]).await, + "banner" => show(state, i, "Banner", &[("Banner link", banner.unwrap_or_default())]).await, + "dates" => interact::private_card(state, i, values("Dates, as Discord timestamps", &[dated("Server created", created_at(id.get()))])).await, + "features" => list(state, i, presser, "Server features", features.iter().map(|f| escape(f)).collect(), "This server has no special features.").await, + "roles" => { + let mut roles: Vec<(i64, Id, String)> = cache.guild_roles(id).map(|r| r.iter().filter_map(|r| cache.role(*r).map(|x| (x.position, *r, x.name.clone()))).collect()).unwrap_or_default(); + roles.sort_by_key(|r| std::cmp::Reverse(r.0)); + list(state, i, presser, "Roles", roles.iter().map(|r| id_line(r.1, &r.2)).collect(), "No roles.").await; + } + "channels" => { + let ids: Vec<_> = cache.guild_channels(id).map(|c| c.iter().copied().collect()).unwrap_or_default(); + let mut rows: Vec<(i64, i64, Id, String)> = ids.iter().filter_map(|c| cache.channel(*c).map(|x| { + let parent = x.parent_id.and_then(|p| cache.channel(p).map(|p| p.position.unwrap_or(0) as i64)).unwrap_or(x.position.unwrap_or(0) as i64); + (parent, if x.parent_id.is_some() { 1 + x.position.unwrap_or(0) as i64 } else { 0 }, *c, x.name.clone().unwrap_or_default()) + })).collect(); + rows.sort_by_key(|r| (r.0, r.1)); + list(state, i, presser, "Channels", rows.iter().map(|r| id_line(r.2, &r.3)).collect(), "No channels.").await; + } + "emojis" => { + let ids: Vec<_> = cache.guild_emojis(id).map(|e| e.iter().copied().collect()).unwrap_or_default(); + let lines = ids.iter().filter_map(|e| cache.emoji(*e).map(|x| format!("{}`{}`", if x.animated() { format!(" ", x.name(), x.id()) } else { format!("<:{}:{}> ", x.name(), x.id()) }, if x.animated() { format!("", x.name(), x.id()) } else { format!("<:{}:{}>", x.name(), x.id()) }))).collect(); + list(state, i, presser, "Emojis", lines, "This server has no custom emojis.").await; + } + "stickers" => { + let ids: Vec<_> = cache.guild_stickers(id).map(|e| e.iter().copied().collect()).unwrap_or_default(); + let lines = ids.iter().filter_map(|s| cache.sticker(*s).map(|x| id_line(s, x.name()))).collect(); + list(state, i, presser, "Stickers", lines, "This server has no stickers.").await; + } + _ => {} + } +} + +async fn channel(state: &State, i: &Interaction, presser: u64, guild: Id, id: Id, action: &str) { + let cache = &state.cache; + let Some(c) = cache.channel(id).filter(|c| c.guild_id == Some(guild)).map(|c| c.clone()) else { return interact::private_text(state, i, "I can't see that channel any more.").await }; + match action { + "ids" => { + let mut items = vec![("Channel ID", id.to_string()), ("Server ID", guild.to_string())]; + if let Some(p) = c.parent_id { + items.push(("Category ID", p.to_string())); + } + show(state, i, "IDs", &items).await; + } + "links" => show(state, i, "Links", &[("Jump link", format!("https://discord.com/channels/{guild}/{id}")), ("Mention", format!("<#{id}>"))]).await, + "topic" => show(state, i, "Topic", &[("Topic", c.topic.clone().unwrap_or_default())]).await, + "dates" => interact::private_card(state, i, values("Dates, as Discord timestamps", &[dated("Channel created", created_at(id.get()))])).await, + "perms" => { + let mut lines = vec![]; + for o in c.permission_overwrites.iter().flatten() { + let who = match o.kind { + PermissionOverwriteType::Role => cache.role(o.id.cast()).map_or("A role".to_string(), |r| r.name.clone()), + _ => match Id::::new_checked(o.id.get()) { + Some(u) => super::info::display_name_of(state, Some(guild), u).await, + None => "Someone".to_string(), + }, + }; + let say = |p: Permissions| if p.is_empty() { "nothing".to_string() } else { perm_list(p).join(", ") }; + lines.push(format!("{}\n-# Allowed: {}\n-# Denied: {}", id_line(o.id, &who), say(o.allow), say(o.deny))); + } + list(state, i, presser, "Permission overrides", lines, "This channel has no permission overrides.").await; + } + "people" => { + let users: Vec<_> = cache.voice_channel_states(id).map(|it| it.map(|s| s.user_id()).collect()).unwrap_or_default(); + let mut lines = vec![]; + for u in users { + lines.push(id_line(u, &super::info::display_name_of(state, Some(guild), u).await)); + } + list(state, i, presser, "In voice", lines, "Nobody is in this channel right now.").await; + } + "channels" => { + let ids: Vec<_> = cache.guild_channels(guild).map(|c| c.iter().copied().collect()).unwrap_or_default(); + let lines = ids.iter().filter_map(|x| cache.channel(*x).filter(|x| x.parent_id == Some(id)).map(|x| id_line(x.id, x.name.as_deref().unwrap_or("?")))).collect(); + list(state, i, presser, "Channels in this category", lines, "This category is empty.").await; + } + _ => {} + } +} + +async fn role(state: &State, i: &Interaction, presser: u64, guild: Id, id: Id, action: &str) { + let cache = &state.cache; + let Some(r) = cache.role(id).map(|r| r.resource().clone()) else { return interact::private_text(state, i, "I can't see that role any more.").await }; + match action { + "ids" => show(state, i, "IDs", &[("Role ID", id.to_string()), ("Mention", format!("<@&{id}>")), ("Server ID", guild.to_string())]).await, + "colour" => { + #[allow(deprecated)] + let c = r.color; + show(state, i, "Colour", &[("Hex", colour_text(c)), ("RGB", format!("{}, {}, {}", c >> 16 & 255, c >> 8 & 255, c & 255)), ("Decimal", c.to_string())]).await; + } + "perms" => { + let lines = if r.permissions.contains(Permissions::ADMINISTRATOR) { vec!["Administrator, so every permission".to_string()] } else { perm_list(r.permissions) }; + list(state, i, presser, "Permissions", lines.iter().map(|p| escape(p)).collect(), "This role adds no permissions.").await; + } + "members" => { + let ids: Vec<_> = cache.guild_members(guild).map(|m| m.iter().copied().filter(|u| cache.member(guild, *u).is_some_and(|m| m.roles().contains(&id))).collect()).unwrap_or_default(); + let mut lines = vec![]; + for u in ids { + lines.push(id_line(u, &super::info::display_name_of(state, Some(guild), u).await)); + } + list(state, i, presser, "Members", lines, "Nobody has this role.").await; + } + "icon" => show(state, i, "Icon", &[("Icon link", r.icon.map_or(String::new(), |h| format!("https://cdn.discordapp.com/role-icons/{id}/{h}.png?size=4096")))]).await, + "dates" => interact::private_card(state, i, values("Dates, as Discord timestamps", &[dated("Role created", created_at(id.get()))])).await, + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_stay_inside_their_code_block() { + assert_eq!(fence("a```b"), "a'''b"); + assert!(serde_json::to_string(&values("IDs", &[("User ID".to_string(), "123".to_string())])).unwrap().contains("123")); + } + + #[test] + fn long_lists_lose_nothing_and_every_page_fits() { + let short: Vec = (0..250).map(|n| format!("role {n}")).collect(); + let pages = paged(&short); + assert_eq!(pages.len(), 13); + assert_eq!(pages.iter().map(|p| p.lines().count()).sum::(), 250); + let long: Vec = (0..30).map(|n| format!("{n} {}", "x".repeat(500))).collect(); + let pages = paged(&long); + assert!(pages.iter().all(|p| p.chars().count() <= 4000)); + assert_eq!(pages.iter().map(|p| p.lines().count()).sum::(), 30); + } + + #[test] + fn long_button_sets_wrap_into_rows() { + let actions: Vec<(&str, &str)> = vec![("a", "A"); 9]; + let json = serde_json::to_string(&rows(Card::new(None).text("x"), "user", 42, &actions).build()).unwrap(); + assert!(json.contains("ii:user:a:42")); + assert_eq!(crate::ui::cost(&rows(Card::new(None).text("x"), "user", 42, &actions).build()).0 > 9, true); + } +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index bce4a76..1957bbc 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -13,6 +13,7 @@ pub mod gameboy; pub mod games; pub mod info; mod info_art; +pub mod info_copy; pub mod lastfm; pub mod logs; pub mod media; diff --git a/src/main.rs b/src/main.rs index 4219701..b1a89bd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -289,6 +289,9 @@ async fn on_component(state: Arc, i: twilight_model::application::interac if data.custom_id.starts_with("color:") { return commands::tools::on_color(&state, &i).await; } + if data.custom_id.starts_with("ii:") { + return commands::info_copy::on_component(&state, &i).await; + } if data.custom_id.starts_with("wx:") { return commands::tools::weather::on_component(&state, &i).await; }