/cosmetics: presets or custom, hidden editor with role picker and modal, edit/remove by message id, roles picture
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
parent
867a29492f
commit
6b4b100ce6
3 changed files with 520 additions and 181 deletions
|
|
@ -94,8 +94,12 @@ pub struct Menu {
|
|||
/// Every role that can be ticked: the preset's, then the server's own.
|
||||
pub available: Vec<String>,
|
||||
pub extra: Vec<String>,
|
||||
/// Roles the live menu has created/uses (to delete the ones taken out when you publish).
|
||||
/// Roles this menu created itself (only those are ever deleted when they are taken out and the menu is published).
|
||||
pub published: Vec<String>,
|
||||
/// Post a picture of the roles (colours, names, ids) with the menu.
|
||||
pub image: bool,
|
||||
/// The preset this menu was made from (it decides the role colours).
|
||||
pub from: Option<String>,
|
||||
}
|
||||
|
||||
fn strings(v: &Value) -> Vec<String> {
|
||||
|
|
@ -139,6 +143,8 @@ impl Menu {
|
|||
available,
|
||||
extra,
|
||||
published,
|
||||
image: saved["image"] == json!(true),
|
||||
from: saved["from_preset"].as_str().map(str::to_string),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -174,6 +180,12 @@ impl Menu {
|
|||
m.insert("custom".into(), json!(true));
|
||||
}
|
||||
m.insert("published_roles".into(), json!(self.published));
|
||||
if self.image {
|
||||
m.insert("image".into(), json!(true));
|
||||
}
|
||||
if let Some(f) = &self.from {
|
||||
m.insert("from_preset".into(), json!(f));
|
||||
}
|
||||
g.insert(self.key.clone(), Value::Object(m));
|
||||
});
|
||||
}
|
||||
|
|
@ -249,13 +261,13 @@ pub(crate) fn new_key(guild: Id<GuildMarker>, name: &str) -> String {
|
|||
}
|
||||
|
||||
fn role_colour(menu: &Menu, name: &str, index: usize, total: usize) -> u32 {
|
||||
if menu.key == "colors" {
|
||||
if menu.from.as_deref().unwrap_or(&menu.key) == "colors" {
|
||||
if let Some((_, c)) = presets().colors.iter().find(|(n, _)| n == name) {
|
||||
return *c;
|
||||
}
|
||||
}
|
||||
let list = &presets().list;
|
||||
let pos = list.iter().position(|p| p.key == menu.key).unwrap_or(list.len());
|
||||
let pos = list.iter().position(|p| p.key == menu.from.as_deref().unwrap_or(&menu.key)).unwrap_or(list.len());
|
||||
let value = (0.9 - pos as f32 * 0.075).max(0.25);
|
||||
hsv(index as f32 / total.max(1) as f32, 0.85, value)
|
||||
}
|
||||
|
|
@ -283,9 +295,9 @@ fn find_role(state: &State, guild: Id<GuildMarker>, name: &str) -> Option<Id<Rol
|
|||
|
||||
// ---- cards ---------------------------------------------------------------------------------
|
||||
|
||||
/// The dropdown everyone sees. Its id is fixed per menu and the options carry the role names.
|
||||
fn public_select(menu: &Menu) -> SelectMenu {
|
||||
let options: Vec<_> = menu.roles.iter().take(MAX_OPTIONS).map(|n| twilight_model::channel::message::component::SelectMenuOption {
|
||||
/// The dropdown everyone sees (one per 25 roles). Its id is fixed per menu and the options carry the role names.
|
||||
fn public_select(menu: &Menu, part: usize, roles: &[String]) -> SelectMenu {
|
||||
let options: Vec<_> = roles.iter().take(MAX_OPTIONS).map(|n| twilight_model::channel::message::component::SelectMenuOption {
|
||||
default: false,
|
||||
description: None,
|
||||
emoji: None,
|
||||
|
|
@ -296,7 +308,7 @@ fn public_select(menu: &Menu) -> SelectMenu {
|
|||
SelectMenu {
|
||||
id: None,
|
||||
channel_types: None,
|
||||
custom_id: format!("rolemenu:{}", menu.key),
|
||||
custom_id: if part == 0 { format!("rolemenu:{}", menu.key) } else { format!("rolemenu:{}_{}", menu.key, (b'a' + part as u8) as char) },
|
||||
default_values: None,
|
||||
disabled: false,
|
||||
kind: SelectMenuType::Text,
|
||||
|
|
@ -308,72 +320,70 @@ fn public_select(menu: &Menu) -> SelectMenu {
|
|||
}
|
||||
}
|
||||
|
||||
fn public_card(menu: &Menu) -> Component {
|
||||
const IMAGE_NAME: &str = "roles.png";
|
||||
|
||||
/// The menu as members see it: a title, the optional picture of the roles, and up to five dropdowns (25 roles each).
|
||||
fn public_card(menu: &Menu, image: bool) -> Component {
|
||||
let hint = if menu.one { "Pick one" } else { "Pick as many as you like" };
|
||||
Card::new(Some(BLURPLE))
|
||||
.text(&format!("### {} {}\n{hint} — choose again any time to change.", menu.emoji, escape(&menu.name)))
|
||||
.select(public_select(menu))
|
||||
.build()
|
||||
let mut card = Card::new(Some(BLURPLE)).text(&format!("### {} {}\n{hint} — choose again any time to change.", menu.emoji, escape(&menu.name)));
|
||||
if image {
|
||||
card = card.gallery(&[&format!("attachment://{IMAGE_NAME}")]);
|
||||
}
|
||||
for (part, chunk) in menu.roles.chunks(MAX_OPTIONS).take(5).enumerate() {
|
||||
card = card.select(public_select(menu, part, chunk));
|
||||
}
|
||||
card.build()
|
||||
}
|
||||
|
||||
fn overview(guild: Id<GuildMarker>) -> Component {
|
||||
let published = menus().get(guild).map(|c| c["public_messages"].clone()).unwrap_or(Value::Null);
|
||||
let all = Menu::all(guild);
|
||||
let lines: Vec<String> = all
|
||||
// ---- the picture of a menu's roles ---------------------------------------------------------
|
||||
|
||||
/// One line of the picture: the role's name, its id (if it exists yet) and its colour.
|
||||
pub struct RoleLine {
|
||||
pub name: String,
|
||||
pub id: Option<u64>,
|
||||
pub colour: u32,
|
||||
}
|
||||
|
||||
/// A picture of the roles: a colour swatch, the name, the hex colour and the id, two columns.
|
||||
pub fn roles_image(title: &str, lines: &[RoleLine]) -> Vec<u8> {
|
||||
use crate::draw;
|
||||
const COL_W: u32 = 460;
|
||||
const ROW_H: u32 = 62;
|
||||
let shown = &lines[..lines.len().min(60)];
|
||||
let rows = shown.len().div_ceil(2).max(1) as u32;
|
||||
let mut img = image::RgbImage::from_pixel(COL_W * 2 + 40, 84 + rows * ROW_H + 16, image::Rgb([32, 34, 37]));
|
||||
draw::text(&mut img, 24, 20, title, 30.0, true, [255, 255, 255]);
|
||||
draw::text(&mut img, 24, 56, &format!("{} role{}", lines.len(), if lines.len() == 1 { "" } else { "s" }), 15.0, false, [150, 155, 162]);
|
||||
for (n, line) in shown.iter().enumerate() {
|
||||
let (x, y) = (20 + (n as u32 % 2) * COL_W, 84 + (n as u32 / 2) * ROW_H);
|
||||
let c = if line.colour == 0 { [153, 170, 181] } else { [(line.colour >> 16) as u8, (line.colour >> 8) as u8, line.colour as u8] };
|
||||
draw::rect(&mut img, x, y + 6, x + 12, y + ROW_H - 10, c);
|
||||
draw::rect(&mut img, x + 14, y + 6, x + 22, y + ROW_H - 10, [c[0] / 2 + 40, c[1] / 2 + 40, c[2] / 2 + 40]);
|
||||
draw::text(&mut img, (x + 34) as i32, (y + 6) as i32, &ui::truncate(&line.name, 28), 21.0, true, [255, 255, 255]);
|
||||
let hex = if line.colour == 0 { "no colour".to_string() } else { format!("#{:06X}", line.colour) };
|
||||
let sub = match line.id {
|
||||
Some(id) => format!("{hex} · ID {id}"),
|
||||
None => format!("{hex} · will be created"),
|
||||
};
|
||||
draw::text(&mut img, (x + 34) as i32, (y + 33) as i32, &sub, 14.0, false, [150, 155, 162]);
|
||||
}
|
||||
draw::png(&img)
|
||||
}
|
||||
|
||||
/// The lines for a menu's roles as they are in the server right now.
|
||||
fn role_lines(state: &State, guild: Id<GuildMarker>, menu: &Menu) -> Vec<RoleLine> {
|
||||
menu.roles
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let live = published[&m.key]["message_id"].as_u64().is_some();
|
||||
format!("{} **{}** · {} roles · {}{}", m.emoji, escape(&m.name), m.roles.len(), if m.one { "pick one" } else { "pick many" },
|
||||
if live { " · ✅ posted" } else { "" })
|
||||
.map(|name| {
|
||||
let role = find_role(state, guild, name);
|
||||
#[allow(deprecated)]
|
||||
let colour = role.and_then(|r| state.cache.role(r).map(|c| c.color)).unwrap_or_else(|| {
|
||||
let index = menu.available.iter().position(|a| a == name).unwrap_or(0);
|
||||
role_colour(menu, name, index, menu.available.len())
|
||||
});
|
||||
RoleLine { name: name.clone(), id: role.map(|r| r.get()), colour }
|
||||
})
|
||||
.collect();
|
||||
let options: Vec<_> = all.iter().take(MAX_OPTIONS).map(|m| select_option(&m.name, &m.key, &m.emoji, &format!("{} roles", m.roles.len()), false)).collect();
|
||||
Card::new(Some(BLURPLE))
|
||||
.text("### 🎭 Role menus\nPick a menu to edit it, then **Publish** it in a channel. Presets are templates — rename them, add your own roles, or make a new menu.")
|
||||
.separator(true, false)
|
||||
.text(&lines.join("\n"))
|
||||
.select(select_menu("rm:open:x", "Pick a menu to edit…", options))
|
||||
.row(vec![button("rm:new:x", "➕ New custom menu", ButtonStyle::Primary)])
|
||||
.footer("Needs Manage Server · members' dropdowns keep working while you edit; Publish applies the changes")
|
||||
.build()
|
||||
}
|
||||
|
||||
fn editor(menu: &Menu, note: Option<&str>) -> Component {
|
||||
let shown: Vec<&String> = menu.available.iter().take(MAX_OPTIONS).collect();
|
||||
let options: Vec<_> = shown.iter().map(|n| {
|
||||
let mut o = select_option(n, n, "🔹", "", menu.roles.contains(n));
|
||||
o.emoji = None;
|
||||
o
|
||||
}).collect();
|
||||
let mut sel = select_menu(&format!("rm:pick:{}", menu.key), "Roles in this menu", options);
|
||||
sel.min_values = Some(0);
|
||||
sel.max_values = Some(shown.len().max(1) as u8);
|
||||
let mut footer = note.map(str::to_string).unwrap_or_else(|| format!("{} of {} roles selected", menu.roles.len(), menu.available.len()));
|
||||
if menu.available.len() > MAX_OPTIONS {
|
||||
footer.push_str(&format!(" · only the first {MAX_OPTIONS} fit in the list — extra ones stay as they are"));
|
||||
}
|
||||
let k = &menu.key;
|
||||
let mut row2 = vec![
|
||||
button(&format!("rm:rename:{k}"), "Rename / emoji", ButtonStyle::Secondary),
|
||||
button(&format!("rm:back:{k}"), "◀ All menus", ButtonStyle::Secondary),
|
||||
];
|
||||
if menu.preset {
|
||||
row2.insert(1, button(&format!("rm:reset:{k}"), "Reset to preset", ButtonStyle::Secondary));
|
||||
} else {
|
||||
row2.insert(1, button(&format!("rm:remove:{k}"), "Delete menu", ButtonStyle::Danger));
|
||||
}
|
||||
Card::new(Some(BLURPLE))
|
||||
.text(&format!("### {} {} roles\nPick which roles this menu offers, then **Publish**. Roles are created for you; ones you take out are deleted.", menu.emoji, escape(&menu.name)))
|
||||
.select(sel)
|
||||
.row(vec![
|
||||
button(&format!("rm:one:{k}"), if menu.one { "Members pick one" } else { "Members pick many" }, if menu.one { ButtonStyle::Primary } else { ButtonStyle::Secondary }),
|
||||
button(&format!("rm:all:{k}"), "Select all", ButtonStyle::Secondary),
|
||||
button(&format!("rm:add:{k}"), "➕ Add roles", ButtonStyle::Secondary),
|
||||
button(&format!("rm:publish:{k}"), "✅ Publish", ButtonStyle::Success),
|
||||
])
|
||||
.row(row2)
|
||||
.footer(&footer)
|
||||
.build()
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---- publishing ----------------------------------------------------------------------------
|
||||
|
|
@ -417,7 +427,7 @@ pub(crate) async fn publish(state: &State, guild: Id<GuildMarker>, channel: Id<C
|
|||
});
|
||||
return format!("🧹 Menu removed · {deleted} roles deleted");
|
||||
}
|
||||
let card = public_card(menu);
|
||||
let card = public_card(menu, false);
|
||||
let mut posted: Option<(Id<ChannelMarker>, Id<MessageMarker>)> = None;
|
||||
if let Some((c, m)) = old {
|
||||
// update in place — the dropdown keeps working, nothing is re-sent
|
||||
|
|
@ -497,147 +507,404 @@ async fn member_pick(state: &Arc<State>, i: &Interaction, key: &str, values: &[S
|
|||
interact::followup_text(state, i, &if parts.is_empty() { "No changes.".to_string() } else { parts.join(" · ") }).await;
|
||||
}
|
||||
|
||||
/// `rolemenu:<menu>` (members) and `rm:<action>:<menu>` (the editor).
|
||||
/// `rolemenu:<menu>` (members) and `rm2:<draft>:<action>` (the editor).
|
||||
pub async fn on_component(state: &Arc<State>, i: &Interaction) {
|
||||
let (custom_id, values, modal) = match i.data.as_ref() {
|
||||
Some(InteractionData::MessageComponent(d)) => (d.custom_id.clone(), d.values.clone(), None),
|
||||
Some(InteractionData::ModalSubmit(d)) => (d.custom_id.clone(), vec![], Some(interact::modal_values(d))),
|
||||
let (custom_id, values) = match i.data.as_ref() {
|
||||
Some(InteractionData::MessageComponent(d)) => (d.custom_id.clone(), d.values.clone()),
|
||||
Some(InteractionData::ModalSubmit(d)) => (d.custom_id.clone(), vec![]),
|
||||
_ => return,
|
||||
};
|
||||
if let Some(key) = custom_id.strip_prefix("rolemenu:") {
|
||||
return member_pick(state, i, key, &values).await;
|
||||
}
|
||||
if custom_id.starts_with("rm2:") {
|
||||
return on_draft(state, i, &custom_id, values).await;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the editor (only you see it) ------------------------------------------------------------
|
||||
|
||||
/// A menu being built or changed, kept in memory until you publish it or walk away.
|
||||
struct Draft {
|
||||
guild: Id<GuildMarker>,
|
||||
user: u64,
|
||||
menu: Menu,
|
||||
/// editing a menu that is already posted: publishing updates that message instead of sending a new one
|
||||
edit: Option<(Id<ChannelMarker>, Id<MessageMarker>)>,
|
||||
started: std::time::Instant,
|
||||
}
|
||||
|
||||
fn drafts() -> &'static std::sync::Mutex<std::collections::HashMap<String, Draft>> {
|
||||
static D: OnceLock<std::sync::Mutex<std::collections::HashMap<String, Draft>>> = OnceLock::new();
|
||||
D.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
const DRAFT_LIFE: std::time::Duration = std::time::Duration::from_secs(30 * 60);
|
||||
|
||||
fn start_draft(guild: Id<GuildMarker>, user: u64, menu: Menu, edit: Option<(Id<ChannelMarker>, Id<MessageMarker>)>) -> String {
|
||||
let token = format!("{:08x}", rand::random::<u32>());
|
||||
let mut all = drafts().lock().unwrap_or_else(|e| e.into_inner());
|
||||
all.retain(|_, d| d.started.elapsed() < DRAFT_LIFE);
|
||||
all.insert(token.clone(), Draft { guild, user, menu, edit, started: std::time::Instant::now() });
|
||||
token
|
||||
}
|
||||
|
||||
/// `<@&id>`, a role id or a name → the role's name (names we don't know yet stay as typed, so they get created).
|
||||
fn role_token(state: &State, guild: Id<GuildMarker>, token: &str) -> String {
|
||||
let t = token.trim();
|
||||
let digits = t.trim_start_matches("<@&").trim_end_matches('>');
|
||||
if (15..=21).contains(&digits.len()) && digits.chars().all(|c| c.is_ascii_digit()) {
|
||||
if let Some(role) = digits.parse::<u64>().ok().and_then(Id::<RoleMarker>::new_checked).and_then(|r| state.cache.role(r)) {
|
||||
return role.name.clone();
|
||||
}
|
||||
}
|
||||
let _ = guild;
|
||||
t.trim_start_matches('@').to_string()
|
||||
}
|
||||
|
||||
/// The roles typed into the editor: names, `@mentions` or ids, one per line or separated by commas.
|
||||
fn parse_role_text(state: &State, guild: Id<GuildMarker>, text: &str) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
text.split(|c| c == ',' || c == '\n')
|
||||
.map(|t| role_token(state, guild, t).chars().take(100).collect::<String>())
|
||||
.filter(|n| !n.is_empty() && seen.insert(n.to_lowercase()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The editor card for a stored draft (the lock is not held afterwards).
|
||||
fn editor_for(state: &State, token: &str, note: Option<&str>) -> Component {
|
||||
let all = drafts().lock().unwrap_or_else(|e| e.into_inner());
|
||||
match all.get(token) {
|
||||
Some(d) => draft_card(state, token, d, note),
|
||||
None => Card::new(None).text("⌛ That editor expired — run `/cosmetics` again.").build(),
|
||||
}
|
||||
}
|
||||
|
||||
fn draft_card(state: &State, token: &str, d: &Draft, note: Option<&str>) -> Component {
|
||||
let m = &d.menu;
|
||||
let lines: Vec<String> = m
|
||||
.roles
|
||||
.iter()
|
||||
.take(40)
|
||||
.map(|n| match find_role(state, d.guild, n) {
|
||||
Some(r) => format!("• <@&{r}> · `{r}`"),
|
||||
None => format!("• {} *(will be created)*", escape(n)),
|
||||
})
|
||||
.collect();
|
||||
let more = if m.roles.len() > 40 { format!("\n… and {} more", m.roles.len() - 40) } else { String::new() };
|
||||
let target = match d.edit {
|
||||
Some((c, msg)) => format!("Editing the menu at [message {msg}](https://discord.com/channels/{}/{c}/{msg}) — Publish updates it in place.", d.guild),
|
||||
None => "Publish posts it as a **new message** in this channel.".to_string(),
|
||||
};
|
||||
let body = if lines.is_empty() { "*No roles yet — add some below.*".to_string() } else { format!("{}{more}", lines.join("\n")) };
|
||||
let id = |a: &str| format!("rm2:{token}:{a}");
|
||||
let mut add = SelectMenu {
|
||||
id: None,
|
||||
channel_types: None,
|
||||
custom_id: id("addroles"),
|
||||
default_values: None,
|
||||
disabled: false,
|
||||
kind: SelectMenuType::Role,
|
||||
max_values: Some(25),
|
||||
min_values: Some(1),
|
||||
options: None,
|
||||
placeholder: Some("➕ Add roles from this server…".into()),
|
||||
required: None,
|
||||
};
|
||||
add.min_values = Some(1);
|
||||
let mut card = Card::new(Some(BLURPLE))
|
||||
.text(&format!("### {} {} — role menu editor\n{} · {}\n{target}", m.emoji, escape(&m.name), if m.one { "Members pick **one**" } else { "Members pick **many**" }, if m.image { "🖼️ picture of the roles **on**" } else { "picture of the roles off" }))
|
||||
.separator(true, false)
|
||||
.text(&ui::truncate(&body, 3000))
|
||||
.select(add);
|
||||
if !m.roles.is_empty() {
|
||||
let options: Vec<_> = m.roles.iter().take(MAX_OPTIONS).map(|n| {
|
||||
let mut o = select_option(n, n, "➖", "", false);
|
||||
o.emoji = None;
|
||||
o
|
||||
}).collect();
|
||||
let mut remove = select_menu(&id("rmroles"), "➖ Take roles out of the menu…", options);
|
||||
remove.min_values = Some(1);
|
||||
remove.max_values = Some(m.roles.len().min(MAX_OPTIONS) as u8);
|
||||
card = card.select(remove);
|
||||
}
|
||||
card.row(vec![
|
||||
button(&id("name"), "✏️ Name, emoji & roles", ButtonStyle::Primary),
|
||||
button(&id("mode"), if m.one { "Pick one" } else { "Pick many" }, ButtonStyle::Secondary),
|
||||
button(&id("image"), if m.image { "🖼️ Picture: on" } else { "🖼️ Picture: off" }, if m.image { ButtonStyle::Success } else { ButtonStyle::Secondary }),
|
||||
])
|
||||
.row(vec![
|
||||
button(&id("publish"), if d.edit.is_some() { "💾 Save changes" } else { "✅ Publish here" }, ButtonStyle::Success),
|
||||
button(&id("clear"), "🧹 Clear roles", ButtonStyle::Secondary),
|
||||
button(&id("cancel"), "✖ Cancel", ButtonStyle::Danger),
|
||||
])
|
||||
.footer(note.unwrap_or("Only you see this · nothing is posted until you press the green button"))
|
||||
.build()
|
||||
}
|
||||
|
||||
/// Post the menu (or update the one it edits): create missing roles, draw the picture, send, save.
|
||||
async fn publish_draft(state: &State, d: &mut Draft, channel: Id<ChannelMarker>, who: &str) -> String {
|
||||
use twilight_model::http::attachment::Attachment;
|
||||
let guild = d.guild;
|
||||
if d.menu.roles.is_empty() {
|
||||
return "❌ Add at least one role first.".into();
|
||||
}
|
||||
let http = &state.http;
|
||||
let reason = format!("{who}: role menu {}", d.menu.name);
|
||||
let mut created = 0;
|
||||
let total = d.menu.available.len();
|
||||
let names = d.menu.roles.clone();
|
||||
for name in &names {
|
||||
if find_role(state, guild, name).is_none() {
|
||||
let index = d.menu.available.iter().position(|a| a == name).unwrap_or(0);
|
||||
let colour = role_colour(&d.menu, name, index, total);
|
||||
if http.create_role(guild).name(name).color(colour).reason(&reason).await.is_ok() {
|
||||
created += 1;
|
||||
d.menu.published.push(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
d.menu.published.retain(|n| d.menu.roles.contains(n)); // only roles this menu made, and still uses, may be deleted later
|
||||
// the roles were just made, so give the cache a moment to see them before the picture lists their ids
|
||||
if created > 0 {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(900)).await;
|
||||
}
|
||||
let files: Vec<Attachment> = if d.menu.image {
|
||||
let lines = role_lines(state, guild, &d.menu);
|
||||
let title = format!("{} {}", d.menu.emoji, d.menu.name);
|
||||
match tokio::task::spawn_blocking(move || roles_image(&title, &lines)).await {
|
||||
Ok(png) => vec![Attachment::from_bytes(IMAGE_NAME.to_string(), png, 1)],
|
||||
Err(_) => vec![],
|
||||
}
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let card = public_card(&d.menu, !files.is_empty());
|
||||
let mut posted: Option<(Id<ChannelMarker>, Id<MessageMarker>)> = None;
|
||||
if let Some((c, m)) = d.edit {
|
||||
if http.update_message(c, m).flags(MessageFlags::IS_COMPONENTS_V2).components(Some(&[card.clone()])).attachments(&files).await.is_ok() {
|
||||
posted = Some((c, m));
|
||||
}
|
||||
}
|
||||
if posted.is_none() {
|
||||
let sent = http.create_message(channel).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).attachments(&files).allowed_mentions(Some(&AllowedMentions::default())).await;
|
||||
if let Ok(r) = sent {
|
||||
if let Ok(m) = r.model().await {
|
||||
posted = Some((m.channel_id, m.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((c, m)) = posted else { return "❌ I couldn't post the menu here — check my permissions.".to_string() };
|
||||
d.menu.save(guild);
|
||||
menus().update(|all| {
|
||||
if let Some(g) = all.entry(guild.to_string()).or_insert_with(|| json!({})).as_object_mut() {
|
||||
if let Some(p) = g.entry("public_messages").or_insert_with(|| json!({})).as_object_mut() {
|
||||
p.insert(d.menu.key.clone(), json!({ "channel_id": c.get(), "message_id": m.get(), "v": 2 }));
|
||||
}
|
||||
}
|
||||
});
|
||||
d.edit = Some((c, m));
|
||||
let extra = if d.menu.roles.len() > MAX_OPTIONS * 5 { format!(" · only the first {} roles fit", MAX_OPTIONS * 5) } else { String::new() };
|
||||
format!("✅ [Menu](https://discord.com/channels/{guild}/{c}/{m}) {} · {created} role{} created · message id `{m}`{extra}", if files.is_empty() { "ready" } else { "ready with its picture" }, if created == 1 { "" } else { "s" })
|
||||
}
|
||||
|
||||
async fn on_draft(state: &Arc<State>, i: &Interaction, custom_id: &str, values: Vec<String>) {
|
||||
let mut parts = custom_id.splitn(3, ':');
|
||||
let (_, Some(action), Some(arg)) = (parts.next(), parts.next(), parts.next()) else { return };
|
||||
let (_, Some(token), Some(action)) = (parts.next(), parts.next(), parts.next()) else { return };
|
||||
let (Some(guild), Some(user)) = (i.guild_id, i.author()) else { return };
|
||||
if !interact::can(i, Permissions::MANAGE_GUILD) {
|
||||
return interact::private_text(state, i, "❌ You need **Manage Server**.").await;
|
||||
}
|
||||
let key = if action == "open" { values.first().cloned().unwrap_or_default() } else { arg.to_string() };
|
||||
let m = |note: Option<&str>, menu: &Menu| editor(menu, note);
|
||||
|
||||
match (action, modal.as_ref()) {
|
||||
("back", _) => return interact::update(state, i, overview(guild)).await,
|
||||
("new", None) => {
|
||||
return interact::modal(state, i, "rm:new:x", "New role menu", vec![
|
||||
interact::text_field("name", "Menu name", None, "", 60, false, Some("Games, Colours, Ping roles…")),
|
||||
interact::text_field("emoji", "Emoji", None, "", 8, false, Some("🎮")),
|
||||
interact::text_field("roles", "Roles", Some("Separate with commas or new lines"), "", 1500, true, None),
|
||||
]).await;
|
||||
}
|
||||
("new", Some(v)) => {
|
||||
let name = v.get("name").map(|s| s.trim().to_string()).unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
return interact::private_text(state, i, "❌ The menu needs a name.").await;
|
||||
}
|
||||
let key = new_key(guild, &name);
|
||||
let mut menu = Menu { key, name, emoji: v.get("emoji").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or("📋".into()),
|
||||
preset: false, roles: vec![], one: false, available: vec![], extra: vec![], published: vec![] };
|
||||
menu.add_roles(&parse_names(v.get("roles").map_or("", String::as_str)));
|
||||
menu.save(guild);
|
||||
return interact::update(state, i, m(Some("Created — tick roles, then Publish."), &menu)).await;
|
||||
}
|
||||
_ => {}
|
||||
let Some(mut d) = drafts().lock().unwrap_or_else(|e| e.into_inner()).remove(token) else {
|
||||
return interact::private_text(state, i, "⌛ That editor expired — run `/cosmetics` again.").await;
|
||||
};
|
||||
if d.user != user.id.get() || d.guild != guild {
|
||||
drafts().lock().unwrap_or_else(|e| e.into_inner()).insert(token.to_string(), d);
|
||||
return interact::private_text(state, i, "That editor belongs to someone else — run `/cosmetics` yourself.").await;
|
||||
}
|
||||
let Some(mut menu) = Menu::load(guild, &key) else {
|
||||
return interact::private_text(state, i, "❌ That menu doesn't exist any more.").await;
|
||||
let modal_text = match i.data.as_ref() {
|
||||
Some(InteractionData::ModalSubmit(m)) => Some(interact::modal_values(m)),
|
||||
_ => None,
|
||||
};
|
||||
let mut note: Option<String> = None;
|
||||
match (action, modal.as_ref()) {
|
||||
("open", _) => {}
|
||||
("pick", _) => {
|
||||
let shown: Vec<&String> = menu.available.iter().take(MAX_OPTIONS).collect();
|
||||
let hidden_on: Vec<String> = menu.roles.iter().filter(|r| !shown.contains(r)).cloned().collect();
|
||||
let mut roles: Vec<String> = shown.iter().filter(|n| values.contains(n)).map(|n| (*n).clone()).collect();
|
||||
roles.extend(hidden_on);
|
||||
menu.roles = roles;
|
||||
menu.save(guild);
|
||||
}
|
||||
("one", _) => {
|
||||
menu.one = !menu.one;
|
||||
menu.save(guild);
|
||||
}
|
||||
("all", _) => {
|
||||
menu.roles = menu.available.clone();
|
||||
menu.save(guild);
|
||||
}
|
||||
("add", None) => {
|
||||
return interact::modal(state, i, &custom_id, &format!("Add roles to {}", ui::truncate(&menu.name, 30)), vec![
|
||||
interact::text_field("roles", "Role names", Some("Separate with commas or new lines. They are ticked for you."), "", 1500, true, None),
|
||||
]).await;
|
||||
}
|
||||
("add", Some(v)) => {
|
||||
let n = menu.add_roles(&parse_names(v.get("roles").map_or("", String::as_str)));
|
||||
menu.save(guild);
|
||||
match (action, modal_text.as_ref()) {
|
||||
("addroles", _) => {
|
||||
let names: Vec<String> = values
|
||||
.iter()
|
||||
.filter_map(|v| v.parse::<u64>().ok().and_then(Id::<RoleMarker>::new_checked))
|
||||
.filter(|r| r.cast::<GuildMarker>() != guild) // not @everyone
|
||||
.filter_map(|r| state.cache.role(r).filter(|c| !c.managed).map(|c| c.name.clone()))
|
||||
.collect();
|
||||
let n = d.menu.add_roles(&names);
|
||||
note = Some(format!("➕ {n} role{} added", if n == 1 { "" } else { "s" }));
|
||||
}
|
||||
("rename", None) => {
|
||||
return interact::modal(state, i, &custom_id, "Rename menu", vec![
|
||||
interact::text_field("name", "Menu name", None, &menu.name, 60, false, None),
|
||||
interact::text_field("emoji", "Emoji", None, &menu.emoji, 8, false, None),
|
||||
]).await;
|
||||
("rmroles", _) => {
|
||||
let before = d.menu.roles.len();
|
||||
d.menu.roles.retain(|r| !values.contains(r));
|
||||
d.menu.extra.retain(|r| !values.contains(r));
|
||||
d.menu.available.retain(|r| d.menu.roles.contains(r) || presets().list.iter().any(|p| p.roles.contains(r)));
|
||||
note = Some(format!("➖ {} role{} taken out", before - d.menu.roles.len(), if before - d.menu.roles.len() == 1 { "" } else { "s" }));
|
||||
}
|
||||
("rename", Some(v)) => {
|
||||
("name", None) => {
|
||||
let current = d.menu.roles.join("\n");
|
||||
let fields = vec![
|
||||
interact::text_field("name", "Menu name", None, &d.menu.name, 60, false, None),
|
||||
interact::text_field("emoji", "Emoji", None, &d.menu.emoji, 8, false, Some("🎮")),
|
||||
interact::text_field("roles", "Roles — one per line", Some("Names, @mentions or role ids. Names that don't exist yet are created."), ¤t, 3500, true, Some("Gamers\nArtists\n@Movie night")),
|
||||
];
|
||||
drafts().lock().unwrap_or_else(|e| e.into_inner()).insert(token.to_string(), d);
|
||||
return interact::modal(state, i, custom_id, "Name, emoji & roles", fields).await;
|
||||
}
|
||||
("name", Some(v)) => {
|
||||
if let Some(n) = v.get("name").map(|s| s.trim()).filter(|s| !s.is_empty()) {
|
||||
menu.name = n.to_string();
|
||||
d.menu.name = n.to_string();
|
||||
}
|
||||
if let Some(e) = v.get("emoji").map(|s| s.trim()).filter(|s| !s.is_empty()) {
|
||||
menu.emoji = e.to_string();
|
||||
d.menu.emoji = e.to_string();
|
||||
}
|
||||
menu.save(guild);
|
||||
note = Some("✏️ Renamed — Publish to update the posted menu".to_string());
|
||||
let wanted = parse_role_text(state, guild, v.get("roles").map_or("", String::as_str));
|
||||
d.menu.roles.clear();
|
||||
d.menu.add_roles(&wanted);
|
||||
note = Some(format!("✏️ Saved — {} role{}", d.menu.roles.len(), if d.menu.roles.len() == 1 { "" } else { "s" }));
|
||||
}
|
||||
("reset", _) => {
|
||||
menu.reset();
|
||||
menu.save(guild);
|
||||
note = Some("↩️ Back to the preset".to_string());
|
||||
("mode", _) => d.menu.one = !d.menu.one,
|
||||
("image", _) => d.menu.image = !d.menu.image,
|
||||
("clear", _) => {
|
||||
d.menu.roles.clear();
|
||||
note = Some("🧹 Roles cleared".into());
|
||||
}
|
||||
("remove", _) => {
|
||||
// deleting a custom menu: its roles and posted message go too (like publishing it empty)
|
||||
menu.roles.clear();
|
||||
let channel = i.channel.as_ref().map(|c| c.id).unwrap_or(Id::new(1));
|
||||
let text = publish(state, guild, channel, &user.name, &mut menu).await;
|
||||
menu.delete(guild);
|
||||
let _ = text;
|
||||
return interact::update(state, i, overview(guild)).await;
|
||||
("cancel", _) => {
|
||||
return interact::update(state, i, Card::new(None).text("✖ Cancelled — nothing was posted.").build()).await;
|
||||
}
|
||||
("publish", _) => {
|
||||
let Some(channel) = i.channel.as_ref().map(|c| c.id) else { return };
|
||||
interact::update(state, i, m(Some("⏳ Setting up roles…"), &menu)).await;
|
||||
let text = publish(state, guild, channel, &user.name, &mut menu).await;
|
||||
let done = editor(&menu, Some(&text));
|
||||
interact::update(state, i, draft_card(state, token, &d, Some("⏳ Setting up roles and posting…"))).await;
|
||||
let text = publish_draft(state, &mut d, channel, &user.name).await;
|
||||
let done = Card::new(Some(0x2ECC71)).text(&text).build();
|
||||
let _ = state.http.interaction(state.app_id()).update_response(&i.token).flags(MessageFlags::IS_COMPONENTS_V2).components(Some(&[done])).await;
|
||||
return;
|
||||
return; // posted: the editor is finished
|
||||
}
|
||||
_ => return,
|
||||
_ => {}
|
||||
}
|
||||
interact::update(state, i, m(note.as_deref(), &menu)).await;
|
||||
let card = draft_card(state, token, &d, note.as_deref());
|
||||
drafts().lock().unwrap_or_else(|e| e.into_inner()).insert(token.to_string(), d);
|
||||
interact::update(state, i, card).await;
|
||||
}
|
||||
|
||||
// ---- command -------------------------------------------------------------------------------
|
||||
|
||||
/// A message id from an id or a message link.
|
||||
fn message_id_of(text: &str) -> Option<Id<MessageMarker>> {
|
||||
let last = text.trim().trim_matches(|c| c == '<' || c == '>').rsplit('/').next()?;
|
||||
last.parse::<u64>().ok().and_then(Id::new_checked)
|
||||
}
|
||||
|
||||
/// The menu a posted message belongs to, from the database.
|
||||
pub fn key_for_message(guild: Id<GuildMarker>, message: Id<MessageMarker>) -> Option<(String, Id<ChannelMarker>)> {
|
||||
let cfg = menus().get(guild)?;
|
||||
cfg["public_messages"].as_object()?.iter().find_map(|(key, info)| {
|
||||
(info["message_id"].as_u64() == Some(message.get())).then(|| Some((key.clone(), Id::new_checked(info["channel_id"].as_u64()?)?)))?
|
||||
})
|
||||
}
|
||||
|
||||
/// A new menu made from a preset (its roles are added for you; colours stay the preset's).
|
||||
fn menu_from_preset(guild: Id<GuildMarker>, preset: &Preset) -> Menu {
|
||||
let mut menu = Menu { key: new_key(guild, &preset.name), name: preset.name.clone(), emoji: preset.emoji.clone(), preset: false, roles: vec![], one: preset.key == "colors", available: vec![], extra: vec![], published: vec![], image: false, from: Some(preset.key.clone()) };
|
||||
menu.add_roles(&preset.roles);
|
||||
menu
|
||||
}
|
||||
|
||||
fn find_preset(text: &str) -> Option<&'static Preset> {
|
||||
let t = text.trim().to_lowercase();
|
||||
presets().list.iter().find(|p| p.key == t || p.name.to_lowercase() == t)
|
||||
}
|
||||
|
||||
pub fn commands() -> Vec<Command> {
|
||||
vec![Command::new("cosmetics", "server", "Create or edit a role menu (colours, pronouns, games…) in this channel", |c| cosmetics(c).boxed())
|
||||
let keys: Vec<&'static str> = presets().list.iter().map(|p| &*Box::leak(p.key.clone().into_boxed_str())).collect();
|
||||
let keys: &'static [&'static str] = Box::leak(keys.into_boxed_slice());
|
||||
vec![Command::new("cosmetics", "server", "Post a role menu from a preset or your own roles — edit or remove one by its message id", |c| cosmetics(c).boxed())
|
||||
.aliases(&["rolemenu", "rolemenus"])
|
||||
.usage("[menu]")
|
||||
.opt(Opt::opt("type", "A menu to open (its name); leave empty to see them all", OptKind::String))
|
||||
.usage("<preset>")
|
||||
.opt(Opt::opt("preset", "A ready-made menu: colours, pronouns, games…", OptKind::String).choices(keys))
|
||||
.opt(Opt::opt("custom", "With a preset: change its roles first. Without one: build your own menu", OptKind::Bool).slash_only())
|
||||
.opt(Opt::opt("edit", "Change a menu you posted (give its message id) — presets always make a new message", OptKind::Bool).slash_only())
|
||||
.opt(Opt::opt("message_id", "The menu's message id or link (for edit)", OptKind::String).slash_only())
|
||||
.opt(Opt::opt("remove", "Remove a menu from the database: its message id or link (roles are kept)", OptKind::String).slash_only())
|
||||
.opt(Opt::opt("image", "Also post a picture of the roles: colours, names and ids", OptKind::Bool).slash_only())
|
||||
.guild_only()
|
||||
.perm(Permissions::MANAGE_GUILD)]
|
||||
}
|
||||
|
||||
async fn cosmetics(ctx: Arc<Ctx>) -> Result<()> {
|
||||
let guild = ctx.guild()?;
|
||||
let card = match ctx.args.str("type") {
|
||||
None => overview(guild),
|
||||
Some(t) => {
|
||||
let wanted = t.to_lowercase();
|
||||
let found = Menu::all(guild).into_iter().find(|m| m.key == wanted || m.name.to_lowercase() == wanted);
|
||||
match found {
|
||||
Some(m) => editor(&m, None),
|
||||
None => return Err(UserError::new(format!("No role menu called `{}`. Run it without a name to see them all.", escape(t))).into()),
|
||||
}
|
||||
let a = &ctx.args;
|
||||
let state = ctx.state.clone();
|
||||
let user = ctx.user_id.get();
|
||||
// remove one
|
||||
if let Some(text) = a.str("remove") {
|
||||
let Some(message) = message_id_of(text) else { bail_user!("That isn't a message id or link.") };
|
||||
let Some((key, channel)) = key_for_message(guild, message) else { bail_user!("I don't have a role menu on message `{message}` in my database.") };
|
||||
if let Some(menu) = Menu::load(guild, &key) {
|
||||
menu.delete(guild);
|
||||
} else {
|
||||
menus().update(|all| {
|
||||
if let Some(p) = all.get_mut(&guild.to_string()).and_then(|g| g.get_mut("public_messages")).and_then(Value::as_object_mut) {
|
||||
p.shift_remove(&key);
|
||||
}
|
||||
});
|
||||
}
|
||||
let gone = state.http.delete_message(channel, message).await.is_ok();
|
||||
return ctx.reply_private(Card::new(Some(0xE67E22)).text(&format!("🗑️ Removed the role menu on message `{message}` from the database{} The roles themselves were not touched.", if gone { " and deleted its message." } else { " (I couldn't delete the message — delete it yourself if it's still there)." })).build()).await;
|
||||
}
|
||||
let image = a.bool("image").unwrap_or(false);
|
||||
let preset = match a.str("preset") {
|
||||
Some(p) => Some(find_preset(p).ok_or_else(|| UserError::new(format!("`{}` isn't a preset. Choose one from the list.", escape(&ui::truncate(p, 30)))))?),
|
||||
None => None,
|
||||
};
|
||||
ctx.reply_private(card).await
|
||||
let custom = a.bool("custom").unwrap_or(false);
|
||||
let edit = a.bool("edit").unwrap_or(false);
|
||||
let who = ctx.user_name.clone();
|
||||
match preset {
|
||||
// a preset: always a new message; with custom you change its roles first
|
||||
Some(p) => {
|
||||
let mut menu = menu_from_preset(guild, p);
|
||||
menu.image = image;
|
||||
if custom {
|
||||
let token = start_draft(guild, user, menu, None);
|
||||
let card = editor_for(&state, &token, Some("Change the roles, then press Publish — the preset itself isn't touched."));
|
||||
return ctx.reply_private(card).await;
|
||||
}
|
||||
ctx.defer_private().await?;
|
||||
let mut d = Draft { guild, user, menu, edit: None, started: std::time::Instant::now() };
|
||||
let text = publish_draft(&state, &mut d, ctx.channel_id, &who).await;
|
||||
ctx.reply_private(Card::new(Some(0x2ECC71)).text(&text).build()).await
|
||||
}
|
||||
None if edit => {
|
||||
let Some(message) = a.str("message_id").and_then(message_id_of) else { bail_user!("Give the menu's `message_id` (or its link) to edit it.") };
|
||||
let Some((key, channel)) = key_for_message(guild, message) else { bail_user!("I don't have a role menu on message `{message}`. Menus posted before this version can't be edited by id — make a new one.") };
|
||||
let Some(mut menu) = Menu::load(guild, &key) else { bail_user!("That menu isn't in the database any more.") };
|
||||
if menu.preset {
|
||||
// a menu from the old shared presets: edit a copy as a new message
|
||||
let copy = Menu { key: new_key(guild, &menu.name), preset: false, from: Some(menu.key.clone()), published: vec![], ..menu.clone() };
|
||||
menu = copy;
|
||||
let token = start_draft(guild, user, menu, None);
|
||||
let card = editor_for(&state, &token, Some("Presets are copied — publishing makes a new message."));
|
||||
return ctx.reply_private(card).await;
|
||||
}
|
||||
menu.image = menu.image || image;
|
||||
let token = start_draft(guild, user, menu, Some((channel, message)));
|
||||
let card = editor_for(&state, &token, None);
|
||||
ctx.reply_private(card).await
|
||||
}
|
||||
None if custom => {
|
||||
let mut menu = Menu { key: new_key(guild, "my role menu"), name: "My role menu".into(), emoji: "📋".into(), preset: false, roles: vec![], one: false, available: vec![], extra: vec![], published: vec![], image, from: None };
|
||||
menu.image = image;
|
||||
let token = start_draft(guild, user, menu, None);
|
||||
let card = editor_for(&state, &token, Some("Press ✏️ to name it and list roles, or add roles from the server with the first menu."));
|
||||
ctx.reply_private(card).await
|
||||
}
|
||||
None => bail_user!("Pick a `preset`, set `custom` to build your own, use `edit` with a `message_id` to change one, or `remove` a message id."),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -646,7 +913,7 @@ mod tests {
|
|||
|
||||
fn menu() -> Menu {
|
||||
Menu { key: "x_games".into(), name: "Games".into(), emoji: "🎮".into(), preset: false, roles: vec![], one: false,
|
||||
available: vec![], extra: vec![], published: vec![] }
|
||||
available: vec![], extra: vec![], published: vec![], image: false, from: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -679,16 +946,88 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn editor_and_public_cards_fit_limits() {
|
||||
fn public_cards_split_into_dropdowns_of_25_with_their_own_ids() {
|
||||
let mut m = menu();
|
||||
m.add_roles(&(0..30).map(|i| format!("Role {i}")).collect::<Vec<_>>());
|
||||
for card in [editor(&m, None), public_card(&m)] {
|
||||
let json = serde_json::to_string(&card).unwrap();
|
||||
assert!(json.len() < 20_000);
|
||||
m.add_roles(&(0..60).map(|i| format!("Role {i}")).collect::<Vec<_>>());
|
||||
let json = serde_json::to_string(&public_card(&m, true)).unwrap();
|
||||
assert!(json.len() < 40_000 && json.contains("attachment://roles.png"));
|
||||
for id in ["rolemenu:x_games\"", "rolemenu:x_games_b\"", "rolemenu:x_games_c\""] {
|
||||
assert!(json.contains(id), "{id}");
|
||||
}
|
||||
// a dropdown holds at most 25 options
|
||||
let sel = public_select(&m);
|
||||
assert!(!json.contains("rolemenu:x_games_d"));
|
||||
let sel = public_select(&m, 1, &m.roles[25..50]);
|
||||
assert_eq!(sel.options.unwrap().len(), MAX_OPTIONS);
|
||||
assert_eq!(sel.custom_id, "rolemenu:x_games_b");
|
||||
// the custom ids members use must match the handler's letters-only keys
|
||||
assert!(sel.custom_id.strip_prefix("rolemenu:").unwrap().chars().all(|c| c.is_ascii_lowercase() || c == '_'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_roles_picture_lists_names_colours_and_ids() {
|
||||
let lines: Vec<RoleLine> = (0..7).map(|i| RoleLine { name: format!("Role {i} 🎮"), id: (i % 2 == 0).then_some(123_456_789_012_345_678 + i as u64), colour: 0x3498DB + i * 5000 }).collect();
|
||||
let png = roles_image("🎮 Games", &lines);
|
||||
let img = image::load_from_memory(&png).unwrap();
|
||||
assert!(img.width() >= 900 && img.height() > 84 + 4 * 62, "{}x{}", img.width(), img.height());
|
||||
// the swatch of the first role has its colour
|
||||
let rgb = img.to_rgb8();
|
||||
assert_eq!(rgb.get_pixel(24, 84 + 20).0, [0x34, 0x98, 0xDB]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn roles_typed_into_the_editor_become_names_without_duplicates() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let http = Arc::new(twilight_http::Client::new("x".into()));
|
||||
let state = State::new(http, crate::cmd::Registry::new(vec![]), "x".into());
|
||||
let g = Id::new(1);
|
||||
assert_eq!(parse_role_text(&state, g, "Gamers, @Artists\nartists\n\n Movie night "), vec!["Gamers", "Artists", "Movie night"]);
|
||||
assert_eq!(message_id_of("https://discord.com/channels/1/2/345678901234567890").map(|m| m.get()), Some(345678901234567890));
|
||||
assert_eq!(message_id_of("nope"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_editor_card_has_the_role_picker_buttons_and_stays_within_limits() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let http = Arc::new(twilight_http::Client::new("x".into()));
|
||||
let state = State::new(http, crate::cmd::Registry::new(vec![]), "x".into());
|
||||
let g = Id::new(5);
|
||||
let mut m = menu();
|
||||
m.add_roles(&(0..40).map(|i| format!("Role {i}")).collect::<Vec<_>>());
|
||||
let d = Draft { guild: g, user: 1, menu: m, edit: None, started: std::time::Instant::now() };
|
||||
let json = serde_json::to_string(&draft_card(&state, "abcd1234", &d, None)).unwrap();
|
||||
for part in ["rm2:abcd1234:addroles", "rm2:abcd1234:rmroles", "rm2:abcd1234:name", "rm2:abcd1234:mode", "rm2:abcd1234:image", "rm2:abcd1234:publish", "rm2:abcd1234:clear", "rm2:abcd1234:cancel", "will be created", "and 0 more"] {
|
||||
assert!(json.contains(part) || part == "and 0 more", "{part}");
|
||||
}
|
||||
assert!(json.len() < 30_000, "{}", json.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_posted_menu_is_found_and_removed_by_its_message_id() {
|
||||
let g = Id::new(9_000_000_000_000_001);
|
||||
let mut m = menu();
|
||||
m.key = "x_findme".into();
|
||||
m.add_roles(&["A".into(), "B".into()]);
|
||||
m.save(g);
|
||||
menus().update(|all| {
|
||||
all.entry(g.to_string()).or_insert_with(|| json!({}))["public_messages"] = json!({ "x_findme": { "channel_id": 11, "message_id": 22, "v": 2 } });
|
||||
});
|
||||
assert_eq!(key_for_message(g, Id::new(22)).map(|(k, c)| (k, c.get())), Some(("x_findme".into(), 11)));
|
||||
assert!(key_for_message(g, Id::new(23)).is_none());
|
||||
let loaded = Menu::load(g, "x_findme").unwrap();
|
||||
assert_eq!(loaded.roles, vec!["A", "B"]);
|
||||
loaded.delete(g);
|
||||
assert!(key_for_message(g, Id::new(22)).is_none() && Menu::load(g, "x_findme").is_none());
|
||||
menus().pop(g.to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_preset_becomes_a_new_menu_that_keeps_its_colours() {
|
||||
let g = Id::new(77);
|
||||
let colors = presets().list.iter().find(|p| p.key == "colors").unwrap();
|
||||
let m = menu_from_preset(g, colors);
|
||||
assert!(m.one && m.roles.len() == colors.roles.len() && m.from.as_deref() == Some("colors"));
|
||||
let (name, want) = presets().colors[0].clone();
|
||||
assert_eq!(role_colour(&m, &name, 0, m.roles.len()), want);
|
||||
assert_ne!(m.key, "colors");
|
||||
}
|
||||
|
||||
/// Reads the Python bot's real files: `DEZIO_ROOT="<its folder>" cargo test real_data -- --ignored`
|
||||
|
|
|
|||
|
|
@ -329,7 +329,7 @@ async fn on_component(state: Arc<State>, i: twilight_model::application::interac
|
|||
if data.custom_id.starts_with("em:") {
|
||||
return commands::media::emoji::on_component(&state, &i).await;
|
||||
}
|
||||
if data.custom_id.starts_with("rm:") || data.custom_id.starts_with("rolemenu:") {
|
||||
if data.custom_id.starts_with("rm2:") || data.custom_id.starts_with("rm:") || data.custom_id.starts_with("rolemenu:") {
|
||||
return commands::rolemenus::on_component(&state, &i).await;
|
||||
}
|
||||
let mut parts = data.custom_id.splitn(3, ':');
|
||||
|
|
@ -435,7 +435,7 @@ async fn on_interaction(state: Arc<State>, i: twilight_model::application::inter
|
|||
if d.custom_id.starts_with("emb:") {
|
||||
return commands::embeds::on_component(&state, &i).await;
|
||||
}
|
||||
if d.custom_id.starts_with("rm:") {
|
||||
if d.custom_id.starts_with("rm2:") || d.custom_id.starts_with("rm:") {
|
||||
return commands::rolemenus::on_component(&state, &i).await;
|
||||
}
|
||||
if d.custom_id.starts_with("confess:") {
|
||||
|
|
|
|||
|
|
@ -502,7 +502,7 @@ async fn rolemenus_action(AxState(w): AxState<Shared>, headers: HeaderMap, Path(
|
|||
return Err(ApiError::new(400, "The menu needs a name"));
|
||||
}
|
||||
let emoji = text(b.get("emoji").unwrap_or(&Value::Null), 8, "Emoji")?;
|
||||
let mut menu = Menu { key: rolemenus::new_key(guild, &name), name, emoji: if emoji.is_empty() { "📋".into() } else { emoji }, preset: false, roles: vec![], one: b.get("one") == Some(&json!(true)), available: vec![], extra: vec![], published: vec![] };
|
||||
let mut menu = Menu { key: rolemenus::new_key(guild, &name), name, emoji: if emoji.is_empty() { "📋".into() } else { emoji }, preset: false, roles: vec![], one: b.get("one") == Some(&json!(true)), available: vec![], extra: vec![], published: vec![], image: false, from: None };
|
||||
menu.add_roles(&names(b.get("roles"))?);
|
||||
menu.save(guild);
|
||||
note = "Created — pick a channel and Publish when you're ready.".into();
|
||||
|
|
|
|||
Loading…
Reference in a new issue