//! The setup wizard's Discord steps (`app/src/admin.spec.md`, "Admin commands"): check a bot //! token, the Message Content intent and the invite link, and list servers and channels for the //! pickers. REST only: nothing here connects to the gateway or joins anything. use serde::Serialize; use serenity::all::{ApplicationFlags, ChannelType, GuildId, Http, Permissions}; /// What the bot needs: read and post in chat channels (reply, react, delete, pin), keep channel /// names and topics in step (desktop-app.md), and talk in voice. pub fn needed_permissions() -> Permissions { Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES | Permissions::READ_MESSAGE_HISTORY | Permissions::ADD_REACTIONS | Permissions::MANAGE_MESSAGES | Permissions::MANAGE_CHANNELS | Permissions::CONNECT | Permissions::SPEAK | Permissions::USE_VAD } /// The link that adds the bot to a server with those permissions and its slash command. pub fn invite_url(application_id: u64) -> String { format!("https://discord.com/oauth2/authorize?client_id={application_id}&scope=bot%20applications.commands&permissions={}", needed_permissions().bits()) } /// The Message Content intent is on (either the full or the limited flag of unverified bots). pub fn message_content_on(flags: Option) -> bool { flags.is_some_and(|f| f.intersects(ApplicationFlags::GATEWAY_MESSAGE_CONTENT | ApplicationFlags::GATEWAY_MESSAGE_CONTENT_LIMITED)) } #[derive(Debug, Clone, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TokenCheck { pub bot_tag: String, pub bot_id: String, pub application_id: String, pub message_content: bool, pub invite_url: String, } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct Named { pub id: String, pub name: String, } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct Channels { pub voice: Vec, pub text: Vec, } fn err(e: serenity::Error) -> String { match e { serenity::Error::Http(h) if h.status_code().is_some_and(|s| s.as_u16() == 401) => "디스코드가 이 봇 토큰을 받아들이지 않았습니다".into(), e => format!("디스코드에 연결하지 못했습니다: {e}"), } } /// Check a token without storing it. pub async fn check_token(token: &str) -> Result { let http = Http::new(token.trim()); let me = http.get_current_user().await.map_err(err)?; let app = http.get_current_application_info().await.map_err(err)?; Ok(TokenCheck { bot_tag: me.tag(), bot_id: me.id.to_string(), application_id: app.id.to_string(), message_content: message_content_on(app.flags), invite_url: invite_url(app.id.get()) }) } /// The servers the bot is in. pub async fn guilds(token: &str) -> Result, String> { let list = Http::new(token).get_guilds(None, Some(200)).await.map_err(err)?; Ok(list.into_iter().map(|g| Named { id: g.id.to_string(), name: g.name }).collect()) } /// A server's voice and text channels, in their server order. pub async fn channels(token: &str, guild_id: u64) -> Result { let mut list = Http::new(token).get_channels(GuildId::new(guild_id)).await.map_err(err)?; list.sort_by_key(|c| c.position); let pick = |kinds: &[ChannelType]| list.iter().filter(|c| kinds.contains(&c.kind)) .map(|c| Named { id: c.id.to_string(), name: c.name.clone() }).collect(); Ok(Channels { voice: pick(&[ChannelType::Voice, ChannelType::Stage]), text: pick(&[ChannelType::Text]) }) } #[cfg(test)] mod tests { use super::*; #[test] fn the_invite_asks_for_the_bot_its_command_and_its_permissions() { let url = invite_url(123456789012345678); assert!(url.contains("client_id=123456789012345678")); assert!(url.contains("scope=bot%20applications.commands")); let bits: u64 = url.rsplit("permissions=").next().unwrap().parse().unwrap(); let p = Permissions::from_bits_truncate(bits); for need in [Permissions::CONNECT, Permissions::SPEAK, Permissions::SEND_MESSAGES, Permissions::MANAGE_CHANNELS] { assert!(p.contains(need), "{need:?}"); } assert!(!p.contains(Permissions::ADMINISTRATOR)); } #[test] fn message_content_counts_when_full_or_limited() { assert!(message_content_on(Some(ApplicationFlags::GATEWAY_MESSAGE_CONTENT))); assert!(message_content_on(Some(ApplicationFlags::GATEWAY_MESSAGE_CONTENT_LIMITED))); assert!(!message_content_on(Some(ApplicationFlags::GATEWAY_GUILD_MEMBERS))); assert!(!message_content_on(None)); } }