Dezio/src/emojis.rs
astar76 0416e4eb56 /fm: status line above the picture, with a custom previous icon
The picture's own status is easy to miss, so now playing and last played
are said in text again, using the playing emoji or the new previous icon.

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

91 lines
4.4 KiB
Rust

//! Dezio's own icons, uploaded as application emojis: they belong to the bot, so they work in every server and don't
//! use up a server's emoji slots. The pictures are `assets/emojis/dz_*.png` (their SVG sources sit next to them).
//! At startup [`sync`] uploads any that are missing. Until that has run, or if it fails, buttons keep the plain emoji.
use crate::paths;
use crate::state::State;
use base64::Engine as _;
use std::collections::HashMap;
use std::sync::{OnceLock, RwLock};
use twilight_model::channel::message::EmojiReactionType;
use twilight_model::id::marker::EmojiMarker;
use twilight_model::id::Id;
/// The plain emoji the code uses, and the icon that replaces it.
const ICONS: [(&str, &str); 31] = [
("▶️", "play"), ("⏸️", "pause"), ("⏭️", "skip"), ("⏹️", "stop"), ("🔁", "repeat"), ("🔂", "repeat_one"), ("🔀", "shuffle"), ("📜", "queue"), ("🔉", "vol_down"), ("🔊", "vol_up"),
("🔗", "link"), ("👋", "leave"), ("👑", "heads"), ("🦅", "tails"), ("🃏", "hit"), ("✋", "stand"), ("✖️", "double"), ("🎰", "spin"), ("🔄", "spin"), ("🔴", "red"), ("⚫", "black"), ("🟢", "green"),
("🪙", "coin"), ("✅", "check"), ("❌", "cross"), ("⬆️", "up"), ("⬇️", "down"), ("🏳️", "flag"), ("🚩", "flag"), ("💰", "coin"), ("⏮️", "previous"),
];
fn uploaded() -> &'static RwLock<HashMap<String, Id<EmojiMarker>>> {
static IDS: OnceLock<RwLock<HashMap<String, Id<EmojiMarker>>>> = OnceLock::new();
IDS.get_or_init(Default::default)
}
fn id_of(emoji: &str) -> Option<(String, Id<EmojiMarker>)> {
let name = format!("dz_{}", ICONS.iter().find(|i| i.0 == emoji)?.1);
let id = *uploaded().read().unwrap_or_else(|e| e.into_inner()).get(&name)?;
Some((name, id))
}
/// What a button shows for `emoji`: Dezio's icon if there is one, or the emoji itself.
pub fn on_button(emoji: &str) -> EmojiReactionType {
match id_of(emoji) {
Some((name, id)) => EmojiReactionType::Custom { animated: false, id, name: Some(name) },
None => EmojiReactionType::Unicode { name: emoji.to_string() },
}
}
/// The same for message text.
pub fn in_text(emoji: &str) -> String {
id_of(emoji).map_or_else(|| emoji.to_string(), |(name, id)| format!("<:{name}:{id}>"))
}
/// Load the bot's emojis and upload any of ours that are missing.
pub async fn sync(state: &State) {
let Ok(list) = state.http.get_application_emojis(state.app_id()).await else { return tracing::warn!("couldn't list the application emojis") };
let Ok(list) = list.model().await else { return };
let mut known: HashMap<String, Id<EmojiMarker>> = list.items.into_iter().map(|e| (e.name, e.id)).collect();
let Ok(folder) = std::fs::read_dir(paths::asset(&["emojis"])) else { return tracing::warn!("no assets/emojis folder") };
for file in folder.flatten() {
let path = file.path();
let Some(name) = path.file_stem().and_then(|n| n.to_str()).map(str::to_string) else { continue };
if path.extension().is_none_or(|e| e != "png") || known.contains_key(&name) {
continue;
}
let Ok(bytes) = std::fs::read(&path) else { continue };
let image = format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes));
match state.http.add_application_emoji(state.app_id(), &name, &image).await {
Ok(r) => {
if let Ok(e) = r.model().await {
known.insert(e.name, e.id);
}
}
Err(e) => tracing::warn!("couldn't upload the emoji {name}: {e}"),
}
}
tracing::info!("{} application emojis ready", known.len());
*uploaded().write().unwrap_or_else(|e| e.into_inner()) = known;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_icon_has_a_picture_small_enough_for_discord() {
for (_, name) in ICONS {
let path = paths::asset(&["emojis", &format!("dz_{name}.png")]);
let bytes = std::fs::read(&path).unwrap_or_else(|_| panic!("{path:?}"));
assert!(bytes.len() < 256 * 1024);
let img = image::load_from_memory(&bytes).unwrap();
assert_eq!((img.width(), img.height()), (128, 128));
}
}
#[test]
fn without_uploads_buttons_keep_the_plain_emoji() {
assert_eq!(in_text("🎲"), "🎲");
assert!(matches!(on_button("🎲"), EmojiReactionType::Unicode { .. }));
}
}