Dezio/src/commands/info.rs
astar76 0fd743122a Drawn user, server, channel and role cards; richest and Who Knows charts
Info cards take their colour from what they describe, with role chips,
member and boost meters and a colour per channel type. The mention and ID
stay as text underneath. Richest pages through drawn charts and Who Knows
draws ranked bars.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 22:27:18 -06:00

503 lines
26 KiB
Rust

//! Info cards: users, servers, channels, roles, avatars and banners.
//!
//! `userinfo`/`serverinfo`/`channelinfo`/`roleinfo` work as `/name` and `D!name`; `D!avatar`/`D!banner`
//! plus the "Show Avatar"/"Show Banner" right-click apps. Prefix versions accept a reply to look up the
//! person you replied to.
//!
//! 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::media::fetch_picture;
use crate::bail_user;
use crate::cmd::{Command, Ctx, Opt, OptKind};
use crate::colors;
use crate::converters::thousands;
use crate::state::State;
use crate::ui::{self, escape, truncate, Card, BLURPLE};
use anyhow::Result;
use futures::FutureExt;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use twilight_model::channel::message::component::{Button, ButtonStyle};
use twilight_model::channel::message::Component;
use twilight_model::channel::ChannelType;
use twilight_model::gateway::presence::{ActivityType, Status};
use twilight_model::guild::Permissions;
use twilight_model::id::marker::{GuildMarker, RoleMarker, UserMarker};
use twilight_model::id::Id;
use twilight_model::user::{User, UserFlags};
const KEY_PERMS: &[(Permissions, &str)] = &[
(Permissions::ADMINISTRATOR, "Administrator"), (Permissions::MANAGE_GUILD, "Manage Server"),
(Permissions::MANAGE_ROLES, "Manage Roles"), (Permissions::MANAGE_CHANNELS, "Manage Channels"),
(Permissions::MANAGE_MESSAGES, "Manage Messages"), (Permissions::BAN_MEMBERS, "Ban Members"),
(Permissions::KICK_MEMBERS, "Kick Members"), (Permissions::MODERATE_MEMBERS, "Moderate Members"),
(Permissions::MENTION_EVERYONE, "Mention Everyone"), (Permissions::MANAGE_WEBHOOKS, "Manage Webhooks"),
(Permissions::MANAGE_GUILD_EXPRESSIONS, "Manage Expressions"),
];
const BADGES: &[(UserFlags, &str)] = &[
(UserFlags::STAFF, "Discord Staff"), (UserFlags::PARTNER, "Partner"), (UserFlags::HYPESQUAD, "HypeSquad Events"),
(UserFlags::BUG_HUNTER_LEVEL_1, "Bug Hunter"), (UserFlags::BUG_HUNTER_LEVEL_2, "Bug Hunter Gold"),
(UserFlags::HYPESQUAD_ONLINE_HOUSE_1, "Bravery"), (UserFlags::HYPESQUAD_ONLINE_HOUSE_2, "Brilliance"),
(UserFlags::HYPESQUAD_ONLINE_HOUSE_3, "Balance"), (UserFlags::PREMIUM_EARLY_SUPPORTER, "Early Supporter"),
(UserFlags::VERIFIED_DEVELOPER, "Early Bot Dev"), (UserFlags::MODERATOR_PROGRAMS_ALUMNI, "Certified Mod"),
(UserFlags::ACTIVE_DEVELOPER, "Active Developer"), (UserFlags::VERIFIED_BOT, "Verified Bot"),
];
pub fn created_at(id: u64) -> i64 {
(((id >> 22) + 1_420_070_400_000) / 1000) as i64
}
fn ts(unix: i64, style: char) -> String {
format!("<t:{unix}:{style}>")
}
/// Title-cased permission names ("manage guild" -> "Manage Server").
pub fn perm_list(p: Permissions) -> Vec<String> {
p.iter_names()
.map(|(n, _)| {
n.to_lowercase().replace("guild", "server").split('_').map(|w| {
let mut c = w.chars();
c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default()
}).collect::<Vec<_>>().join(" ")
})
.collect()
}
fn link_button(label: &str, url: &str) -> Button {
Button { id: None, custom_id: None, disabled: false, emoji: None, label: Some(label.into()), style: ButtonStyle::Link, url: Some(url.into()), sku_id: None }
}
// ---- the full profile (banner + accent colour) ---------------------------------------------
#[derive(Clone)]
pub struct Full {
pub banner: Option<String>,
pub accent: Option<u32>,
}
fn users_cache() -> &'static Mutex<HashMap<u64, (Instant, Full)>> {
static C: OnceLock<Mutex<HashMap<u64, (Instant, Full)>>> = OnceLock::new();
C.get_or_init(Default::default)
}
/// `GET /users/{id}` (has banner + accent colour), cached for 10 minutes.
pub async fn full_user(state: &State, id: Id<UserMarker>) -> Option<Full> {
if let Some((at, f)) = users_cache().lock().unwrap().get(&id.get()) {
if at.elapsed() < Duration::from_secs(600) {
return Some(f.clone());
}
}
let u = state.http.user(id).await.ok()?.model().await.ok()?;
let full = Full {
banner: u.banner.map(|b| format!("https://cdn.discordapp.com/banners/{id}/{b}.{}?size=1024", if b.is_animated() { "gif" } else { "png" })),
accent: u.accent_color,
};
let mut c = users_cache().lock().unwrap();
if c.len() > 500 {
c.clear();
}
c.insert(id.get(), (Instant::now(), full.clone()));
Some(full)
}
/// A user from the cache, or from Discord.
pub async fn user_of(state: &State, id: Id<UserMarker>) -> Result<User> {
if let Some(u) = state.cache.user(id) {
return Ok(u.clone());
}
Ok(state.http.user(id).await.map_err(|_| crate::error::UserError::new("No Discord user has that ID."))?.model().await?)
}
/// A person's server nickname, global name or username (looked up over HTTP when we haven't seen them).
pub async fn display_name_of(state: &State, guild: Option<Id<GuildMarker>>, id: Id<UserMarker>) -> String {
if let Some(n) = guild.and_then(|g| state.cache.member(g, id).and_then(|m| m.nick().map(str::to_string))) {
return n;
}
if let Some(u) = state.cache.user(id) {
return u.global_name.clone().unwrap_or_else(|| u.name.clone());
}
match user_of(state, id).await {
Ok(u) => u.global_name.clone().unwrap_or(u.name),
Err(_) => "someone".into(),
}
}
pub fn display_name(state: &State, guild: Option<Id<GuildMarker>>, u: &User) -> String {
guild
.and_then(|g| state.cache.member(g, u.id).and_then(|m| m.nick().map(str::to_string)))
.or_else(|| u.global_name.clone())
.unwrap_or_else(|| u.name.clone())
}
/// The picture shown for someone: server avatar, else their own, else the default one.
fn display_avatar(state: &State, guild: Option<Id<GuildMarker>>, 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);
}
global_avatar(u, size)
}
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),
}
}
/// Who a command is about: the option, else the replied-to author, else you.
async fn target(ctx: &Ctx, option: &str) -> Result<User> {
if let Some(id) = ctx.args.user(option) {
return user_of(&ctx.state, id).await;
}
if let Some(t) = ctx.args.str(option) {
if let Some(g) = ctx.guild_id {
if let Some(id) = crate::converters::find_member(&ctx.state.cache, g, t) {
return user_of(&ctx.state, id).await;
}
}
bail_user!("I couldn't find `{}`.", escape(t));
}
if let Some(u) = &ctx.target_user {
return Ok(u.clone());
}
user_of(&ctx.state, ctx.reply_to.unwrap_or(ctx.user_id)).await
}
// ---- user ----------------------------------------------------------------------------------
async fn user_card(state: &State, user: &User, guild: Option<Id<GuildMarker>>) -> (Component, Vec<u8>) {
let full = full_user(state, user.id).await;
let member = guild.and_then(|g| state.cache.member(g, user.id).map(|m| (g, m)));
let role_color = member.as_ref().and_then(|(g, m)| {
let top = state.cache.member_highest_role(*g, user.id)?;
let _ = m;
state.cache.role(top).map(|r| r.color).filter(|c| *c != 0)
});
let avatar = display_avatar(state, guild, user, 256);
let accent = full.as_ref().and_then(|f| f.accent).or(role_color).unwrap_or(BLURPLE);
let accent = colors::accent(state, Some(&avatar), accent).await;
let created = created_at(user.id.get());
let badges: Vec<&str> = user.public_flags.map(|f| BADGES.iter().filter(|(b, _)| f.contains(*b)).map(|(_, n)| *n).collect()).unwrap_or_default();
let mut tiles = vec![("Account created".to_string(), art::when(created))];
let (mut status, mut role_rows, mut more_roles, mut permissions) = (None, vec![], 0, vec![]);
if user.bot {
tiles.push(("Account".to_string(), "Bot".to_string()));
}
if !badges.is_empty() {
tiles.push(("Badges".to_string(), badges.join(", ")));
}
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<RoleMarker>)> = 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);
#[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();
role_rows = rows;
if let Some(n) = m.nick() {
tiles.push(("Nickname".to_string(), n.to_string()));
}
status = Some(match state.cache.presence(g, user.id).map(|p| p.status()) {
Some(Status::Online) => ("Online", [76, 195, 138]),
Some(Status::Idle) => ("Idle", [240, 178, 50]),
Some(Status::DoNotDisturb) => ("Do not disturb", [229, 72, 77]),
_ => ("Offline", [133, 133, 139]),
});
tiles.push(("Status".to_string(), status.map_or("Offline", |s| s.0).to_string()));
if let Some(p) = state.cache.presence(g, user.id) {
if let Some(a) = p.activities().iter().find(|a| a.kind != ActivityType::Custom && !a.name.is_empty()) {
let verb = match a.kind {
ActivityType::Playing => "Playing", ActivityType::Listening => "Listening to", ActivityType::Watching => "Watching",
ActivityType::Streaming => "Streaming", ActivityType::Competing => "Competing in", _ => "Doing",
};
let detail = if a.kind == ActivityType::Listening { a.details.as_ref().map_or(String::new(), |d| format!(": {d}")) } else { String::new() };
tiles.push(("Activity".to_string(), format!("{verb} {}{detail}", a.name)));
}
}
if let Some(b) = m.premium_since() {
tiles.push(("Boosting since".to_string(), art::when(b.as_secs())));
}
if let Some(t) = m.communication_disabled_until().filter(|t| (t.as_secs() as f64) > crate::audit::now()) {
tiles.push(("Timed out until".to_string(), crate::cardart::date(t.as_secs())));
}
let perms = state.guild_permissions(g, user.id);
let mut key: Vec<&str> = KEY_PERMS.iter().filter(|(p, _)| perms.contains(*p)).map(|(_, n)| *n).collect();
if key.contains(&"Administrator") {
key = vec!["Administrator"];
}
permissions = key.into_iter().map(str::to_string).collect();
}
let banner_url = full.and_then(|f| f.banner);
let banner = match &banner_url {
Some(b) => fetch_picture(state, b).await,
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 card = Card::new(Some(accent)).gallery(&[&format!("attachment://{}", art::FILE)]).footer(&format!("<@{}> · ID `{}`", user.id, user.id)).row(buttons).build();
(card, bytes)
}
async fn userinfo(ctx: Arc<Ctx>) -> Result<()> {
let user = target(&ctx, "user").await?;
ctx.defer().await?;
let (card, picture) = user_card(&ctx.state, &user, ctx.guild_id).await;
ctx.reply_file(card, art::FILE, picture).await
}
// ---- server --------------------------------------------------------------------------------
fn emoji_limit(tier: u8) -> usize {
[50, 100, 150, 250][tier.min(3) as usize]
}
fn sticker_limit(tier: u8) -> usize {
[5, 15, 30, 60][tier.min(3) as usize]
}
async fn server_card(state: &State, guild: Id<GuildMarker>) -> Result<(Component, Vec<u8>)> {
let Some(g) = state.cache.guild(guild) else { bail_user!("I can't see that server.") };
let cache = &state.cache;
let members: Vec<Id<UserMarker>> = cache.guild_members(guild).map(|m| m.iter().copied().collect()).unwrap_or_default();
let bots = members.iter().filter(|u| cache.user(**u).is_some_and(|x| x.bot)).count();
let online = members.iter().filter(|u| cache.presence(guild, **u).is_some_and(|p| p.status() != Status::Offline)).count();
let total = g.member_count().unwrap_or(members.len() as u64) as usize;
let created = created_at(guild.get());
let icon = g.icon().map(|i| format!("https://cdn.discordapp.com/icons/{guild}/{i}.{}?size=256", if i.is_animated() { "gif" } else { "png" }));
let banner = g.banner().map(|b| format!("https://cdn.discordapp.com/banners/{guild}/{b}.png?size=1024"));
let accent = colors::accent(state, icon.as_deref().or(banner.as_deref()), BLURPLE).await;
let mut kinds: HashMap<ChannelType, usize> = HashMap::new();
for id in cache.guild_channels(guild).map(|c| c.iter().copied().collect::<Vec<_>>()).unwrap_or_default() {
if let Some(c) = cache.channel(id) {
*kinds.entry(c.kind).or_default() += 1;
}
}
let n = |k: ChannelType| kinds.get(&k).copied().unwrap_or(0);
let voice = n(ChannelType::GuildVoice) + n(ChannelType::GuildStageVoice);
let tier: u8 = u8::from(g.premium_tier());
let roles = cache.guild_roles(guild).map_or(0, |r| r.len());
let emojis = cache.guild_emojis(guild).map_or(0, |e| e.len());
let stickers = cache.guild_stickers(guild).map_or(0, |e| e.len());
let boosters = members.iter().filter(|u| cache.member(guild, **u).is_some_and(|m| m.premium_since().is_some())).count();
let features: Vec<String> = g.features().into_iter().filter_map(|f| {
let name = format!("{f:?}");
["Community", "Partnered", "Verified", "Discoverable", "VanityUrl", "AnimatedIcon", "Banner", "RoleIcons", "WelcomeScreenEnabled", "MemberVerificationGateEnabled"]
.contains(&name.as_str()).then(|| name)
}).collect();
let (name, description, owner, boosts, verification) = (g.name().to_string(), g.description().map(str::to_string), g.owner_id(), g.premium_subscription_count().unwrap_or(0), format!("{:?}", g.verification_level()));
drop(g);
let owner_name = display_name_of(state, Some(guild), owner).await;
let mut tiles = vec![
("Text".to_string(), (n(ChannelType::GuildText) + n(ChannelType::GuildAnnouncement)).to_string()),
("Voice".to_string(), voice.to_string()),
("Categories".to_string(), n(ChannelType::GuildCategory).to_string()),
("Roles".to_string(), roles.to_string()),
("Emojis".to_string(), format!("{emojis} of {}", emoji_limit(tier))),
("Stickers".to_string(), format!("{stickers} of {}", sticker_limit(tier))),
("Owner".to_string(), owner_name),
("Created".to_string(), crate::cardart::date(created)),
("Verification".to_string(), verification),
];
if n(ChannelType::GuildForum) > 0 {
tiles.insert(3, ("Forums".to_string(), n(ChannelType::GuildForum).to_string()));
}
let bytes = art::server(&art::Server {
accent, name, description, tiles, features, tier,
icon: match &icon { Some(i) => fetch_picture(state, i).await, None => None },
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));
}
if let Some(b) = &banner {
buttons.push(link_button("Banner", b));
}
if !buttons.is_empty() {
card = card.row(buttons);
}
Ok((card.build(), bytes))
}
async fn serverinfo(ctx: Arc<Ctx>) -> Result<()> {
ctx.defer().await?;
let (card, picture) = server_card(&ctx.state, ctx.guild()?).await?;
ctx.reply_file(card, art::FILE, picture).await
}
// ---- channel & role ------------------------------------------------------------------------
async fn channelinfo(ctx: Arc<Ctx>) -> Result<()> {
let guild = ctx.guild()?;
let id = ctx.args.id("channel").and_then(Id::new_checked).unwrap_or(ctx.channel_id);
let Some(c) = ctx.state.cache.channel(id).map(|c| c.clone()) else { bail_user!("I can't see that channel.") };
let (accent, symbol, kind) = art::channel_look(&format!("{:?}", c.kind));
let created = created_at(id.get());
let mut tiles = vec![("Created".to_string(), crate::cardart::date(created))];
if let Some(p) = c.parent_id.and_then(|p| ctx.state.cache.channel(p).and_then(|p| p.name.clone())) {
tiles.push(("Category".to_string(), p));
}
let mut topic = None;
if matches!(c.kind, ChannelType::GuildText | ChannelType::GuildAnnouncement | ChannelType::GuildForum) {
topic = c.topic.clone();
let sm = c.rate_limit_per_user.unwrap_or(0);
tiles.push(("Slowmode".to_string(), if sm > 0 { format!("{sm} seconds") } else { "Off".to_string() }));
tiles.push(("Age restricted".to_string(), if c.nsfw.unwrap_or(false) { "Yes" } else { "No" }.to_string()));
}
let mut inside = vec![];
let is_voice = matches!(c.kind, ChannelType::GuildVoice | ChannelType::GuildStageVoice);
if is_voice {
tiles.push(("Bitrate".to_string(), format!("{} kbps", c.bitrate.unwrap_or(0) / 1000)));
tiles.push(("User limit".to_string(), c.user_limit.filter(|l| *l > 0).map_or("None".to_string(), |l| l.to_string())));
tiles.push(("Region".to_string(), c.rtc_region.clone().unwrap_or_else(|| "Automatic".to_string())));
let users: Vec<_> = ctx.state.cache.voice_channel_states(id).map(|it| it.take(24).map(|s| s.user_id()).collect()).unwrap_or_default();
for u in users {
inside.push(display_name_of(&ctx.state, Some(guild), u).await);
}
}
if c.kind == ChannelType::GuildCategory {
let n = ctx.state.cache.guild_channels(guild).map_or(0, |ids| ids.iter().filter(|i| ctx.state.cache.channel(**i).is_some_and(|x| x.parent_id == Some(id))).count());
tiles.push(("Channels".to_string(), n.to_string()));
}
let everyone = ctx.state.cache.role(guild.cast()).map_or(Permissions::empty(), |r| r.permissions);
let mut can = vec![];
if everyone.contains(Permissions::VIEW_CHANNEL) {
can.push("view");
}
if is_voice && everyone.contains(Permissions::CONNECT) {
can.push("connect");
} else if !is_voice && everyone.contains(Permissions::SEND_MESSAGES) {
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 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
}
async fn roleinfo(ctx: Arc<Ctx>) -> Result<()> {
let guild = ctx.guild()?;
let Some(text) = ctx.args.str("role") else { bail_user!("Which role?") };
let cache = &ctx.state.cache;
let id = ctx.args.id("role").and_then(Id::<RoleMarker>::new_checked).filter(|r| cache.role(*r).is_some()).or_else(|| {
let wanted = text.trim_start_matches('@').to_lowercase();
cache.guild_roles(guild)?.iter().copied().find(|r| cache.role(*r).is_some_and(|x| x.name.to_lowercase() == wanted))
});
let Some(id) = id else { bail_user!("No role called `{}`.", escape(text)) };
let role = cache.role(id).map(|r| r.resource().clone()).ok_or_else(|| crate::error::UserError::new("I can't see that role."))?;
let members = cache.guild_members(guild).map_or(0, |ms| ms.iter().filter(|u| cache.member(guild, **u).is_some_and(|m| m.roles().contains(&id))).count());
let total = cache.guild_roles(guild).map_or(1, |r| r.len()) - 1;
let created = created_at(id.get());
let perms = if role.permissions.contains(Permissions::ADMINISTRATOR) { vec!["Administrator (every permission)".to_string()] } else { perm_list(role.permissions) };
let icon = role.icon.map(|i| format!("https://cdn.discordapp.com/role-icons/{id}/{i}.png"));
let yes = |b: bool| if b { "Yes" } else { "No" }.to_string();
let mut tiles = vec![
("Members".to_string(), thousands(members as u64)),
("Position".to_string(), format!("{} of {total}", role.position)),
("Colour".to_string(), if role.color != 0 { format!("#{:06X}", role.color) } else { "None".to_string() }),
("Created".to_string(), crate::cardart::date(created)),
("Shown separately".to_string(), yes(role.hoist)),
("Mentionable".to_string(), yes(role.mentionable)),
];
if role.managed {
tiles.push(("Managed by".to_string(), "An integration".to_string()));
}
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
}
// ---- avatar & banner -----------------------------------------------------------------------
async fn avatar_card(state: &State, user: &User, requester: &str, guild: Option<Id<GuildMarker>>) -> Component {
let shown = display_avatar(state, guild, user, 1024);
let mut images = vec![shown.clone()];
let big = |u: &str| u.replace("size=1024", "size=4096");
let mut buttons = vec![link_button("Open", &big(&shown))];
let has_server = guild.and_then(|g| state.cache.member(g, user.id)).is_some_and(|m| m.avatar().is_some());
if has_server && user.avatar.is_some() {
let global = global_avatar(user, 1024);
buttons.push(link_button("Global avatar", &big(&global)));
images.push(global);
}
let accent = colors::accent(state, Some(&images[0]), BLURPLE).await;
let urls: Vec<&str> = images.iter().map(String::as_str).collect();
Card::new(Some(accent)).text(&format!("### 🖼️ {}'s avatar", escape(&display_name(state, guild, user)))).gallery(&urls)
.footer(&format!("Requested by {requester}")).row(buttons).build()
}
async fn banner_card(state: &State, user: &User, requester: &str) -> Option<Component> {
let full = full_user(state, user.id).await?;
let banner = full.banner?;
let accent = colors::accent(state, Some(&banner), full.accent.unwrap_or(BLURPLE)).await;
Some(Card::new(Some(accent)).text(&format!("### 🏞️ {}'s banner", escape(user.global_name.as_deref().unwrap_or(&user.name))))
.gallery(&[&banner]).footer(&format!("Requested by {requester}")).row(vec![link_button("Open", &banner.replace("size=1024", "size=4096"))]).build())
}
async fn avatar(ctx: Arc<Ctx>) -> Result<()> {
let user = target(&ctx, "user").await?;
ctx.defer().await?;
ctx.reply(avatar_card(&ctx.state, &user, &ctx.user_name, ctx.guild_id).await).await
}
async fn banner(ctx: Arc<Ctx>) -> Result<()> {
let user = target(&ctx, "user").await?;
ctx.defer().await?;
match banner_card(&ctx.state, &user, &ctx.user_name).await {
Some(c) => ctx.reply(c).await,
None => ctx.fail(&format!("🙈 {} doesn't have a banner.", escape(&display_name(&ctx.state, ctx.guild_id, &user)))).await,
}
}
pub fn commands() -> Vec<Command> {
let user = || Opt::opt("user", "Who to look up (defaults to you)", OptKind::User);
vec![
Command::new("userinfo", "utility", "Profile card: account age, roles, status, badges and banner", |c| userinfo(c).boxed())
.aliases(&["ui", "user", "whois"]).usage("[member]").opt(user()),
Command::new("serverinfo", "utility", "Server card: members, channels, boosts, features", |c| serverinfo(c).boxed())
.aliases(&["si", "guildinfo", "server"]).guild_only(),
Command::new("channelinfo", "utility", "Channel card: type, topic, slowmode, permissions", |c| channelinfo(c).boxed())
.aliases(&["ci", "channel"]).usage("[#channel]").opt(Opt::opt("channel", "Defaults to this channel", OptKind::Channel)).guild_only(),
Command::new("roleinfo", "utility", "Role card: colour, members, position and permissions", |c| roleinfo(c).boxed())
.aliases(&["ri"]).usage("<role>").opt(Opt::req("role", "The role to inspect", OptKind::Role)).guild_only(),
Command::new("avatar", "utility", "Someone's avatar in full size (server and global). Reply to a message for its author.", |c| avatar(c).boxed())
.aliases(&["av", "pfp"]).usage("[member]").opt(user()).prefix_only(),
Command::new("banner", "utility", "Someone's profile banner in full size. Reply to a message for its author.", |c| banner(c).boxed())
.aliases(&["bn"]).usage("[member]").opt(user()).prefix_only(),
Command::new("Show Avatar", "apps", "Someone's avatar in full size (server and global).", |c| avatar(c).boxed()).user_menu(),
Command::new("Show Banner", "apps", "Someone's profile banner in full size.", |c| banner(c).boxed()).user_menu(),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn snowflake_dates() {
assert_eq!(created_at((1_704_067_200_000u64 - 1_420_070_400_000) << 22), 1_704_067_200);
}
#[test]
fn permission_names_read_like_discord() {
let names = perm_list(Permissions::MANAGE_GUILD | Permissions::KICK_MEMBERS);
assert!(names.contains(&"Manage Server".to_string()) && names.contains(&"Kick Members".to_string()));
}
#[test]
fn limits_by_boost_level() {
assert_eq!((emoji_limit(0), emoji_limit(3), sticker_limit(2), emoji_limit(9)), (50, 250, 30, 250));
}
}