1wit_bindgen::generate!({
2 world: "discord-plugin",
3 path: "wit",
4 pub_export_macro: true,
5 export_macro_name: "export",
6 additional_derives: [PartialEq, Eq],
7});
8
9
10
11#[cfg(test)]
12extern crate self as santity_pdk;
13
14pub mod audit;
15pub mod brand;
16pub mod channel;
17pub mod guild;
18pub mod voice;
19
20pub use audit::{AuditLogAction, AuditLogEntry};
21pub use brand::{BrandColor, BrandEmbed};
22pub use channel::Channel;
23pub use exports::segv::santity::handler::Guest;
24pub use guild::{CreatedChannel, DiscordApiError, Guild};
25pub use segv::santity::host::{
26 cancel_timer as wit_cancel_timer, db_get, db_increment, db_set, discord_request, http_fetch, log as wit_log,
27 schedule_interval as wit_schedule_interval, schedule_timeout as wit_schedule_timeout,
28 send_message,
29};
30pub use segv::santity::types::*;
31
32impl InteractionEvent {
33 pub fn get_option_value(&self, name: &str) -> Option<serde_json::Value> {
36 let parsed: serde_json::Value = serde_json::from_str(&self.options_json).ok()?;
37
38 fn find_in_options(opts: &[serde_json::Value], target: &str) -> Option<serde_json::Value> {
39 for opt in opts {
40 if opt.get("name").and_then(|n| n.as_str()) == Some(target) {
41 if let Some(val) = opt.get("value") {
42 return Some(val.clone());
43 }
44 }
45 if let Some(sub_opts) = opt.get("options").and_then(|o| o.as_array()) {
46 if let Some(val) = find_in_options(sub_opts, target) {
47 return Some(val);
48 }
49 }
50 }
51 None
52 }
53
54 if let serde_json::Value::Array(ref options) = parsed {
55 find_in_options(options, name)
56 } else {
57 None
58 }
59 }
60
61 pub fn get_subcommand_name(&self) -> Option<String> {
63 let parsed: serde_json::Value = serde_json::from_str(&self.options_json).ok()?;
64 if let serde_json::Value::Array(options) = parsed {
65 for opt in options {
66 let opt_type = opt.get("type").and_then(|t| t.as_u64()).unwrap_or(0);
67 if opt_type == 1 {
68 return opt.get("name").and_then(|n| n.as_str()).map(|s| s.to_string());
69 } else if opt_type == 2 {
70 if let Some(sub_opts) = opt.get("options").and_then(|o| o.as_array()) {
71 for sub_opt in sub_opts {
72 let sub_type = sub_opt.get("type").and_then(|t| t.as_u64()).unwrap_or(0);
73 if sub_type == 1 {
74 return sub_opt.get("name").and_then(|n| n.as_str()).map(|s| s.to_string());
75 }
76 }
77 }
78 }
79 }
80 }
81 None
82 }
83
84 pub fn get_str(&self, name: &str) -> Option<String> {
86 self.get_option_value(name).and_then(|v| match v {
87 serde_json::Value::String(s) => Some(s),
88 _ => None,
89 })
90 }
91
92 pub fn get_int(&self, name: &str) -> Option<i64> {
94 self.get_option_value(name).and_then(|v| match v {
95 serde_json::Value::Number(n) => n.as_i64(),
96 serde_json::Value::String(s) => s.parse::<i64>().ok(),
97 _ => None,
98 })
99 }
100
101 pub fn get_bool(&self, name: &str) -> Option<bool> {
103 self.get_option_value(name).and_then(|v| match v {
104 serde_json::Value::Bool(b) => Some(b),
105 serde_json::Value::String(s) => s.parse::<bool>().ok(),
106 _ => None,
107 })
108 }
109
110 pub fn get_user_id(&self, name: &str) -> Option<String> {
112 self.get_str(name)
113 }
114
115 pub fn get_channel_id(&self, name: &str) -> Option<String> {
117 self.get_str(name)
118 }
119
120 pub fn get_role_id(&self, name: &str) -> Option<String> {
122 self.get_str(name)
123 }
124
125 pub fn get_field(&self, custom_id: &str) -> Option<String> {
127 self.modal_fields
128 .iter()
129 .find(|f| f.custom_id == custom_id)
130 .map(|f| f.value.clone())
131 }
132
133 pub fn get_values(&self) -> &[String] {
135 &self.values
136 }
137
138 pub fn get_custom_id(&self) -> Option<&str> {
140 self.custom_id.as_deref()
141 }
142}
143
144impl Default for InteractionEvent {
145 fn default() -> Self {
146 InteractionEvent {
147 id: String::new(),
148 application_id: String::new(),
149 token: String::new(),
150 kind: InteractionKind::Unknown,
151 command_name: String::new(),
152 custom_id: None,
153 channel_id: String::new(),
154 guild_id: None,
155 user: User {
156 id: String::new(),
157 username: String::new(),
158 discriminator: String::new(),
159 bot: false,
160 },
161 options_json: "[]".to_string(),
162 values: Vec::new(),
163 modal_fields: Vec::new(),
164 focused_option_name: None,
165 focused_option_value: None,
166 }
167 }
168}
169
170impl ResponseAction {
171 pub fn reply(msg: impl Into<String>) -> Self {
172 ResponseAction::Reply(msg.into())
173 }
174
175 pub fn reply_message(payload: MessagePayload) -> Self {
176 ResponseAction::ReplyMessage(payload)
177 }
178
179 pub fn ephemeral(msg: impl Into<String>) -> Self {
180 ResponseAction::ReplyMessage(MessageBuilder::new().content(msg).ephemeral(true).build())
181 }
182
183 pub fn reply_ephemeral(msg: impl Into<String>) -> Self {
184 Self::ephemeral(msg)
185 }
186
187 pub fn reply_embed(embed: Embed) -> Self {
188 ResponseAction::ReplyMessage(MessagePayload {
189 content: None,
190 embeds: vec![embed],
191 components: vec![],
192 ephemeral: false,
193 })
194 }
195
196 pub fn reply_ephemeral_embed(embed: Embed) -> Self {
197 ResponseAction::ReplyMessage(MessagePayload {
198 content: None,
199 embeds: vec![embed],
200 components: vec![],
201 ephemeral: true,
202 })
203 }
204
205 pub fn modal(modal_def: ModalDef) -> Self {
206 ResponseAction::Modal(modal_def)
207 }
208
209 pub fn autocomplete_result(choices: Vec<AutocompleteChoice>) -> Self {
210 ResponseAction::AutocompleteResult(choices)
211 }
212
213 pub fn defer_ephemeral() -> Self {
214 ResponseAction::DeferEphemeral
215 }
216
217 pub fn none() -> Self {
218 ResponseAction::None
219 }
220}
221
222#[derive(Default, Clone, Debug)]
227pub struct EmbedBuilder {
228 title: Option<String>,
229 description: Option<String>,
230 url: Option<String>,
231 color: Option<u32>,
232 fields: Vec<EmbedField>,
233 footer: Option<EmbedFooter>,
234 author: Option<EmbedAuthor>,
235 image_url: Option<String>,
236 thumbnail_url: Option<String>,
237 timestamp: Option<String>,
238}
239
240impl EmbedBuilder {
241 pub fn new() -> Self {
242 Self::default()
243 }
244
245 pub fn title(mut self, title: impl Into<String>) -> Self {
246 self.title = Some(title.into());
247 self
248 }
249
250 pub fn description(mut self, description: impl Into<String>) -> Self {
251 self.description = Some(description.into());
252 self
253 }
254
255 pub fn url(mut self, url: impl Into<String>) -> Self {
256 self.url = Some(url.into());
257 self
258 }
259
260 pub fn color(mut self, color: u32) -> Self {
261 self.color = Some(color);
262 self
263 }
264
265 pub fn timestamp(mut self, timestamp: impl Into<String>) -> Self {
266 self.timestamp = Some(timestamp.into());
267 self
268 }
269
270 pub fn footer(mut self, text: impl Into<String>, icon_url: Option<String>) -> Self {
271 self.footer = Some(EmbedFooter {
272 text: text.into(),
273 icon_url,
274 });
275 self
276 }
277
278 pub fn author(
279 mut self,
280 name: impl Into<String>,
281 url: Option<String>,
282 icon_url: Option<String>,
283 ) -> Self {
284 self.author = Some(EmbedAuthor {
285 name: name.into(),
286 url,
287 icon_url,
288 });
289 self
290 }
291
292 pub fn image(mut self, url: impl Into<String>) -> Self {
293 self.image_url = Some(url.into());
294 self
295 }
296
297 pub fn thumbnail(mut self, url: impl Into<String>) -> Self {
298 self.thumbnail_url = Some(url.into());
299 self
300 }
301
302 pub fn field(mut self, name: impl Into<String>, value: impl Into<String>, inline: bool) -> Self {
303 self.fields.push(EmbedField {
304 name: name.into(),
305 value: value.into(),
306 inline,
307 });
308 self
309 }
310
311 pub fn build(self) -> Embed {
312 Embed {
313 title: self.title,
314 description: self.description,
315 url: self.url,
316 color: self.color,
317 fields: self.fields,
318 footer: self.footer,
319 author: self.author,
320 image_url: self.image_url,
321 thumbnail_url: self.thumbnail_url,
322 timestamp: self.timestamp,
323 }
324 }
325}
326
327#[derive(Default, Clone, Debug)]
328pub struct MessageBuilder {
329 content: Option<String>,
330 embeds: Vec<Embed>,
331 components: Vec<ActionRow>,
332 ephemeral: bool,
333}
334
335impl MessageBuilder {
336 pub fn new() -> Self {
337 Self::default()
338 }
339
340 pub fn content(mut self, content: impl Into<String>) -> Self {
341 self.content = Some(content.into());
342 self
343 }
344
345 pub fn embed(mut self, embed: Embed) -> Self {
346 self.embeds.push(embed);
347 self
348 }
349
350 pub fn button(mut self, button: ComponentButton) -> Self {
351 if let Some(last_row) = self.components.last_mut() {
352 if last_row.components.len() < 5 {
353 last_row.components.push(ComponentItem::Button(button));
354 return self;
355 }
356 }
357 self.components.push(ActionRow {
358 components: vec![ComponentItem::Button(button)],
359 });
360 self
361 }
362
363 pub fn select_menu(mut self, menu: ComponentSelectMenu) -> Self {
364 self.components.push(ActionRow {
365 components: vec![ComponentItem::SelectMenu(menu)],
366 });
367 self
368 }
369
370 pub fn action_row(mut self, row: ActionRow) -> Self {
371 self.components.push(row);
372 self
373 }
374
375 pub fn ephemeral(mut self, ephemeral: bool) -> Self {
376 self.ephemeral = ephemeral;
377 self
378 }
379
380 pub fn build(self) -> MessagePayload {
381 MessagePayload {
382 content: self.content,
383 embeds: self.embeds,
384 components: self.components,
385 ephemeral: self.ephemeral,
386 }
387 }
388}
389
390pub struct Button;
391
392impl Button {
393 pub fn primary(custom_id: impl Into<String>, label: impl Into<String>) -> ComponentButton {
394 ComponentButton {
395 custom_id: custom_id.into(),
396 label: label.into(),
397 style: ButtonStyle::Primary,
398 url: None,
399 disabled: false,
400 emoji: None,
401 }
402 }
403
404 pub fn secondary(custom_id: impl Into<String>, label: impl Into<String>) -> ComponentButton {
405 ComponentButton {
406 custom_id: custom_id.into(),
407 label: label.into(),
408 style: ButtonStyle::Secondary,
409 url: None,
410 disabled: false,
411 emoji: None,
412 }
413 }
414
415 pub fn success(custom_id: impl Into<String>, label: impl Into<String>) -> ComponentButton {
416 ComponentButton {
417 custom_id: custom_id.into(),
418 label: label.into(),
419 style: ButtonStyle::Success,
420 url: None,
421 disabled: false,
422 emoji: None,
423 }
424 }
425
426 pub fn danger(custom_id: impl Into<String>, label: impl Into<String>) -> ComponentButton {
427 ComponentButton {
428 custom_id: custom_id.into(),
429 label: label.into(),
430 style: ButtonStyle::Danger,
431 url: None,
432 disabled: false,
433 emoji: None,
434 }
435 }
436
437 pub fn link(url: impl Into<String>, label: impl Into<String>) -> ComponentButton {
438 ComponentButton {
439 custom_id: String::new(),
440 label: label.into(),
441 style: ButtonStyle::Link,
442 url: Some(url.into()),
443 disabled: false,
444 emoji: None,
445 }
446 }
447}
448
449pub struct ModalBuilder {
450 modal: ModalDef,
451}
452
453impl ModalBuilder {
454 pub fn new(custom_id: impl Into<String>, title: impl Into<String>) -> Self {
455 Self {
456 modal: ModalDef {
457 custom_id: custom_id.into(),
458 title: title.into(),
459 components: Vec::new(),
460 },
461 }
462 }
463
464 pub fn text_input(
465 mut self,
466 custom_id: impl Into<String>,
467 label: impl Into<String>,
468 style: TextInputStyle,
469 ) -> Self {
470 self.modal.components.push(ModalTextInput {
471 custom_id: custom_id.into(),
472 label: label.into(),
473 style,
474 min_length: None,
475 max_length: None,
476 required: true,
477 value: None,
478 placeholder: None,
479 });
480 self
481 }
482
483 pub fn optional_text_input(
484 mut self,
485 custom_id: impl Into<String>,
486 label: impl Into<String>,
487 style: TextInputStyle,
488 ) -> Self {
489 self.modal.components.push(ModalTextInput {
490 custom_id: custom_id.into(),
491 label: label.into(),
492 style,
493 min_length: None,
494 max_length: None,
495 required: false,
496 value: None,
497 placeholder: None,
498 });
499 self
500 }
501
502 pub fn build(self) -> ModalDef {
503 self.modal
504 }
505}
506
507impl AutocompleteChoice {
508 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
509 Self {
510 name: name.into(),
511 value: value.into(),
512 }
513 }
514}
515
516pub mod timer {
521 use super::*;
522
523 pub fn interval(interval_secs: u64, tag: impl Into<String>) -> Result<u64, PdkError> {
525 wit_schedule_interval(interval_secs, &tag.into()).map_err(PdkError::Host)
526 }
527
528 pub fn timeout(delay_secs: u64, tag: impl Into<String>) -> Result<u64, PdkError> {
530 wit_schedule_timeout(delay_secs, &tag.into()).map_err(PdkError::Host)
531 }
532
533 pub fn cancel(timer_id: u64) -> Result<(), PdkError> {
535 wit_cancel_timer(timer_id).map_err(PdkError::Host)
536 }
537}
538
539use log::{Level, LevelFilter, Metadata, Record, SetLoggerError};
540
541pub use log::{debug, error, info, trace, warn};
543pub use santity_pdk_macro::plugin;
544pub use serde::{Deserialize, Serialize};
545pub use serde_json;
546
547pub mod prelude {
548 pub use super::exports;
549 pub use super::exports::segv::santity::handler::Guest;
550 pub use super::exports::segv::santity::handler::Guest as PluginHandler;
551 pub use super::http;
552 pub use super::plugin;
553 pub use super::router::Router;
554 pub use super::segv::santity::types::*;
555 pub use super::storage;
556 pub use super::timer;
557 pub use super::{
558 AutocompleteChoice, Button, EmbedBuilder, MessageBuilder, ModalBuilder, PdkError,
559 ResponseAction,
560 };
561 pub use log::{debug, error, info, trace, warn};
562 pub use serde::{Deserialize, Serialize};
563 pub use serde_json;
564}
565
566
567
568
569pub struct SantityLogger;
575
576static LOGGER: SantityLogger = SantityLogger;
577
578impl log::Log for SantityLogger {
579 fn enabled(&self, metadata: &Metadata) -> bool {
580 metadata.level() <= log::max_level()
581 }
582
583 fn log(&self, record: &Record) {
584 if self.enabled(record.metadata()) {
585 let wit_level = match record.level() {
586 Level::Trace => LogLevel::Trace,
587 Level::Debug => LogLevel::Debug,
588 Level::Info => LogLevel::Info,
589 Level::Warn => LogLevel::Warn,
590 Level::Error => LogLevel::Error,
591 };
592 let message = format!("{}", record.args());
593 wit_log(wit_level, &message);
594 }
595 }
596
597 fn flush(&self) {}
598}
599
600pub fn init() -> Result<(), SetLoggerError> {
602 init_with_level(LevelFilter::Trace)
603}
604
605pub fn init_with_level(level: LevelFilter) -> Result<(), SetLoggerError> {
607 log::set_logger(&LOGGER)?;
608 log::set_max_level(level);
609 Ok(())
610}
611
612#[derive(Debug, thiserror::Error)]
617pub enum PdkError {
618 #[error("Host error: {0:?}")]
619 Host(HostError),
620
621 #[error("Host storage error: {0:?}")]
622 Storage(HostError),
623
624 #[error("Serialization error: {0}")]
625 Serialization(String),
626
627 #[error("Deserialization error: {0}")]
628 Deserialization(String),
629
630 #[error("PDK Error: {0}")]
631 Other(String),
632}
633
634pub mod storage {
635 use super::*;
636 use serde::{de::DeserializeOwned, Serialize};
637
638 pub fn set<T: Serialize>(key: &str, value: &T) -> Result<(), PdkError> {
640 let json_str = serde_json::to_string(value)
641 .map_err(|e| PdkError::Serialization(e.to_string()))?;
642 db_set(key, &json_str).map_err(PdkError::Storage)
643 }
644
645 pub fn get<T: DeserializeOwned>(key: &str) -> Result<Option<T>, PdkError> {
647 match db_get(key).map_err(PdkError::Storage)? {
648 Some(json_str) => {
649 let val = serde_json::from_str(&json_str)
650 .map_err(|e| PdkError::Deserialization(e.to_string()))?;
651 Ok(Some(val))
652 }
653 None => Ok(None),
654 }
655 }
656
657 pub fn increment(key: &str, delta: i64) -> Result<i64, PdkError> {
659 db_increment(key, delta).map_err(PdkError::Storage)
660 }
661
662 pub fn next_id(counter_name: &str) -> Result<u64, PdkError> {
664 let val = increment(counter_name, 1)?;
665 Ok(val as u64)
666 }
667}
668
669pub mod http {
674 use super::*;
675 use serde::{de::DeserializeOwned, Serialize};
676
677 pub struct RequestBuilder {
679 pub url: String,
680 pub method: String,
681 pub headers: Vec<(String, String)>,
682 pub body: Option<Vec<u8>>,
683 }
684
685
686 #[derive(Debug, Clone)]
688 pub struct Response {
689 pub status: u16,
690 pub headers: Vec<(String, String)>,
691 pub body: Vec<u8>,
692 }
693
694 impl Response {
695 pub fn status(&self) -> u16 {
697 self.status
698 }
699
700 pub fn is_success(&self) -> bool {
702 (200..=299).contains(&self.status)
703 }
704
705 pub fn text(&self) -> Result<String, PdkError> {
707 String::from_utf8(self.body.clone())
708 .map_err(|e| PdkError::Deserialization(e.to_string()))
709 }
710
711 pub fn json<T: DeserializeOwned>(&self) -> Result<T, PdkError> {
713 serde_json::from_slice(&self.body)
714 .map_err(|e| PdkError::Deserialization(e.to_string()))
715 }
716 }
717
718 pub fn get(url: impl Into<String>) -> RequestBuilder {
720 RequestBuilder::new("GET", url)
721 }
722
723 pub fn post(url: impl Into<String>) -> RequestBuilder {
725 RequestBuilder::new("POST", url)
726 }
727
728 pub fn put(url: impl Into<String>) -> RequestBuilder {
730 RequestBuilder::new("PUT", url)
731 }
732
733 pub fn delete(url: impl Into<String>) -> RequestBuilder {
735 RequestBuilder::new("DELETE", url)
736 }
737
738 impl RequestBuilder {
739 pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
740 Self {
741 url: url.into(),
742 method: method.into().to_uppercase(),
743 headers: Vec::new(),
744 body: None,
745 }
746 }
747
748 pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
749 let key = key.into();
750 let value = value.into();
751 if let Some(existing) = self.headers.iter_mut().find(|(k, _)| k.eq_ignore_ascii_case(&key)) {
752 existing.1 = value;
753 } else {
754 self.headers.push((key, value));
755 }
756 self
757 }
758
759 pub fn json<T: Serialize>(self, data: &T) -> Result<Self, PdkError> {
760 let json_bytes = serde_json::to_vec(data)
761 .map_err(|e| PdkError::Serialization(e.to_string()))?;
762 let builder = self.header("Content-Type", "application/json");
763 Ok(builder.body(json_bytes))
764 }
765
766
767 pub fn body(mut self, bytes: impl Into<Vec<u8>>) -> Self {
768 self.body = Some(bytes.into());
769 self
770 }
771
772 pub fn send(self) -> Result<Response, PdkError> {
773 let req = HttpRequest {
774 url: self.url,
775 method: self.method,
776 headers: self.headers,
777 body: self.body,
778 };
779 let wit_resp = http_fetch(&req).map_err(PdkError::Host)?;
780 Ok(Response {
781 status: wit_resp.status,
782 headers: wit_resp.headers,
783 body: wit_resp.body,
784 })
785 }
786 }
787}
788
789
790pub mod router {
795 use super::*;
796
797 pub type CommandHandler = fn(InteractionEvent) -> ResponseAction;
798
799 #[derive(Default)]
801 pub struct Router {
802 routes: Vec<(&'static str, CommandHandler)>,
803 fallback: Option<CommandHandler>,
804 }
805
806 impl Router {
807 pub fn new() -> Self {
808 Self {
809 routes: Vec::new(),
810 fallback: None,
811 }
812 }
813
814 pub fn route(mut self, command_name: &'static str, handler: CommandHandler) -> Self {
815 self.routes.push((command_name, handler));
816 self
817 }
818
819 pub fn fallback(mut self, handler: CommandHandler) -> Self {
820 self.fallback = Some(handler);
821 self
822 }
823
824 pub fn handle(&self, event: InteractionEvent) -> ResponseAction {
825 for (name, handler) in &self.routes {
826 if *name == event.command_name {
827 return handler(event);
828 }
829 }
830 if let Some(fallback_fn) = self.fallback {
831 fallback_fn(event)
832 } else {
833 ResponseAction::None
834 }
835 }
836 }
837}
838
839pub use router::Router;
840
841#[cfg(test)]
842mod tests {
843 use super::*;
844
845 #[test]
846 fn test_router_dispatch() {
847 fn handle_ping(_event: InteractionEvent) -> ResponseAction {
848 ResponseAction::Reply("pong".to_string())
849 }
850
851 let router = Router::new().route("ping", handle_ping);
852
853 let event = InteractionEvent {
854 id: "1".to_string(),
855 token: "tok".to_string(),
856 command_name: "ping".to_string(),
857 channel_id: "100".to_string(),
858 user: User {
859 id: "u1".to_string(),
860 username: "testuser".to_string(),
861 discriminator: "0000".to_string(),
862 bot: false,
863 },
864 options_json: "{}".to_string(),
865 ..Default::default()
866 };
867
868 let action = router.handle(event);
869 assert!(matches!(action, ResponseAction::Reply(ref msg) if msg == "pong"));
870 }
871
872 #[test]
873 fn test_router_fallback() {
874 let router = Router::new().fallback(|_| ResponseAction::Reply("unknown".to_string()));
875
876 let event = InteractionEvent {
877 id: "1".to_string(),
878 token: "tok".to_string(),
879 command_name: "unknown_cmd".to_string(),
880 channel_id: "100".to_string(),
881 user: User {
882 id: "u1".to_string(),
883 username: "testuser".to_string(),
884 discriminator: "0000".to_string(),
885 bot: false,
886 },
887 options_json: "{}".to_string(),
888 ..Default::default()
889 };
890
891 let action = router.handle(event);
892 assert!(matches!(action, ResponseAction::Reply(ref msg) if msg == "unknown"));
893 }
894
895 #[test]
896 fn test_http_request_builder() {
897 let req = http::post("https://api.example.com/data")
898 .header("Authorization", "Bearer token123")
899 .json(&serde_json::json!({ "key": "value" }))
900 .unwrap();
901
902 assert_eq!(req.url, "https://api.example.com/data");
903 assert_eq!(req.method, "POST");
904 assert_eq!(
905 req.headers,
906 vec![
907 ("Authorization".to_string(), "Bearer token123".to_string()),
908 ("Content-Type".to_string(), "application/json".to_string())
909 ]
910 );
911 assert!(req.body.is_some());
912 }
913
914 #[test]
915 fn test_http_header_deduplication() {
916 let req = http::post("https://api.example.com/data")
917 .header("Content-Type", "text/plain")
918 .json(&serde_json::json!({ "key": "value" }))
919 .unwrap();
920
921 assert_eq!(
922 req.headers,
923 vec![("Content-Type".to_string(), "application/json".to_string())]
924 );
925 }
926
927 #[test]
928 fn test_interaction_event_option_extractors() {
929 let options_json = serde_json::json!([
930 { "name": "user", "type": 6, "value": "123456789012345678" },
931 { "name": "reason", "type": 3, "value": "Spamming in chat" },
932 { "name": "count", "type": 4, "value": 42 },
933 { "name": "silent", "type": 5, "value": true }
934 ]).to_string();
935
936 let event = InteractionEvent {
937 options_json,
938 ..Default::default()
939 };
940
941 assert_eq!(event.get_str("reason"), Some("Spamming in chat".to_string()));
942 assert_eq!(event.get_user_id("user"), Some("123456789012345678".to_string()));
943 assert_eq!(event.get_int("count"), Some(42));
944 assert_eq!(event.get_bool("silent"), Some(true));
945 assert_eq!(event.get_str("nonexistent"), None);
946 assert_eq!(event.get_int("reason"), None); assert_eq!(event.get_int("user"), Some(123456789012345678)); }
949
950 #[test]
951 fn test_subcommand_recursive_option_extractors() {
952 let nested_subcommand_json = serde_json::json!([
954 {
955 "name": "add",
956 "type": 1,
957 "options": [
958 { "name": "name", "type": 3, "value": "rust" },
959 { "name": "content", "type": 3, "value": "fast" }
960 ]
961 }
962 ]).to_string();
963
964 let event = InteractionEvent {
965 options_json: nested_subcommand_json,
966 ..Default::default()
967 };
968
969 assert_eq!(event.get_subcommand_name(), Some("add".to_string()));
970 assert_eq!(event.get_str("name"), Some("rust".to_string()));
971 assert_eq!(event.get_str("content"), Some("fast".to_string()));
972 assert_eq!(event.get_str("missing"), None);
973
974 let group_subcommand_json = serde_json::json!([
976 {
977 "name": "log",
978 "type": 2,
979 "options": [
980 {
981 "name": "channel",
982 "type": 1,
983 "options": [
984 { "name": "channel_id", "type": 7, "value": "999999" }
985 ]
986 }
987 ]
988 }
989 ]).to_string();
990
991 let event_group = InteractionEvent {
992 options_json: group_subcommand_json,
993 ..Default::default()
994 };
995
996 assert_eq!(event_group.get_subcommand_name(), Some("channel".to_string()));
997 assert_eq!(event_group.get_channel_id("channel_id"), Some("999999".to_string()));
998 assert_eq!(event_group.get_int("channel_id"), Some(999999));
999 }
1000
1001 #[test]
1002 fn test_embed_builder_construction() {
1003 let embed = EmbedBuilder::new()
1004 .title("Server Status")
1005 .description("All systems operational.")
1006 .color(0x00FF00)
1007 .field("Uptime", "99.99%", true)
1008 .field("Latency", "24ms", true)
1009 .footer("Santity Core", None)
1010 .build();
1011
1012 assert_eq!(embed.title.as_deref(), Some("Server Status"));
1013 assert_eq!(embed.description.as_deref(), Some("All systems operational."));
1014 assert_eq!(embed.color, Some(0x00FF00));
1015 assert_eq!(embed.fields.len(), 2);
1016 assert_eq!(embed.fields[0].name, "Uptime");
1017 assert_eq!(embed.fields[0].value, "99.99%");
1018 assert!(embed.fields[0].inline);
1019 assert_eq!(embed.footer.as_ref().map(|f| f.text.as_str()), Some("Santity Core"));
1020 }
1021
1022 #[test]
1023 fn test_message_builder_with_buttons_and_embeds() {
1024 let embed = EmbedBuilder::new().title("Voting Panel").build();
1025 let btn_yes = Button::success("btn_vote_yes", "Vote Yes");
1026 let btn_no = Button::danger("btn_vote_no", "Vote No");
1027
1028 let msg = MessageBuilder::new()
1029 .content("Please cast your vote below:")
1030 .embed(embed)
1031 .button(btn_yes)
1032 .button(btn_no)
1033 .ephemeral(true)
1034 .build();
1035
1036 assert_eq!(msg.content.as_deref(), Some("Please cast your vote below:"));
1037 assert_eq!(msg.embeds.len(), 1);
1038 assert_eq!(msg.components.len(), 1); assert_eq!(msg.components[0].components.len(), 2);
1040 assert!(msg.ephemeral);
1041 }
1042
1043 #[test]
1044 fn test_modal_builder_construction() {
1045 let modal = ModalBuilder::new("ticket_modal", "Open Support Ticket")
1046 .text_input("subject", "Issue Subject", TextInputStyle::Short)
1047 .optional_text_input("details", "Additional Details", TextInputStyle::Paragraph)
1048 .build();
1049
1050 assert_eq!(modal.custom_id, "ticket_modal");
1051 assert_eq!(modal.title, "Open Support Ticket");
1052 assert_eq!(modal.components.len(), 2);
1053 assert_eq!(modal.components[0].custom_id, "subject");
1054 assert!(modal.components[0].required);
1055 assert_eq!(modal.components[1].custom_id, "details");
1056 assert!(!modal.components[1].required);
1057 }
1058
1059 #[test]
1060 fn test_interaction_event_modal_and_component_extractors() {
1061 let event = InteractionEvent {
1062 custom_id: Some("my_btn".to_string()),
1063 values: vec!["val1".to_string(), "val2".to_string()],
1064 modal_fields: vec![
1065 ModalField {
1066 custom_id: "name_field".to_string(),
1067 value: "Santity User".to_string(),
1068 },
1069 ],
1070 ..Default::default()
1071 };
1072
1073 assert_eq!(event.get_custom_id(), Some("my_btn"));
1074 assert_eq!(event.get_values(), &["val1".to_string(), "val2".to_string()]);
1075 assert_eq!(event.get_field("name_field"), Some("Santity User".to_string()));
1076 assert_eq!(event.get_field("missing"), None);
1077 }
1078
1079 struct MockModalPlugin;
1080
1081 #[santity_pdk_macro::plugin(name = "tickets")]
1082 impl MockModalPlugin {
1083 #[command(name = "modal_test", opens_modal = true)]
1084 fn test_modal_cmd() -> ResponseAction {
1085 ResponseAction::Reply("modal_opened".to_string())
1086 }
1087
1088 #[button("btn_ticket")]
1089 fn handle_ticket_btn() -> ResponseAction {
1090 ResponseAction::Reply("ticket_clicked".to_string())
1091 }
1092
1093 #[button("btn_role_")]
1094 fn handle_role_btn(event: InteractionEvent) -> ResponseAction {
1095 let cid = event.custom_id.unwrap_or_default();
1096 ResponseAction::Reply(format!("role_assigned:{}", cid))
1097 }
1098
1099 #[event(member_join)]
1100 fn handle_member_join(payload: String) -> ResponseAction {
1101 ResponseAction::Reply(format!("welcome:{}", payload))
1102 }
1103
1104 #[autocomplete(command = "tag", subcommand = "edit", option = "name")]
1105 fn handle_tag_edit_autocomplete() -> ResponseAction {
1106 ResponseAction::AutocompleteResult(vec![
1107 AutocompleteChoice {
1108 name: "my_tag".to_string(),
1109 value: "my_tag_val".to_string(),
1110 }
1111 ])
1112 }
1113
1114 #[autocomplete(command = "tag", subcommand = "view", option = "name")]
1115 fn handle_tag_view_autocomplete() -> ResponseAction {
1116 ResponseAction::AutocompleteResult(vec![
1117 AutocompleteChoice {
1118 name: "public_tag".to_string(),
1119 value: "public_tag_val".to_string(),
1120 }
1121 ])
1122 }
1123
1124 #[autocomplete(command = "ping", option = "query")]
1125 fn handle_generic_ping_autocomplete() -> ResponseAction {
1126 ResponseAction::AutocompleteResult(vec![
1127 AutocompleteChoice {
1128 name: "ping_choice".to_string(),
1129 value: "ping_choice_val".to_string(),
1130 }
1131 ])
1132 }
1133 }
1134
1135 #[test]
1136 fn test_plugin_macro_opens_modal_and_namespacing() {
1137 use crate::exports::segv::santity::handler::Guest;
1138
1139 let commands = MockModalPlugin::get_slash_commands();
1140 assert_eq!(commands.len(), 1);
1141 assert_eq!(commands[0].name, "modal_test");
1142 assert!(commands[0].opens_modal);
1143
1144 let event_direct = InteractionEvent {
1146 custom_id: Some("btn_ticket".to_string()),
1147 ..Default::default()
1148 };
1149 let res_direct = MockModalPlugin::on_interaction(event_direct);
1150 assert!(matches!(res_direct, ResponseAction::Reply(s) if s == "ticket_clicked"));
1151
1152 let event_namespaced = InteractionEvent {
1154 custom_id: Some("tickets:btn_ticket".to_string()),
1155 ..Default::default()
1156 };
1157 let res_namespaced = MockModalPlugin::on_interaction(event_namespaced);
1158 assert!(matches!(res_namespaced, ResponseAction::Reply(s) if s == "ticket_clicked"));
1159
1160 let event_prefix_direct = InteractionEvent {
1162 custom_id: Some("btn_role_123456".to_string()),
1163 ..Default::default()
1164 };
1165 let res_prefix_direct = MockModalPlugin::on_interaction(event_prefix_direct);
1166 assert!(matches!(res_prefix_direct, ResponseAction::Reply(s) if s == "role_assigned:btn_role_123456"));
1167
1168 let event_prefix_namespaced = InteractionEvent {
1170 custom_id: Some("tickets:btn_role_987654".to_string()),
1171 ..Default::default()
1172 };
1173 let res_prefix_namespaced = MockModalPlugin::on_interaction(event_prefix_namespaced);
1174 assert!(matches!(res_prefix_namespaced, ResponseAction::Reply(s) if s == "role_assigned:tickets:btn_role_987654"));
1175
1176 let res_event = MockModalPlugin::on_gateway_event(EventKind::MemberJoin, "user_123".to_string());
1178 assert!(matches!(res_event, ResponseAction::Reply(s) if s == "welcome:user_123"));
1179
1180 let res_unhandled = MockModalPlugin::on_gateway_event(EventKind::VoiceStateUpdate, "voice_456".to_string());
1182 assert!(matches!(res_unhandled, ResponseAction::None));
1183
1184 let edit_autocomplete_event = InteractionEvent {
1186 kind: InteractionKind::Autocomplete,
1187 command_name: "tag".to_string(),
1188 focused_option_name: Some("name".to_string()),
1189 options_json: serde_json::json!([
1190 {
1191 "name": "edit",
1192 "type": 1,
1193 "options": [
1194 { "name": "name", "type": 3, "value": "my", "focused": true }
1195 ]
1196 }
1197 ]).to_string(),
1198 ..Default::default()
1199 };
1200 let edit_res = MockModalPlugin::on_interaction(edit_autocomplete_event);
1201 match edit_res {
1202 ResponseAction::AutocompleteResult(choices) => {
1203 assert_eq!(choices.len(), 1);
1204 assert_eq!(choices[0].name, "my_tag");
1205 }
1206 _ => panic!("Expected AutocompleteResult for /tag edit"),
1207 }
1208
1209 let view_autocomplete_event = InteractionEvent {
1211 kind: InteractionKind::Autocomplete,
1212 command_name: "tag".to_string(),
1213 focused_option_name: Some("name".to_string()),
1214 options_json: serde_json::json!([
1215 {
1216 "name": "view",
1217 "type": 1,
1218 "options": [
1219 { "name": "name", "type": 3, "value": "pub", "focused": true }
1220 ]
1221 }
1222 ]).to_string(),
1223 ..Default::default()
1224 };
1225 let view_res = MockModalPlugin::on_interaction(view_autocomplete_event);
1226 match view_res {
1227 ResponseAction::AutocompleteResult(choices) => {
1228 assert_eq!(choices.len(), 1);
1229 assert_eq!(choices[0].name, "public_tag");
1230 }
1231 _ => panic!("Expected AutocompleteResult for /tag view"),
1232 }
1233
1234 let ping_autocomplete_event = InteractionEvent {
1236 kind: InteractionKind::Autocomplete,
1237 command_name: "ping".to_string(),
1238 focused_option_name: Some("query".to_string()),
1239 options_json: "[]".to_string(),
1240 ..Default::default()
1241 };
1242 let ping_res = MockModalPlugin::on_interaction(ping_autocomplete_event);
1243 match ping_res {
1244 ResponseAction::AutocompleteResult(choices) => {
1245 assert_eq!(choices.len(), 1);
1246 assert_eq!(choices[0].name, "ping_choice");
1247 }
1248 _ => panic!("Expected AutocompleteResult for /ping"),
1249 }
1250 }
1251
1252 #[test]
1253 fn test_brand_embed_zero_emojis_and_ephemeral_by_default() {
1254 let embed = BrandEmbed::success("Ticket Resolved", "Issue marked closed.")
1255 .field("ASSIGNEE", "<@123456>", true);
1256
1257 let action = embed.into_action();
1258 match action {
1259 ResponseAction::ReplyMessage(msg) => {
1260 assert!(msg.ephemeral, "BrandEmbed should default to ephemeral");
1261 assert_eq!(msg.embeds.len(), 1);
1262 let e = &msg.embeds[0];
1263 assert_eq!(e.title.as_deref(), Some("[SUCCESS] Ticket Resolved"));
1264 assert_eq!(e.description.as_deref(), Some("Issue marked closed."));
1265 assert_eq!(e.color, Some(BrandColor::SUCCESS));
1266 assert_eq!(e.fields.len(), 1);
1267 assert_eq!(e.fields[0].name, "ASSIGNEE");
1268 assert!(!e.title.as_ref().unwrap().contains('✅'));
1270 assert!(!e.title.as_ref().unwrap().contains("⚠️"));
1271 assert!(!e.title.as_ref().unwrap().contains('❌'));
1272 }
1273 _ => panic!("Expected ReplyMessage"),
1274 }
1275 }
1276
1277 #[test]
1278 fn test_audit_log_entry_parsing() {
1279 let sample_json = r#"{
1280 "audit_log_entries": [
1281 {
1282 "id": "999888",
1283 "user_id": "111222",
1284 "target_id": "333444",
1285 "action_type": 22,
1286 "reason": "Spamming invitations"
1287 }
1288 ]
1289 }"#;
1290
1291 let entries = AuditLogEntry::parse_entries(sample_json);
1292 assert_eq!(entries.len(), 1);
1293 assert_eq!(entries[0].id, "999888");
1294 assert_eq!(entries[0].user_id.as_deref(), Some("111222"));
1295 assert_eq!(entries[0].target_id.as_deref(), Some("333444"));
1296 assert_eq!(entries[0].action_type, 22);
1297 assert_eq!(entries[0].reason.as_deref(), Some("Spamming invitations"));
1298 }
1299
1300 #[test]
1301 fn test_discord_api_error_actionable_diagnostics() {
1302 let err_json = br#"{"code": 50013, "message": "Missing Permissions"}"#;
1303 let resp = HttpResponse {
1304 status: 403,
1305 headers: vec![],
1306 body: err_json.to_vec(),
1307 };
1308
1309 let err = DiscordApiError::from_response(&resp);
1310 assert_eq!(err.code, Some(50013));
1311 assert_eq!(err.status, 403);
1312 assert_eq!(err.message, "Missing Permissions");
1313 assert!(err.hint.contains("highest role"));
1314 }
1315}
1316
1317
1318
1319