Skip to main content

babyrite/
reply.rs

1//! Assembly of the messages Babyrite posts back to the requester.
2//!
3//! Everything the bot says goes through [`build_messages`], so the reply
4//! policy — what is allowed to be mentioned, and what rides in which message —
5//! is decided in one place instead of at each call site.
6
7use crate::expand::ExpandedContent;
8use crate::utils::{defuse_code_fences, fence_info};
9use twilight_model::channel::message::{AllowedMentions, Embed};
10use twilight_model::id::{Id, marker::MessageMarker};
11
12/// A message to post, independent of the HTTP request that sends it.
13#[derive(Debug)]
14pub struct OutgoingMessage {
15    /// The message content.
16    pub content: Option<String>,
17    /// The embeds attached to the message.
18    pub embeds: Vec<Embed>,
19    /// The message this one replies to.
20    pub reply_to: Option<Id<MessageMarker>>,
21    /// Who the message may mention.
22    pub allowed_mentions: AllowedMentions,
23}
24
25/// Builds the messages answering the message `request_id`, in the order they
26/// are sent.
27///
28/// Every message replies to the request, so each expansion stays attached to the
29/// link it came from. Embeds ride in a single reply, while each code block gets a
30/// reply of its own: a block fills the message content, and a message carries
31/// only one.
32pub fn build_messages(
33    request_id: Id<MessageMarker>,
34    results: Vec<ExpandedContent>,
35) -> Vec<OutgoingMessage> {
36    let mut embeds = Vec::new();
37    let mut code_blocks = Vec::new();
38
39    for result in results {
40        match result {
41            ExpandedContent::Embed(embed) => embeds.push(*embed),
42            ExpandedContent::CodeBlock {
43                language,
44                code,
45                metadata,
46            } => {
47                let code = defuse_code_fences(&code);
48                let language = fence_info(&language);
49                // `allowed_mentions` is set explicitly, and empty: left unset,
50                // Discord parses every mention in the content under the bot's
51                // permissions. The content is fetched from a repository the
52                // requester chose, so that would let it borrow mention rights
53                // the requester may not hold. That also leaves `replied_user`
54                // off: only the preview pings the requester, so a message with
55                // several permalinks does not ping them once per code block.
56                code_blocks.push(OutgoingMessage {
57                    content: Some(format!("{metadata}\n```{language}\n{code}\n```")),
58                    embeds: Vec::new(),
59                    reply_to: Some(request_id),
60                    allowed_mentions: AllowedMentions::default(),
61                });
62            }
63        }
64    }
65
66    if embeds.is_empty() {
67        return code_blocks;
68    }
69
70    // Only the reply ping is allowed: the quoted message is someone else's
71    // content and must not gain mention rights by being echoed by the bot.
72    let preview = OutgoingMessage {
73        content: None,
74        embeds,
75        reply_to: Some(request_id),
76        allowed_mentions: AllowedMentions {
77            replied_user: true,
78            ..Default::default()
79        },
80    };
81
82    std::iter::once(preview).chain(code_blocks).collect()
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88    use twilight_util::builder::embed::EmbedBuilder;
89
90    const REQUEST: Id<MessageMarker> = Id::new(1);
91
92    fn embed() -> ExpandedContent {
93        ExpandedContent::Embed(Box::new(EmbedBuilder::new().description("quoted").build()))
94    }
95
96    fn code_block() -> ExpandedContent {
97        ExpandedContent::CodeBlock {
98            language: "rust".to_string(),
99            code: "fn main() {}".to_string(),
100            metadata: "src/main.rs L1".to_string(),
101        }
102    }
103
104    #[test]
105    fn embeds_share_one_message_and_every_code_block_gets_its_own() {
106        let messages = build_messages(REQUEST, vec![embed(), code_block(), embed(), code_block()]);
107
108        assert_eq!(messages.len(), 3);
109        assert_eq!(messages[0].embeds.len(), 2);
110    }
111
112    #[test]
113    fn embeds_are_sent_before_code_blocks() {
114        let messages = build_messages(REQUEST, vec![code_block(), embed()]);
115
116        assert_eq!(messages[0].embeds[0].description.as_deref(), Some("quoted"));
117        assert!(messages[1].content.is_some());
118    }
119
120    #[test]
121    fn nothing_is_sent_without_expanded_content() {
122        assert!(build_messages(REQUEST, Vec::new()).is_empty());
123    }
124
125    #[test]
126    fn code_block_is_fenced_with_its_language_below_its_metadata() {
127        let messages = build_messages(REQUEST, vec![code_block()]);
128
129        assert_eq!(
130            messages[0].content.as_deref(),
131            Some("src/main.rs L1\n```rust\nfn main() {}\n```")
132        );
133    }
134
135    fn code_block_in(language: &str) -> ExpandedContent {
136        ExpandedContent::CodeBlock {
137            language: language.to_string(),
138            code: "x".to_string(),
139            metadata: "m".to_string(),
140        }
141    }
142
143    #[test]
144    fn an_unknown_language_is_kept_as_the_info_string() {
145        for language in ["c~", "%E8%A8%AD"] {
146            let messages = build_messages(REQUEST, vec![code_block_in(language)]);
147
148            assert_eq!(
149                messages[0].content.as_deref(),
150                Some(format!("m\n```{language}\nx\n```").as_str())
151            );
152        }
153    }
154
155    #[test]
156    fn a_language_containing_a_backtick_cannot_close_the_fence() {
157        let messages = build_messages(REQUEST, vec![code_block_in("a```")]);
158
159        assert_eq!(messages[0].content.as_deref(), Some("m\n```\nx\n```"));
160    }
161
162    #[test]
163    fn the_preview_replies_to_the_request() {
164        let messages = build_messages(REQUEST, vec![embed()]);
165
166        assert_eq!(messages[0].reply_to, Some(REQUEST));
167    }
168
169    #[test]
170    fn only_the_reply_ping_is_allowed_in_the_preview() {
171        let messages = build_messages(REQUEST, vec![embed()]);
172
173        assert_eq!(
174            messages[0].allowed_mentions,
175            AllowedMentions {
176                replied_user: true,
177                ..Default::default()
178            }
179        );
180    }
181
182    #[test]
183    fn a_code_block_mentions_nobody() {
184        let messages = build_messages(REQUEST, vec![code_block()]);
185
186        assert_eq!(messages[0].allowed_mentions, AllowedMentions::default());
187    }
188
189    #[test]
190    fn every_message_replies_to_the_request() {
191        let messages = build_messages(REQUEST, vec![embed(), code_block(), code_block()]);
192
193        assert!(messages.iter().all(|m| m.reply_to == Some(REQUEST)));
194    }
195}