Dezio/src/cmd.rs
2026-12-01 21:50:16 -06:00

602 lines
24 KiB
Rust

//! One command framework for both `D!name args` messages and `/name` slash commands.
//!
//! A command declares its options once; a prefix message fills them from the words after the
//! name (the last option takes the rest of the line), a slash command from the typed options.
//! Handlers then read [`Args`] and answer through [`Ctx`], which replies correctly either way.
use crate::converters::find_member;
use crate::error::UserError;
use crate::state::State;
use crate::ui::{self, Card};
use anyhow::{Context as _, Result};
use futures::future::BoxFuture;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use twilight_model::channel::message::{AllowedMentions, Component, MessageFlags};
use twilight_model::guild::Permissions;
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType};
use twilight_model::id::marker::{ChannelMarker, GuildMarker, InteractionMarker, UserMarker};
use twilight_model::id::Id;
use twilight_util::permission_calculator::PermissionCalculator;
#[derive(Clone, Copy, PartialEq)]
pub enum OptKind {
String,
Integer,
Bool,
User,
Role,
Channel,
Attachment,
}
pub struct Opt {
pub name: &'static str,
pub description: &'static str,
pub kind: OptKind,
pub required: bool,
/// Given as a word after `D!name` (some options only make sense as slash options, and vice versa).
pub in_prefix: bool,
pub in_slash: bool,
pub min: Option<i64>,
pub max: Option<i64>,
pub choices: &'static [&'static str],
/// Suggestions while typing (see `Command::autocomplete`).
pub autocomplete: bool,
}
impl Opt {
fn make(name: &'static str, description: &'static str, kind: OptKind, required: bool) -> Self {
Self { name, description, kind, required, in_prefix: true, in_slash: true, min: None, max: None, choices: &[], autocomplete: false }
}
pub fn req(name: &'static str, description: &'static str, kind: OptKind) -> Self {
Self::make(name, description, kind, true)
}
pub fn opt(name: &'static str, description: &'static str, kind: OptKind) -> Self {
Self::make(name, description, kind, false)
}
pub fn slash_only(mut self) -> Self {
self.in_prefix = false;
self
}
pub fn prefix_only(mut self) -> Self {
self.in_slash = false;
self
}
pub fn autocomplete(mut self) -> Self {
self.autocomplete = true;
self
}
pub fn choices(mut self, c: &'static [&'static str]) -> Self {
self.choices = c;
self
}
pub fn range(mut self, min: i64, max: i64) -> Self {
self.min = Some(min);
self.max = Some(max);
self
}
}
pub type Handler = fn(Arc<Ctx>) -> BoxFuture<'static, Result<()>>;
/// Suggestions for an option being typed: (state, option name, text so far, who, where) -> (label, value) pairs.
/// Like [`Suggest`], but also gets the other options already filled in (so one choice can depend on another).
pub type SuggestWith = fn(Arc<State>, String, String, HashMap<String, String>) -> BoxFuture<'static, Vec<(String, String)>>;
pub type Suggest = fn(Arc<State>, String, String, Option<Id<GuildMarker>>, Id<UserMarker>) -> BoxFuture<'static, Vec<(String, String)>>;
pub struct Command {
pub name: &'static str,
pub aliases: &'static [&'static str],
pub description: &'static str,
pub category: &'static str,
pub usage: &'static str,
pub options: Vec<Opt>,
pub slash: bool,
/// The slash command's name when it differs from the text command's.
pub slash_name: Option<&'static str>,
pub guild_only: bool,
/// Bot-owner tools: only listed in help for the owner.
pub hidden: bool,
/// Only the bot's owner may run it.
pub owner_only: bool,
/// Minimum time between two uses by the same person.
pub cooldown: Option<std::time::Duration>,
/// A right-click "Apps" entry on a message instead of a text command.
pub message_menu: bool,
/// A right-click "Apps" entry on a user.
pub user_menu: bool,
/// What the person running it needs (checked for both forms; also hides the slash command from others).
pub perm: Option<Permissions>,
pub handler: Handler,
pub suggest: Option<Suggest>,
pub suggest_with: Option<SuggestWith>,
}
impl Command {
pub fn new(name: &'static str, category: &'static str, description: &'static str, handler: Handler) -> Self {
Self { name, aliases: &[], description, category, usage: "", options: vec![], slash: true, slash_name: None,
guild_only: false, hidden: false, owner_only: false, cooldown: None, message_menu: false, user_menu: false, perm: None, handler, suggest: None, suggest_with: None }
}
pub fn aliases(mut self, a: &'static [&'static str]) -> Self {
self.aliases = a;
self
}
pub fn usage(mut self, u: &'static str) -> Self {
self.usage = u;
self
}
pub fn opt(mut self, o: Opt) -> Self {
self.options.push(o);
self
}
pub fn message_menu(mut self) -> Self {
self.message_menu = true;
self.slash = true;
self
}
pub fn user_menu(mut self) -> Self {
self.user_menu = true;
self.slash = true;
self
}
pub fn suggest_with(mut self, f: SuggestWith) -> Self {
self.suggest_with = Some(f);
self
}
pub fn suggest(mut self, f: Suggest) -> Self {
self.suggest = Some(f);
self
}
pub fn owner_only(mut self) -> Self {
self.owner_only = true;
self.hidden = true;
self
}
pub fn cooldown(mut self, secs: u64) -> Self {
self.cooldown = Some(std::time::Duration::from_secs(secs));
self
}
pub fn hidden(mut self) -> Self {
self.hidden = true;
self
}
pub fn prefix_only(mut self) -> Self {
self.slash = false;
self
}
pub fn slash_as(mut self, name: &'static str) -> Self {
self.slash_name = Some(name);
self
}
pub fn guild_only(mut self) -> Self {
self.guild_only = true;
self
}
pub fn perm(mut self, p: Permissions) -> Self {
self.perm = Some(p);
self.guild_only = true;
self
}
}
/// Option values by name, always as text (parse with the helpers).
#[derive(Default, Clone)]
pub struct Args(pub HashMap<String, String>);
impl Args {
pub fn str(&self, name: &str) -> Option<&str> {
self.0.get(name).map(|s| s.trim()).filter(|s| !s.is_empty())
}
pub fn int(&self, name: &str) -> Option<i64> {
self.str(name)?.parse().ok()
}
pub fn bool(&self, name: &str) -> Option<bool> {
match self.str(name)?.to_lowercase().as_str() {
"true" | "yes" | "y" | "on" | "1" => Some(true),
"false" | "no" | "n" | "off" | "0" => Some(false),
_ => None,
}
}
/// A role or channel given as `<@&id>`, `<#id>` or a raw id.
pub fn id(&self, name: &str) -> Option<u64> {
let s = self.str(name)?.trim_start_matches("<@&").trim_start_matches("<#").trim_end_matches('>');
s.parse::<u64>().ok().filter(|&n| n > 0)
}
/// A user given as `<@id>`, `<@!id>` or a raw id.
pub fn user(&self, name: &str) -> Option<Id<UserMarker>> {
let s = self.str(name)?.trim_start_matches("<@").trim_start_matches('!').trim_end_matches('>');
s.parse::<u64>().ok().and_then(Id::new_checked)
}
}
/// Fill [`Args`] from the words of a prefix command.
pub fn parse_positional(options: &[Opt], rest: &str) -> Args {
let mut map = HashMap::new();
let mut rest = rest.trim();
let options: Vec<&Opt> = options.iter().filter(|o| o.in_prefix).collect();
for (i, opt) in options.iter().enumerate() {
if rest.is_empty() {
break;
}
if i + 1 == options.len() {
map.insert(opt.name.to_string(), rest.to_string());
break;
}
let (word, tail) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
map.insert(opt.name.to_string(), word.to_string());
rest = tail.trim_start();
}
Args(map)
}
pub enum Origin {
Message { channel_id: Id<ChannelMarker> },
Interaction {
id: Id<InteractionMarker>,
token: String,
permissions: Option<Permissions>,
responded: AtomicBool,
deferred: AtomicBool,
},
}
pub struct Ctx {
pub state: Arc<State>,
pub origin: Origin,
/// The name of the command that was run (matters for one handler serving many commands: `D!cat`, `D!hug`…).
pub invoked: &'static str,
pub args: Args,
pub user_id: Id<UserMarker>,
pub user_name: String,
pub guild_id: Option<Id<GuildMarker>>,
pub channel_id: Id<ChannelMarker>,
/// Author of the message this prefix command replies to.
pub reply_to: Option<Id<UserMarker>>,
/// The message this prefix command replies to.
pub reply_msg: Option<Id<twilight_model::id::marker::MessageMarker>>,
/// The message that held the command (prefix commands).
pub message_id: Option<Id<twilight_model::id::marker::MessageMarker>>,
/// The message a right-click menu was used on.
pub target_message: Option<twilight_model::channel::Message>,
/// The user a right-click menu was used on.
pub target_user: Option<twilight_model::user::User>,
/// Files attached to the message (prefix) or given as an option (slash).
pub attachments: Vec<twilight_model::channel::Attachment>,
/// The caller's Discord language, e.g. `es-ES` (slash commands).
pub locale: Option<String>,
}
/// How high a member's top role is: position first, then the older role wins ties.
pub use crate::state::Rank;
impl Ctx {
/// A copy of this context with different option values (used when the words were typed in a
/// different order than usual).
pub fn with_args(&self, args: Args) -> Ctx {
Ctx {
state: self.state.clone(),
invoked: self.invoked,
origin: match &self.origin {
Origin::Message { channel_id } => Origin::Message { channel_id: *channel_id },
Origin::Interaction { id, token, permissions, responded, deferred } => Origin::Interaction {
id: *id,
token: token.clone(),
permissions: *permissions,
responded: AtomicBool::new(responded.load(Ordering::SeqCst)),
deferred: AtomicBool::new(deferred.load(Ordering::SeqCst)),
},
},
args,
user_id: self.user_id,
user_name: self.user_name.clone(),
guild_id: self.guild_id,
channel_id: self.channel_id,
reply_to: self.reply_to,
reply_msg: self.reply_msg,
message_id: self.message_id,
target_message: self.target_message.clone(),
target_user: self.target_user.clone(),
attachments: self.attachments.clone(),
locale: self.locale.clone(),
}
}
pub fn command_message_id(&self) -> Option<Id<twilight_model::id::marker::MessageMarker>> {
self.message_id
}
pub fn is_slash(&self) -> bool {
matches!(self.origin, Origin::Interaction { .. })
}
pub fn guild(&self) -> Result<Id<GuildMarker>> {
self.guild_id.ok_or_else(|| UserError::new("This command only works in servers.").into())
}
/// Answer a slash command with "thinking…" now (the work may take longer than Discord's 3 s).
pub async fn defer(&self) -> Result<()> {
if let Origin::Interaction { id, token, responded, deferred, .. } = &self.origin {
if !responded.swap(true, Ordering::SeqCst) {
let response = InteractionResponse { kind: InteractionResponseType::DeferredChannelMessageWithSource, data: None };
self.state.http.interaction(self.state.app_id()).create_response(*id, token, &response).await?;
deferred.store(true, Ordering::SeqCst);
}
}
Ok(())
}
/// Answer a slash command with a private "thinking…" (only the caller sees what follows).
pub async fn defer_private(&self) -> Result<()> {
if let Origin::Interaction { id, token, responded, deferred, .. } = &self.origin {
if !responded.swap(true, Ordering::SeqCst) {
let data = InteractionResponseData { flags: Some(MessageFlags::EPHEMERAL), ..Default::default() };
let response = InteractionResponse { kind: InteractionResponseType::DeferredChannelMessageWithSource, data: Some(data) };
self.state.http.interaction(self.state.app_id()).create_response(*id, token, &response).await?;
deferred.store(false, Ordering::SeqCst); // already private: nothing to clear later
}
}
Ok(())
}
/// Send a card to wherever the command came from.
pub async fn reply(&self, card: Component) -> Result<()> {
self.send(card, false).await
}
/// Like `reply`, but private: ephemeral for slash commands, removed after 20 s for messages.
pub async fn reply_private(&self, card: Component) -> Result<()> {
self.send(card, true).await
}
/// The same as [`Self::reply_file`], seen only by the person who asked (when it's a slash command).
pub async fn reply_private_file(&self, card: Component, name: &str, bytes: Vec<u8>) -> Result<()> {
use twilight_model::http::attachment::Attachment;
let Origin::Interaction { token, .. } = &self.origin else { return self.reply_file(card, name, bytes).await };
self.defer_private().await?; // a no-op if we already answered
let files = [Attachment::from_bytes(name.to_string(), bytes, 1)];
self.state.http.interaction(self.state.app_id()).create_followup(token).flags(MessageFlags::IS_COMPONENTS_V2 | MessageFlags::EPHEMERAL).components(&[card])
.attachments(&files).allowed_mentions(Some(&AllowedMentions::default())).await.context("sending a private follow-up with a file")?;
Ok(())
}
/// Send a card that refers to an uploaded file as `attachment://<name>`.
pub async fn reply_file(&self, card: Component, name: &str, bytes: Vec<u8>) -> Result<()> {
use twilight_model::http::attachment::Attachment;
let http = &self.state.http;
let files = [Attachment::from_bytes(name.to_string(), bytes, 1)];
let no_pings = AllowedMentions::default();
match &self.origin {
Origin::Message { channel_id } => {
http.create_message(*channel_id).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card])
.attachments(&files).allowed_mentions(Some(&no_pings)).await.context("sending a card with a file")?;
}
Origin::Interaction { token, .. } => {
self.defer().await?; // a no-op if we already answered
let client = http.interaction(self.state.app_id());
client.create_followup(token).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card])
.attachments(&files).allowed_mentions(Some(&no_pings)).await.context("sending a follow-up with a file")?;
}
}
Ok(())
}
/// Send a card and give back the message (prefix commands only; slash commands answer `None`).
pub async fn reply_message(&self, card: Component) -> Result<Option<twilight_model::channel::Message>> {
match &self.origin {
Origin::Message { channel_id } => Ok(Some(self.state.http.create_message(*channel_id).flags(MessageFlags::IS_COMPONENTS_V2)
.components(&[card]).allowed_mentions(Some(&AllowedMentions::default())).await?.model().await?)),
Origin::Interaction { .. } => {
self.reply(card).await?;
Ok(None)
}
}
}
pub async fn say(&self, text: &str) -> Result<()> {
self.reply(ui::notice(text, None)).await
}
pub async fn fail(&self, text: &str) -> Result<()> {
self.reply_private(ui::notice(text, Some(ui::RED))).await
}
async fn send(&self, card: Component, private: bool) -> Result<()> {
let http = &self.state.http;
let mut flags = MessageFlags::IS_COMPONENTS_V2;
let no_pings = AllowedMentions::default();
match &self.origin {
Origin::Message { channel_id } => {
let sent = http
.create_message(*channel_id)
.flags(flags)
.components(&[card])
.allowed_mentions(Some(&no_pings))
.await
.context("sending a card")?
.model()
.await?;
if private {
let http = http.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(20)).await;
let _ = http.delete_message(sent.channel_id, sent.id).await;
});
}
}
Origin::Interaction { id, token, responded, deferred, .. } => {
if private {
flags |= MessageFlags::EPHEMERAL;
}
let client = http.interaction(self.state.app_id());
if !responded.swap(true, Ordering::SeqCst) {
let data = InteractionResponseData {
components: Some(vec![card]),
flags: Some(flags),
allowed_mentions: Some(no_pings),
..Default::default()
};
let response = InteractionResponse { kind: InteractionResponseType::ChannelMessageWithSource, data: Some(data) };
client.create_response(*id, token, &response).await.context("answering the interaction")?;
} else {
// After a public "thinking…", Discord shows the first follow-up publicly whatever
// the flags say; remove the placeholder first so a private reply really is private.
if private && deferred.swap(false, Ordering::SeqCst) {
let _ = client.delete_response(token).await;
}
client
.create_followup(token)
.flags(flags)
.components(&[card])
.allowed_mentions(Some(&no_pings))
.await
.context("sending a follow-up")?;
}
}
}
Ok(())
}
// ---- people & permissions (from the cache) -----------------------------------------------
/// The person an option points at: the named option, else the replied-to author.
pub fn target(&self, option: &str) -> Result<Id<UserMarker>> {
let guild = self.guild()?;
match self.args.str(option) {
Some(text) => find_member(&self.state.cache, guild, text).ok_or_else(|| {
UserError::new(format!("I couldn't find a member called `{}` here.", ui::escape(text))).into()
}),
None => self.reply_to.ok_or_else(|| {
UserError::new("Who? Mention them, give their ID or name, or reply to one of their messages.").into()
}),
}
}
pub fn is_owner(&self, guild: Id<GuildMarker>, user: Id<UserMarker>) -> bool {
self.state.is_guild_owner(guild, user)
}
pub fn rank(&self, guild: Id<GuildMarker>, user: Id<UserMarker>) -> Rank {
self.state.rank(guild, user)
}
/// The moderation safety rules: not yourself, not me, not the owner, roles below yours and mine.
pub fn check_hierarchy(&self, target: Id<UserMarker>) -> Result<()> {
let guild = self.guild()?;
let mention = format!("<@{target}>");
if target == self.user_id {
bail_user!("You can't do that to yourself.");
}
if target == self.state.bot_id() {
bail_user!("I can't do that to myself.");
}
if self.is_owner(guild, target) {
bail_user!("The server owner can't be moderated.");
}
if !self.is_owner(guild, self.user_id) && self.rank(guild, self.user_id) <= self.rank(guild, target) {
bail_user!("{mention} has a role equal to or above yours.");
}
if self.rank(guild, self.state.bot_id()) <= self.rank(guild, target) {
bail_user!("{mention} has a role equal to or above mine — move my role higher.");
}
Ok(())
}
/// Does the person who ran this have `needed` here? DMs: false.
pub fn has_permission(&self, needed: Permissions) -> bool {
if let Origin::Interaction { permissions: Some(p), .. } = &self.origin {
return p.contains(needed) || p.contains(Permissions::ADMINISTRATOR);
}
let Some(guild) = self.guild_id else { return false };
if self.is_owner(guild, self.user_id) {
return true;
}
let cache = &self.state.cache;
let everyone = cache.role(guild.cast()).map_or(Permissions::empty(), |r| r.permissions);
let roles: Vec<_> = cache
.member(guild, self.user_id)
.map(|m| m.roles().iter().filter_map(|&id| cache.role(id).map(|r| (id, r.permissions))).collect())
.unwrap_or_default();
let perms = PermissionCalculator::new(guild, self.user_id, everyone, roles.as_slice()).root();
perms.contains(needed) || perms.contains(Permissions::ADMINISTRATOR)
}
/// Fail with a permission message unless the person has `needed`.
pub fn require(&self, needed: Permissions, label: &str) -> Result<()> {
if self.has_permission(needed) {
return Ok(());
}
bail_user!("You are missing required permissions: `{label}`");
}
}
/// Name/alias lookup, case-insensitive.
pub struct Registry {
commands: Vec<Command>,
index: HashMap<String, usize>,
slash_index: HashMap<String, usize>,
}
impl Registry {
pub fn new(commands: Vec<Command>) -> Self {
let mut index = HashMap::new();
for (i, c) in commands.iter().enumerate() {
for name in std::iter::once(&c.name).chain(c.aliases.iter()) {
let old = index.insert(name.to_lowercase(), i);
assert!(old.is_none(), "duplicate command name {name}");
}
}
let mut slash_index = HashMap::new();
for (i, c) in commands.iter().enumerate().filter(|(_, c)| c.slash) {
// Discord refuses the whole command list if two slash commands share a name (a menu entry and a slash command may)
let key = format!("{}:{}", c.message_menu as u8 + 2 * c.user_menu as u8, c.slash_name.unwrap_or(c.name).to_lowercase());
let old = slash_index.insert(c.slash_name.unwrap_or(c.name).to_lowercase(), i);
if let Some(o) = old {
let other = &commands[o];
let same_kind = (other.message_menu, other.user_menu) == (c.message_menu, c.user_menu);
assert!(!same_kind, "two slash commands are both called {key}");
}
}
Self { commands, index, slash_index }
}
pub fn find(&self, name: &str) -> Option<&Command> {
self.index.get(&name.to_lowercase()).map(|&i| &self.commands[i])
}
/// The command behind a slash command / menu name Discord sent.
pub fn find_slash(&self, name: &str) -> Option<&Command> {
self.slash_index.get(&name.to_lowercase()).map(|&i| &self.commands[i])
}
pub fn all(&self) -> &[Command] {
&self.commands
}
}
pub fn error_card(text: &str) -> Component {
Card::new(Some(ui::RED)).text(text).build()
}
#[cfg(test)]
mod tests {
use super::*;
fn opts() -> Vec<Opt> {
vec![
Opt::req("user", "", OptKind::User),
Opt::opt("reason", "", OptKind::String),
]
}
#[test]
fn last_option_takes_the_rest() {
let a = parse_positional(&opts(), " <@!123> being rude today ");
assert_eq!(a.user("user").map(|i| i.get()), Some(123));
assert_eq!(a.str("reason"), Some("being rude today"));
}
#[test]
fn missing_values_stay_unset() {
let a = parse_positional(&opts(), "");
assert!(a.str("user").is_none());
}
}