Each button opens a private message with IDs, names, links, dates and so on in code blocks. Roles, channels, emojis, members and permissions are listed in full with their IDs, on pages when they run long. The user card also shows up to 40 role chips. Co-Authored-By: Claude Opus 5.5 <[email protected]>
719 lines
34 KiB
Rust
719 lines
34 KiB
Rust
//! Dezio — the Rust port. Stage 1: config, storage, cards, and the prefix + slash command framework.
|
|
#![allow(dead_code)] // framework pieces are used as more commands are ported
|
|
#[macro_use]
|
|
mod error;
|
|
mod audit;
|
|
mod calc;
|
|
mod cardart;
|
|
mod cdn;
|
|
mod colors;
|
|
mod confirm;
|
|
mod draw;
|
|
mod emojis;
|
|
mod cmd;
|
|
mod commands;
|
|
mod converters;
|
|
mod interact;
|
|
mod pager;
|
|
mod prefs;
|
|
mod paths;
|
|
mod pix;
|
|
mod state;
|
|
mod hosted;
|
|
mod presence;
|
|
mod text;
|
|
mod tui;
|
|
mod web;
|
|
mod storage;
|
|
mod ui;
|
|
|
|
use anyhow::{Context as _, Result};
|
|
use cmd::{Args, Command, Ctx, Origin, OptKind};
|
|
use error::UserError;
|
|
use state::State;
|
|
use twilight_model::gateway::payload::outgoing::RequestGuildMembers;
|
|
use std::collections::hash_map::DefaultHasher;
|
|
use std::hash::{Hash, Hasher};
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
use twilight_gateway::{create_recommended, Config, EventTypeFlags, Intents, StreamExt as _};
|
|
use twilight_http::Client;
|
|
use twilight_model::application::command::{Command as ApiCommand, CommandOptionChoice, CommandOptionChoiceValue, CommandType};
|
|
use twilight_model::application::interaction::{InteractionContextType, InteractionData, InteractionType};
|
|
use twilight_model::application::interaction::application_command::CommandOptionValue;
|
|
use twilight_model::gateway::event::Event;
|
|
use twilight_model::oauth::ApplicationIntegrationType;
|
|
use twilight_util::builder::command::{AttachmentBuilder, BooleanBuilder, ChannelBuilder, CommandBuilder, IntegerBuilder, RoleBuilder, StringBuilder, UserBuilder};
|
|
|
|
/// Discord allows 100 characters in a slash description.
|
|
fn cut(text: &str) -> String {
|
|
if text.chars().count() <= 100 {
|
|
return text.to_string();
|
|
}
|
|
let mut t: String = text.chars().take(99).collect();
|
|
t.push('…');
|
|
t
|
|
}
|
|
|
|
fn api_command(c: &Command) -> ApiCommand {
|
|
let mut b = CommandBuilder::new(c.slash_name.unwrap_or(c.name), if c.message_menu || c.user_menu { String::new() } else { cut(c.description) }, if c.message_menu { CommandType::Message } else if c.user_menu { CommandType::User } else { CommandType::ChatInput });
|
|
for o in c.options.iter().filter(|o| o.in_slash) {
|
|
b = match o.kind {
|
|
OptKind::String => {
|
|
let mut opt = StringBuilder::new(o.name, cut(o.description)).required(o.required).build();
|
|
if o.autocomplete {
|
|
opt.autocomplete = Some(true);
|
|
}
|
|
if !o.choices.is_empty() {
|
|
opt.choices = Some(o.choices.iter().map(|c| CommandOptionChoice {
|
|
name: (*c).to_string(),
|
|
name_localizations: None,
|
|
value: CommandOptionChoiceValue::String((*c).to_string()),
|
|
}).collect());
|
|
}
|
|
b.option(opt)
|
|
}
|
|
OptKind::Integer => {
|
|
let mut ib = IntegerBuilder::new(o.name, cut(o.description)).required(o.required);
|
|
if let (Some(lo), Some(hi)) = (o.min, o.max) {
|
|
ib = ib.min_value(lo).max_value(hi);
|
|
}
|
|
b.option(ib)
|
|
}
|
|
OptKind::Bool => b.option(BooleanBuilder::new(o.name, cut(o.description)).required(o.required)),
|
|
OptKind::User => b.option(UserBuilder::new(o.name, cut(o.description)).required(o.required)),
|
|
OptKind::Role => b.option(RoleBuilder::new(o.name, cut(o.description)).required(o.required)),
|
|
OptKind::Channel => b.option(ChannelBuilder::new(o.name, cut(o.description)).required(o.required)),
|
|
OptKind::Attachment => b.option(AttachmentBuilder::new(o.name, cut(o.description)).required(o.required)),
|
|
};
|
|
}
|
|
if let Some(p) = c.perm {
|
|
b = b.default_member_permissions(p);
|
|
}
|
|
let mut cmd = b.build();
|
|
cmd.contexts = Some(if c.guild_only {
|
|
vec![InteractionContextType::Guild]
|
|
} else {
|
|
vec![InteractionContextType::Guild, InteractionContextType::BotDm, InteractionContextType::PrivateChannel]
|
|
});
|
|
cmd.integration_types = Some(if c.guild_only {
|
|
vec![ApplicationIntegrationType::GuildInstall]
|
|
} else {
|
|
vec![ApplicationIntegrationType::GuildInstall, ApplicationIntegrationType::UserInstall]
|
|
});
|
|
cmd
|
|
}
|
|
|
|
/// Register slash commands, but only when the list changed since the last start.
|
|
async fn sync_commands(state: &State) -> Result<()> {
|
|
sync_commands_inner(state, false).await.map(|_| ())
|
|
}
|
|
|
|
/// Force a sync (the console's `sync`). Returns how many commands are registered.
|
|
pub(crate) async fn sync_commands_now(state: &State) -> Result<usize> {
|
|
sync_commands_inner(state, true).await
|
|
}
|
|
|
|
async fn sync_commands_inner(state: &State, force: bool) -> Result<usize> {
|
|
let mut list: Vec<ApiCommand> = state.registry.all().iter().filter(|c| c.slash).map(api_command).collect();
|
|
// the Game Boy Activity's "Launch" entry point is made by Discord and must survive a sync
|
|
if let Ok(r) = state.http.interaction(state.app_id()).global_commands().await {
|
|
if let Ok(existing) = r.models().await {
|
|
list.extend(existing.into_iter().filter(|c| u8::from(c.kind) == 4));
|
|
}
|
|
}
|
|
let json = serde_json::to_string(&list)?;
|
|
let mut h = DefaultHasher::new();
|
|
json.hash(&mut h);
|
|
let hash = h.finish().to_string();
|
|
let hash_path = paths::data(&[".command_sync_hash_rust"]);
|
|
if !force && std::fs::read_to_string(&hash_path).ok().as_deref() == Some(&hash) {
|
|
tracing::info!("slash commands unchanged ({})", list.len());
|
|
return Ok(list.len());
|
|
}
|
|
state.http.interaction(state.app_id()).set_global_commands(&list).await.context("syncing slash commands")?;
|
|
std::fs::write(hash_path, hash)?;
|
|
tracing::info!("synced {} slash commands", list.len());
|
|
Ok(list.len())
|
|
}
|
|
|
|
/// Tell the user what went wrong: expected problems in plain words, anything else as a generic card.
|
|
async fn report(ctx: &Ctx, name: &str, error: &anyhow::Error) {
|
|
let text = if let Some(e) = error.downcast_ref::<UserError>() {
|
|
format!("❌ {e}")
|
|
} else if error
|
|
.downcast_ref::<twilight_http::Error>()
|
|
.is_some_and(|e| matches!(e.kind(), twilight_http::error::ErrorType::Response { status, .. } if status.get() == 403))
|
|
{
|
|
"❌ Discord didn't let me do that — check my role position and permissions.".to_string()
|
|
} else {
|
|
tracing::error!("{name} failed for {}: {error:#}", ctx.user_name);
|
|
"⚠️ Something went wrong while running that command.".to_string()
|
|
};
|
|
if let Err(e) = ctx.fail(&text).await {
|
|
tracing::warn!("couldn't send the error card: {e:#}");
|
|
}
|
|
}
|
|
|
|
async fn run_command(state: &Arc<State>, name: &str, ctx: Ctx) {
|
|
let Some(command) = state.registry.find(name) else { return };
|
|
let (handler, perm, guild_only) = (command.handler, command.perm, command.guild_only);
|
|
let (owner_only, cooldown) = (command.owner_only, command.cooldown);
|
|
let cname = command.name;
|
|
let ctx = Arc::new(ctx);
|
|
let started = std::time::Instant::now();
|
|
let result: Result<()> = async {
|
|
if owner_only && !state.is_owner(ctx.user_id) {
|
|
bail_user!("This is an owner-only command.");
|
|
}
|
|
if let Some(cd) = cooldown {
|
|
let wait = state.cooldown_left(cname, ctx.user_id.get(), cd);
|
|
if wait > 0 {
|
|
bail_user!("⏳ Slow down — try again in {wait}s.");
|
|
}
|
|
}
|
|
if guild_only && ctx.guild_id.is_none() {
|
|
bail_user!("This command only works in servers.");
|
|
}
|
|
if let Some(p) = perm {
|
|
let label = format!("{p:?}").to_lowercase().replace('_', " ").replace(" | ", ", ");
|
|
ctx.require(p, &label)?;
|
|
}
|
|
// Never leave anyone staring at nothing: after 700 ms a slash command is deferred ("thinking…")
|
|
// and a text command shows "typing…" until it is done.
|
|
let fut = handler(ctx.clone());
|
|
tokio::pin!(fut);
|
|
tokio::select! {
|
|
r = &mut fut => r,
|
|
_ = tokio::time::sleep(std::time::Duration::from_millis(700)) => {
|
|
let typing = match &ctx.origin {
|
|
Origin::Interaction { .. } => {
|
|
let _ = ctx.defer().await;
|
|
None
|
|
}
|
|
Origin::Message { channel_id } => {
|
|
let (http, channel) = (state.http.clone(), *channel_id);
|
|
Some(tokio::spawn(async move {
|
|
loop {
|
|
let _ = http.create_typing_trigger(channel).await;
|
|
tokio::time::sleep(std::time::Duration::from_secs(8)).await;
|
|
}
|
|
}))
|
|
}
|
|
};
|
|
let r = fut.await;
|
|
if let Some(t) = typing {
|
|
t.abort();
|
|
}
|
|
r
|
|
}
|
|
}
|
|
}
|
|
.await;
|
|
let took = started.elapsed();
|
|
if took > std::time::Duration::from_millis(1000) {
|
|
tracing::info!("slow command {cname}: handler took {} ms", took.as_millis());
|
|
}
|
|
state.count(result.is_ok());
|
|
tui::activity(format!("{} ran {cname}{}", ctx.user_name, if result.is_ok() { "" } else { " (failed)" }));
|
|
if let Err(e) = result {
|
|
report(&ctx, cname, &e).await;
|
|
}
|
|
}
|
|
|
|
async fn on_message(state: Arc<State>, m: twilight_model::channel::Message) {
|
|
if m.author.bot {
|
|
return;
|
|
}
|
|
let lag = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64) - m.timestamp.as_micros() / 1000;
|
|
let prefix = state.prefix(m.guild_id);
|
|
let Some(head) = m.content.get(..prefix.len()) else { return };
|
|
if !head.eq_ignore_ascii_case(&prefix) {
|
|
return;
|
|
}
|
|
let body = m.content[prefix.len()..].trim_start();
|
|
let (name, rest) = body.split_once(char::is_whitespace).unwrap_or((body, ""));
|
|
let Some(command) = state.registry.find(name).filter(|c| !c.message_menu && !c.user_menu) else { return };
|
|
let args = cmd::parse_positional(&command.options, rest);
|
|
let ctx = Ctx {
|
|
state: state.clone(),
|
|
origin: Origin::Message { channel_id: m.channel_id },
|
|
invoked: command.name,
|
|
args,
|
|
user_id: m.author.id,
|
|
user_name: m.author.name.clone(),
|
|
guild_id: m.guild_id,
|
|
channel_id: m.channel_id,
|
|
reply_to: m.referenced_message.as_ref().map(|r| r.author.id),
|
|
reply_msg: m.referenced_message.as_ref().map(|r| r.id),
|
|
message_id: Some(m.id),
|
|
target_message: None,
|
|
target_user: None,
|
|
attachments: m.attachments.clone(),
|
|
locale: None,
|
|
};
|
|
let name = command.name;
|
|
if lag > 1000 {
|
|
tracing::info!("text command {name}: the message reached us {lag} ms after it was sent");
|
|
}
|
|
run_command(&state, name, ctx).await;
|
|
}
|
|
|
|
/// Button clicks. Custom ids look like `feature:action:argument`.
|
|
async fn on_component(state: Arc<State>, i: twilight_model::application::interaction::Interaction) {
|
|
let Some(InteractionData::MessageComponent(data)) = i.data.as_ref() else { return };
|
|
if data.custom_id.starts_with("help:") {
|
|
return commands::help::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("welcome:") {
|
|
return commands::welcome::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("ad:") {
|
|
return commands::other::on_ad(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("cf:") {
|
|
return confirm::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("emb:") {
|
|
return commands::embeds::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("pg:") {
|
|
return pager::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("wk:") {
|
|
return commands::search::wiki_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("calc:") {
|
|
return commands::tools::on_calc(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("color:") {
|
|
return commands::tools::on_color(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("ii:") {
|
|
return commands::info_copy::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("wx:") {
|
|
return commands::tools::weather::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("snipe:") {
|
|
return commands::snipe::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("log:") {
|
|
return commands::logs::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("unpin:") {
|
|
return commands::channels::on_unpin(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("qt:") {
|
|
return commands::media::quote::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("confess:") {
|
|
return commands::fun::confessions::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("gameboy:") {
|
|
return commands::gameboy::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("fm:") {
|
|
return commands::lastfm::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("music:") {
|
|
return commands::music::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("gm:") {
|
|
return commands::games::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("cookie:") {
|
|
return commands::games::on_cookie(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("act:") {
|
|
return commands::fun::actions::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("dl:") {
|
|
return commands::media::download::on_component(&state, &i).await;
|
|
}
|
|
if data.custom_id.starts_with("em:") {
|
|
return commands::media::emoji::on_component(&state, &i).await;
|
|
}
|
|
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, ':');
|
|
let (Some(feature), Some(action), Some(arg)) = (parts.next(), parts.next(), parts.next()) else { return };
|
|
let Some(user) = i.author() else { return };
|
|
let (kind, text) = match (feature, action) {
|
|
("purge", "stop") => {
|
|
let Some(channel) = arg.parse::<u64>().ok().and_then(twilight_model::id::Id::new_checked) else { return };
|
|
let can = i.member.as_ref().and_then(|m| m.permissions).is_some_and(|p| {
|
|
p.contains(twilight_model::guild::Permissions::MANAGE_MESSAGES) || p.contains(twilight_model::guild::Permissions::ADMINISTRATOR)
|
|
});
|
|
match commands::purge::stop_button(&state, channel, user.id, can).await {
|
|
Ok("stopping") => (twilight_model::http::interaction::InteractionResponseType::DeferredUpdateMessage, None),
|
|
Ok(msg) => (twilight_model::http::interaction::InteractionResponseType::ChannelMessageWithSource, Some(msg)),
|
|
Err(_) => return,
|
|
}
|
|
}
|
|
_ => return,
|
|
};
|
|
let data = text.map(|t| twilight_model::http::interaction::InteractionResponseData {
|
|
content: Some(t.to_string()),
|
|
flags: Some(twilight_model::channel::message::MessageFlags::EPHEMERAL),
|
|
..Default::default()
|
|
});
|
|
let response = twilight_model::http::interaction::InteractionResponse { kind, data };
|
|
if let Err(e) = state.http.interaction(state.app_id()).create_response(i.id, &i.token, &response).await {
|
|
tracing::warn!("component response failed: {e}");
|
|
}
|
|
}
|
|
|
|
/// Suggestions while someone types an option. Discord drops answers later than 3 s, so slow lookups are cut off.
|
|
async fn on_autocomplete(state: Arc<State>, i: twilight_model::application::interaction::Interaction) {
|
|
use twilight_model::application::command::{CommandOptionChoice, CommandOptionChoiceValue};
|
|
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType};
|
|
let Some(InteractionData::ApplicationCommand(data)) = i.data.as_ref() else { return };
|
|
let Some(command) = state.registry.find_slash(&data.name) else { return };
|
|
let (suggest, suggest_with) = (command.suggest, command.suggest_with);
|
|
if suggest.is_none() && suggest_with.is_none() {
|
|
return;
|
|
}
|
|
let Some(user) = i.author() else { return };
|
|
let focused = data.options.iter().find_map(|o| match &o.value {
|
|
CommandOptionValue::Focused(text, _) => Some((o.name.clone(), text.clone())),
|
|
_ => None,
|
|
});
|
|
let Some((name, text)) = focused else { return };
|
|
let mut siblings: std::collections::HashMap<String, String> = data
|
|
.options
|
|
.iter()
|
|
.filter_map(|o| match &o.value {
|
|
CommandOptionValue::String(v) => Some((o.name.clone(), v.clone())),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
// an attached file: tell the suggestion what kind it is (picture, video or sound)
|
|
for o in &data.options {
|
|
if let CommandOptionValue::Attachment(id) = &o.value {
|
|
if let Some(a) = data.resolved.as_ref().and_then(|r| r.attachments.get(id)) {
|
|
if let Some(kind) = commands::media::convert::kind_from(a.content_type.as_deref(), &a.filename) {
|
|
siblings.insert("file_kind".into(), kind.into());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let found = match (suggest_with, suggest) {
|
|
(Some(f), _) => tokio::time::timeout(Duration::from_millis(2500), f(state.clone(), name, text, siblings)).await.unwrap_or_default(),
|
|
(None, Some(f)) => tokio::time::timeout(Duration::from_millis(2500), f(state.clone(), name, text, i.guild_id, user.id)).await.unwrap_or_default(),
|
|
(None, None) => return,
|
|
};
|
|
let choices: Vec<CommandOptionChoice> = found
|
|
.into_iter()
|
|
.take(25)
|
|
.map(|(label, value)| CommandOptionChoice {
|
|
name: label.chars().take(100).collect(),
|
|
name_localizations: None,
|
|
value: CommandOptionChoiceValue::String(value.chars().take(100).collect()),
|
|
})
|
|
.collect();
|
|
let response = InteractionResponse {
|
|
kind: InteractionResponseType::ApplicationCommandAutocompleteResult,
|
|
data: Some(InteractionResponseData { choices: Some(choices), ..Default::default() }),
|
|
};
|
|
if let Err(e) = state.http.interaction(state.app_id()).create_response(i.id, &i.token, &response).await {
|
|
tracing::debug!("autocomplete answer too late: {e}");
|
|
}
|
|
}
|
|
|
|
async fn on_interaction(state: Arc<State>, i: twilight_model::application::interaction::Interaction) {
|
|
if i.kind == InteractionType::MessageComponent {
|
|
return on_component(state, i).await;
|
|
}
|
|
if i.kind == InteractionType::ApplicationCommandAutocomplete {
|
|
return on_autocomplete(state, i).await;
|
|
}
|
|
if i.kind == InteractionType::ModalSubmit {
|
|
if let Some(InteractionData::ModalSubmit(d)) = i.data.as_ref() {
|
|
if d.custom_id.starts_with("welcome:") {
|
|
return commands::welcome::on_component(&state, &i).await;
|
|
}
|
|
if d.custom_id.starts_with("ad:") {
|
|
return commands::other::on_ad(&state, &i).await;
|
|
}
|
|
if d.custom_id.starts_with("emb:") {
|
|
return commands::embeds::on_component(&state, &i).await;
|
|
}
|
|
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:") {
|
|
return commands::fun::confessions::on_component(&state, &i).await;
|
|
}
|
|
if d.custom_id.starts_with("fm:") {
|
|
return commands::lastfm::on_component(&state, &i).await;
|
|
}
|
|
if d.custom_id.starts_with("gm:") {
|
|
return commands::games::on_component(&state, &i).await;
|
|
}
|
|
if d.custom_id.starts_with("qt:") {
|
|
return commands::media::quote::on_component(&state, &i).await;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
if i.kind != InteractionType::ApplicationCommand {
|
|
return;
|
|
}
|
|
let Some(InteractionData::ApplicationCommand(data)) = i.data.as_ref() else { return };
|
|
let Some(command) = state.registry.find_slash(&data.name) else { return };
|
|
let mut args = Args::default();
|
|
for o in &data.options {
|
|
let text = match &o.value {
|
|
CommandOptionValue::String(s) => s.clone(),
|
|
CommandOptionValue::Integer(n) => n.to_string(),
|
|
CommandOptionValue::Boolean(b) => b.to_string(),
|
|
CommandOptionValue::User(id) => id.get().to_string(),
|
|
CommandOptionValue::Role(id) => id.get().to_string(),
|
|
CommandOptionValue::Channel(id) => id.get().to_string(),
|
|
CommandOptionValue::Attachment(id) => id.get().to_string(),
|
|
_ => continue,
|
|
};
|
|
args.0.insert(o.name.clone(), text);
|
|
}
|
|
let (Some(user), Some(channel)) = (i.author(), i.channel.as_ref()) else { return };
|
|
let target_message = data.target_id.and_then(|t| data.resolved.as_ref()?.messages.get(&t.cast()).cloned());
|
|
let target_user = data.target_id.and_then(|t| data.resolved.as_ref()?.users.get(&t.cast()).cloned());
|
|
let ctx = Ctx {
|
|
state: state.clone(),
|
|
invoked: command.name,
|
|
guild_id: i.guild_id,
|
|
user_id: user.id,
|
|
user_name: user.name.clone(),
|
|
args,
|
|
channel_id: channel.id,
|
|
reply_to: None,
|
|
reply_msg: None,
|
|
message_id: None,
|
|
target_message,
|
|
target_user,
|
|
attachments: data.resolved.as_ref().map(|r| r.attachments.values().cloned().collect()).unwrap_or_default(),
|
|
locale: i.locale.clone(),
|
|
origin: Origin::Interaction {
|
|
id: i.id,
|
|
token: i.token.clone(),
|
|
permissions: i.member.as_ref().and_then(|m| m.permissions),
|
|
responded: Default::default(),
|
|
deferred: Default::default(),
|
|
},
|
|
};
|
|
let name = command.name;
|
|
run_command(&state, name, ctx).await;
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() -> Result<()> {
|
|
rustls::crypto::ring::default_provider().install_default().expect("crypto provider");
|
|
let _ = dotenvy::dotenv();
|
|
use std::io::IsTerminal as _;
|
|
use tracing_subscriber::layer::SubscriberExt as _;
|
|
use tracing_subscriber::util::SubscriberInitExt as _;
|
|
let console = std::env::var("DEZIO_LIVE").as_deref() == Ok("1") && std::io::stdout().is_terminal() && !std::env::args().any(|a| a == "--headless");
|
|
let filter = tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into());
|
|
if console {
|
|
tracing_subscriber::registry().with(filter).with(tui::BufferLayer).init();
|
|
} else {
|
|
tracing_subscriber::fmt().with_env_filter(filter).init();
|
|
}
|
|
|
|
let token = std::env::var("DISCORD_BOT_TOKEN").context("DISCORD_BOT_TOKEN is not set")?;
|
|
// twilight cuts requests off after 10 s by default, which is far too short for uploading a video
|
|
let http = Arc::new(Client::builder().token(token.clone()).timeout(std::time::Duration::from_secs(180)).build());
|
|
let registry = cmd::Registry::new(commands::all());
|
|
tracing::info!("loaded {} commands", registry.all().len());
|
|
|
|
// `--web-dev`: only the web pages, with a made-up signed-in session (cookie dezio_session=devtoken) — for looking at the dashboard.
|
|
if std::env::args().any(|a| a == "--web-dev") {
|
|
let state: &'static Arc<State> = Box::leak(Box::new(Arc::new(State::new(http.clone(), registry, token.clone()))));
|
|
state.set_app_id(twilight_model::id::Id::new(1));
|
|
state.set_bot_id(twilight_model::id::Id::new(2));
|
|
web::start_dev(state.clone());
|
|
tokio::signal::ctrl_c().await?;
|
|
return Ok(());
|
|
}
|
|
|
|
// The live bot runs on the Chromebook. Logging in here would make it answer twice.
|
|
if std::env::var("DEZIO_LIVE").as_deref() != Ok("1") {
|
|
tracing::warn!("DEZIO_LIVE is not 1: offline check only, not connecting to Discord");
|
|
for c in registry.all() {
|
|
println!("{:<12} {:<10} {}", c.name, c.category, c.description);
|
|
}
|
|
return Ok(());
|
|
}
|
|
|
|
let state: &'static Arc<State> = Box::leak(Box::new(Arc::new(State::new(http.clone(), registry, token.clone()))));
|
|
let app = http.current_user_application().await?.model().await?;
|
|
state.set_app_id(app.id);
|
|
let mut owners: Vec<_> = app.owner.iter().map(|o| o.id).collect();
|
|
if let Some(team) = &app.team {
|
|
owners.extend(team.members.iter().map(|m| m.user.id));
|
|
}
|
|
state.set_owners(owners);
|
|
state.set_bot_id(http.current_user().await?.model().await?.id);
|
|
sync_commands(state).await?;
|
|
|
|
let config = Config::new(token, Intents::all());
|
|
let shards: Vec<_> = create_recommended(&http, config, |_, b| b.build()).await?.collect();
|
|
let _ = state.senders.set(shards.iter().map(|s| s.sender()).collect());
|
|
let senders = shards.iter().map(|s| (s.id().number(), s.sender())).collect();
|
|
let _ = state.voice.set(Arc::new(songbird::Songbird::twilight(Arc::new(songbird::shards::TwilightMap::new(senders)), state.bot_id())));
|
|
let mut tasks = Vec::new();
|
|
for mut shard in shards {
|
|
let state = state.clone();
|
|
tasks.push(tokio::spawn(async move {
|
|
while let Some(item) = shard.next_event(EventTypeFlags::all()).await {
|
|
let event = match item {
|
|
Ok(e) => e,
|
|
Err(e) => {
|
|
tracing::warn!("gateway: {e}");
|
|
continue;
|
|
}
|
|
};
|
|
if let Some(l) = shard.latency().recent().first() {
|
|
state.gateway_ms.store(l.as_millis() as u64, std::sync::atomic::Ordering::Relaxed);
|
|
}
|
|
// what the cache knew about a member before this event changes it
|
|
let before = match &event {
|
|
Event::MemberUpdate(u) => state.cache.member(u.guild_id, u.user.id).map(|m| (m.pending(), m.roles().to_vec(), m.nick().map(str::to_string))),
|
|
Event::MemberRemove(r) => state.cache.member(r.guild_id, r.user.id).map(|m| (m.pending(), m.roles().to_vec(), m.nick().map(str::to_string))),
|
|
_ => None,
|
|
};
|
|
// a server that goes away: remember who it was before the cache forgets
|
|
let leaving = match &event {
|
|
Event::GuildDelete(g) if g.unavailable != Some(true) => state.cache.guild(g.id).map(|c| (g.id, c.name().to_string(), c.owner_id(), c.member_count().unwrap_or(0))),
|
|
_ => None,
|
|
};
|
|
if matches!(event, Event::VoiceServerUpdate(_) | Event::VoiceStateUpdate(_)) {
|
|
if let Some(voice) = state.voice.get() {
|
|
let (voice, e) = (voice.clone(), event.clone());
|
|
tokio::spawn(async move { voice.process(&e).await });
|
|
}
|
|
}
|
|
if let Event::VoiceStateUpdate(v) = &event {
|
|
if v.user_id == state.bot_id() && v.channel_id.is_none() {
|
|
if let Some(g) = v.guild_id {
|
|
tokio::spawn(commands::music::on_bot_left(state.clone(), g));
|
|
}
|
|
}
|
|
}
|
|
let pre = commands::logs::events::capture(&state, &event);
|
|
state.cache.update(&event);
|
|
commands::snipe::record(&state, &event, &pre);
|
|
tokio::spawn(commands::logs::events::handle(state.clone(), event.clone(), pre));
|
|
match event {
|
|
Event::MemberAdd(m) => {
|
|
let (state, m) = (state.clone(), *m);
|
|
tokio::spawn(async move {
|
|
if !m.member.pending {
|
|
commands::welcome::give_roles(&state, m.guild_id, m.member.user.id).await;
|
|
}
|
|
commands::welcome::send_message(&state, m.guild_id, &m.member.user, m.member.nick.as_deref(), "welcome").await;
|
|
});
|
|
}
|
|
Event::MemberUpdate(u) => {
|
|
if before.as_ref().is_some_and(|b| b.0) && !u.pending {
|
|
let state = state.clone();
|
|
tokio::spawn(async move { commands::welcome::give_roles(&state, u.guild_id, u.user.id).await });
|
|
}
|
|
}
|
|
Event::MemberRemove(r) => {
|
|
let (roles, nick) = before.map(|b| (b.1, b.2)).unwrap_or_default();
|
|
commands::welcome::remember_roles(r.guild_id, r.user.id, &roles, &state);
|
|
let state = state.clone();
|
|
tokio::spawn(async move {
|
|
commands::welcome::send_message(&state, r.guild_id, &r.user, nick.as_deref(), "goodbye").await;
|
|
});
|
|
}
|
|
Event::GuildDelete(_) => {
|
|
presence::update(&state);
|
|
tui::activity("Removed from a server");
|
|
if let Some((id, name, owner, members)) = leaving {
|
|
state.known_guilds.lock().unwrap().remove(&id.get());
|
|
let state = state.clone();
|
|
tokio::spawn(async move { commands::other::dm_owner(&state, id, name, owner, members, false).await });
|
|
}
|
|
}
|
|
Event::GuildCreate(g) => {
|
|
presence::update(&state);
|
|
if let twilight_model::gateway::payload::incoming::GuildCreate::Available(guild) = &*g {
|
|
tui::activity(format!("Server available: {} ({} members)", guild.name, guild.member_count.unwrap_or(0)));
|
|
}
|
|
if let twilight_model::gateway::payload::incoming::GuildCreate::Available(guild) = &*g {
|
|
// a server we weren't in when we connected = a new join
|
|
if state.known_guilds.lock().unwrap().insert(guild.id.get()) {
|
|
let (state, id, name, owner, members) = (state.clone(), guild.id, guild.name.clone(), guild.owner_id, guild.member_count.unwrap_or(0));
|
|
tokio::spawn(async move { commands::other::dm_owner(&state, id, name, owner, members, true).await });
|
|
}
|
|
}
|
|
tokio::spawn(commands::logs::events::warm_up(state.clone(), g.id()));
|
|
// like discord.py's chunking: ask for the whole member list so names can be looked up
|
|
let request = RequestGuildMembers::builder(g.id()).query("", None);
|
|
shard.command(&request);
|
|
}
|
|
Event::Ready(r) => {
|
|
state.ready.store(true, std::sync::atomic::Ordering::Relaxed);
|
|
presence::update(&state);
|
|
state.known_guilds.lock().unwrap().extend(r.guilds.iter().map(|g| g.id.get()));
|
|
commands::fun::phone::start_watch(state.clone());
|
|
commands::fun::ai::start(state.clone());
|
|
tokio::spawn({
|
|
let state = state.clone();
|
|
async move { emojis::sync(&state).await }
|
|
});
|
|
commands::games::start_watch(state.clone());
|
|
commands::music::start_watch(state.clone());
|
|
commands::reactionroles::start_watch(state.clone());
|
|
hosted::start_cleanup();
|
|
web::start(state.clone());
|
|
tracing::info!("ready as {} in {} guilds", r.user.name, r.guilds.len());
|
|
}
|
|
Event::MessageUpdate(u) => {
|
|
tokio::spawn(commands::fun::phone::on_edit(state.clone(), *u));
|
|
}
|
|
Event::MessageDelete(d) => {
|
|
tokio::spawn(commands::fun::phone::on_delete(state.clone(), d.channel_id, d.id));
|
|
}
|
|
Event::ReactionAdd(r) => {
|
|
tokio::spawn(commands::reactionroles::on_reaction(state.clone(), commands::reactionroles::Reaction { guild_id: r.guild_id, channel_id: r.channel_id, message_id: r.message_id, user_id: r.user_id, emoji: r.emoji.clone(), bot: r.member.as_ref().map(|m| m.user.bot) }, true));
|
|
tokio::spawn(commands::fun::phone::on_reaction(state.clone(), r.channel_id, r.message_id, r.user_id, r.emoji.clone(), true));
|
|
}
|
|
Event::ReactionRemove(r) => {
|
|
tokio::spawn(commands::reactionroles::on_reaction(state.clone(), commands::reactionroles::Reaction { guild_id: r.guild_id, channel_id: r.channel_id, message_id: r.message_id, user_id: r.user_id, emoji: r.emoji.clone(), bot: r.member.as_ref().map(|m| m.user.bot) }, false));
|
|
tokio::spawn(commands::fun::phone::on_reaction(state.clone(), r.channel_id, r.message_id, r.user_id, r.emoji.clone(), false));
|
|
}
|
|
Event::MessageCreate(m) => {
|
|
tokio::spawn(commands::fun::phone::on_message(state.clone(), m.0.clone()));
|
|
tokio::spawn(commands::games::on_chat(state.clone(), m.0.clone()));
|
|
tokio::spawn(commands::fun::ai::on_message(state.clone(), m.0.clone()));
|
|
tokio::spawn(commands::channels::on_message(state.clone(), m.0.clone()));
|
|
tokio::spawn(commands::other::on_message(state.clone(), m.0.clone()));
|
|
tokio::spawn(on_message(state.clone(), m.0));
|
|
}
|
|
Event::InteractionCreate(i) => {
|
|
tokio::spawn(on_interaction(state.clone(), i.0));
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
if console {
|
|
// the interactive console runs here; quitting it shuts the bot down
|
|
if let Err(e) = tui::run(state.clone()).await {
|
|
eprintln!("console stopped: {e}");
|
|
}
|
|
} else {
|
|
tokio::select! {
|
|
_ = tokio::signal::ctrl_c() => tracing::info!("shutting down"),
|
|
_ = futures::future::join_all(tasks) => {}
|
|
}
|
|
}
|
|
storage::flush_all();
|
|
Ok(())
|
|
}
|