Music with a live player, Last.fm, video downloads, games, AI chat, moderation, logging, a web dashboard and a Game Boy Activity. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
201 lines
8.3 KiB
Rust
201 lines
8.3 KiB
Rust
//! Answering button clicks, menu choices and modal submits.
|
|
use crate::state::State;
|
|
use crate::ui;
|
|
use serde_json::Value;
|
|
use std::collections::HashMap;
|
|
use twilight_model::application::interaction::modal::ModalInteractionData;
|
|
use twilight_model::application::interaction::Interaction;
|
|
use twilight_model::channel::message::{AllowedMentions, Component, MessageFlags};
|
|
use twilight_model::guild::Permissions;
|
|
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType};
|
|
|
|
/// Does the person who clicked have `needed` (or Administrator) in this server?
|
|
pub fn can(i: &Interaction, needed: Permissions) -> bool {
|
|
i.member
|
|
.as_ref()
|
|
.and_then(|m| m.permissions)
|
|
.is_some_and(|p| p.contains(needed) || p.contains(Permissions::ADMINISTRATOR))
|
|
}
|
|
|
|
async fn send(state: &State, i: &Interaction, response: InteractionResponse) {
|
|
if let Err(e) = state.http.interaction(state.app_id()).create_response(i.id, &i.token, &response).await {
|
|
tracing::warn!("interaction response failed: {e}");
|
|
}
|
|
}
|
|
|
|
/// Replace the message the button/menu sits on (or, from a modal opened by one, that message).
|
|
pub async fn update(state: &State, i: &Interaction, card: Component) {
|
|
let data = InteractionResponseData {
|
|
components: Some(vec![card]),
|
|
flags: Some(MessageFlags::IS_COMPONENTS_V2),
|
|
allowed_mentions: Some(AllowedMentions::default()),
|
|
..Default::default()
|
|
};
|
|
send(state, i, InteractionResponse { kind: InteractionResponseType::UpdateMessage, data: Some(data) }).await;
|
|
}
|
|
|
|
/// A card only the clicker sees.
|
|
pub async fn private_card(state: &State, i: &Interaction, card: Component) {
|
|
let data = InteractionResponseData {
|
|
components: Some(vec![card]),
|
|
flags: Some(MessageFlags::IS_COMPONENTS_V2 | MessageFlags::EPHEMERAL),
|
|
allowed_mentions: Some(AllowedMentions::default()),
|
|
..Default::default()
|
|
};
|
|
send(state, i, InteractionResponse { kind: InteractionResponseType::ChannelMessageWithSource, data: Some(data) }).await;
|
|
}
|
|
|
|
/// A short private message (an error, usually).
|
|
pub async fn private_text(state: &State, i: &Interaction, text: &str) {
|
|
private_card(state, i, ui::notice(text, Some(ui::RED))).await;
|
|
}
|
|
|
|
/// Acknowledge a click without changing anything.
|
|
pub async fn ack(state: &State, i: &Interaction) {
|
|
send(state, i, InteractionResponse { kind: InteractionResponseType::DeferredUpdateMessage, data: None }).await;
|
|
}
|
|
|
|
pub async fn modal(state: &State, i: &Interaction, custom_id: &str, title: &str, components: Vec<Component>) {
|
|
let data = InteractionResponseData {
|
|
custom_id: Some(custom_id.to_string()),
|
|
title: Some(title.to_string()),
|
|
components: Some(components),
|
|
..Default::default()
|
|
};
|
|
send(state, i, InteractionResponse { kind: InteractionResponseType::Modal, data: Some(data) }).await;
|
|
}
|
|
|
|
/// `custom_id -> typed text` for every text field in a submitted modal.
|
|
pub fn modal_values(data: &ModalInteractionData) -> HashMap<String, String> {
|
|
fn walk(v: &Value, out: &mut HashMap<String, String>) {
|
|
match v {
|
|
Value::Object(o) => {
|
|
if let (Some(Value::String(id)), Some(Value::String(val))) = (o.get("custom_id"), o.get("value")) {
|
|
out.insert(id.clone(), val.clone());
|
|
}
|
|
if let (Some(Value::String(id)), Some(Value::Array(vals))) = (o.get("custom_id"), o.get("values")) {
|
|
out.insert(id.clone(), vals.first().and_then(Value::as_str).unwrap_or("").to_string());
|
|
}
|
|
o.values().for_each(|x| walk(x, out));
|
|
}
|
|
Value::Array(a) => a.iter().for_each(|x| walk(x, out)),
|
|
_ => {}
|
|
}
|
|
}
|
|
let mut out = HashMap::new();
|
|
if let Ok(v) = serde_json::to_value(data) {
|
|
walk(&v, &mut out);
|
|
}
|
|
out
|
|
}
|
|
|
|
/// A labelled text box for a modal.
|
|
pub fn text_field(custom_id: &str, label: &str, description: Option<&str>, value: &str, max: u16, paragraph: bool, placeholder: Option<&str>) -> Component {
|
|
use twilight_model::channel::message::component::{Label, TextInput, TextInputStyle};
|
|
#[allow(deprecated)]
|
|
let input = TextInput {
|
|
id: None,
|
|
custom_id: custom_id.to_string(),
|
|
label: None,
|
|
max_length: Some(max),
|
|
min_length: None,
|
|
placeholder: placeholder.map(str::to_string),
|
|
required: Some(false),
|
|
style: if paragraph { TextInputStyle::Paragraph } else { TextInputStyle::Short },
|
|
value: (!value.is_empty()).then(|| value.to_string()),
|
|
};
|
|
Component::Label(Label {
|
|
id: None,
|
|
label: label.to_string(),
|
|
description: description.map(str::to_string),
|
|
component: Box::new(Component::TextInput(input)),
|
|
})
|
|
}
|
|
|
|
/// "Thinking…" that only the clicker sees; answer it with [`followup_text`].
|
|
pub async fn defer_private(state: &State, i: &Interaction) {
|
|
let data = InteractionResponseData { flags: Some(MessageFlags::EPHEMERAL), ..Default::default() };
|
|
send(state, i, InteractionResponse { kind: InteractionResponseType::DeferredChannelMessageWithSource, data: Some(data) }).await;
|
|
}
|
|
|
|
pub async fn followup_text(state: &State, i: &Interaction, text: &str) {
|
|
let result = state
|
|
.http
|
|
.interaction(state.app_id())
|
|
.create_followup(&i.token)
|
|
.content(text)
|
|
.flags(MessageFlags::EPHEMERAL)
|
|
.allowed_mentions(Some(&AllowedMentions::default()))
|
|
.await;
|
|
if let Err(e) = result {
|
|
tracing::warn!("follow-up failed: {e}");
|
|
}
|
|
}
|
|
|
|
/// The select menu with this custom id anywhere in a message's components.
|
|
pub fn find_select<'a>(components: &'a [Component], custom_id: &str) -> Option<&'a twilight_model::channel::message::component::SelectMenu> {
|
|
for c in components {
|
|
match c {
|
|
Component::SelectMenu(m) if m.custom_id == custom_id => return Some(m),
|
|
Component::Container(x) => {
|
|
if let Some(m) = find_select(&x.components, custom_id) {
|
|
return Some(m);
|
|
}
|
|
}
|
|
Component::ActionRow(x) => {
|
|
if let Some(m) = find_select(&x.components, custom_id) {
|
|
return Some(m);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Every text block of a message's components (Components V2 messages have no `content`).
|
|
pub fn texts(components: &[Component]) -> Vec<String> {
|
|
let mut out = vec![];
|
|
for c in components {
|
|
match c {
|
|
Component::TextDisplay(t) => out.push(t.content.clone()),
|
|
Component::Container(x) => out.extend(texts(&x.components)),
|
|
Component::Section(x) => {
|
|
out.extend(texts(&x.components));
|
|
out.extend(texts(std::slice::from_ref(&*x.accessory)));
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Replace the clicked message's card AND its attached file (a second step after [`ack`]).
|
|
pub async fn edit_with_file(state: &State, i: &Interaction, card: Component, name: &str, bytes: Vec<u8>) {
|
|
use twilight_model::http::attachment::Attachment;
|
|
let files = [Attachment::from_bytes(name.to_string(), bytes, 1)];
|
|
let r = state.http.interaction(state.app_id()).update_response(&i.token).flags(MessageFlags::IS_COMPONENTS_V2)
|
|
.components(Some(&[card])).attachments(&files).await;
|
|
if let Err(e) = r {
|
|
tracing::warn!("couldn't replace the picture: {e}");
|
|
}
|
|
}
|
|
|
|
/// A labelled dropdown for a modal: `options` are (label, value); `current` is preselected.
|
|
pub fn select_field(custom_id: &str, label: &str, options: &[(&str, &str)], current: &str) -> Component {
|
|
use twilight_model::channel::message::component::{Label, SelectMenu, SelectMenuOption, SelectMenuType};
|
|
let menu = SelectMenu {
|
|
id: None,
|
|
channel_types: None,
|
|
custom_id: custom_id.to_string(),
|
|
default_values: None,
|
|
disabled: false,
|
|
kind: SelectMenuType::Text,
|
|
max_values: Some(1),
|
|
min_values: Some(1),
|
|
options: Some(options.iter().map(|(l, v)| SelectMenuOption { default: *v == current, description: None, emoji: None, label: l.to_string(), value: v.to_string() }).collect()),
|
|
placeholder: None,
|
|
required: None,
|
|
};
|
|
Component::Label(Label { id: None, label: label.to_string(), description: None, component: Box::new(Component::SelectMenu(menu)) })
|
|
}
|