-
Notifications
You must be signed in to change notification settings - Fork 563
/
message_builder.rs
318 lines (268 loc) · 9.59 KB
/
message_builder.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use std::default::Default;
use std::fmt::{self, Write};
use ::model::{ChannelId, Emoji, Mentionable, RoleId, UserId};
/// The Message Builder is an ergonomic utility to easily build a message,
/// by adding text and mentioning mentionable structs.
///
/// The finalized value can be accessed via [`build`] or the inner value.
///
/// # Examples
///
/// Build a message, mentioning a [`user`] and an [`emoji`], and retrieving the
/// value:
///
/// ```rust,ignore
/// use serenity::utils::MessageBuilder;
///
/// // assuming an `emoji` and `user` have already been bound
///
/// let content = MessageBuilder::new()
/// .push("You sent a message, ")
/// .mention(user)
/// .push("! ")
/// .mention(emoji)
/// .build();
/// ```
///
/// [`build`]: #method.build
/// [`emoji`]: #method.emoji
/// [`user`]: #method.user
pub struct MessageBuilder(pub String);
impl MessageBuilder {
/// Creates a new, empty-content builder.
pub fn new() -> MessageBuilder {
MessageBuilder::default()
}
/// Pulls the inner value out of the builder.
///
/// # Examples
///
/// This is equivalent to simply retrieving the tuple struct's first value:
///
/// ```rust
/// use serenity::utils::MessageBuilder;
///
/// let content = MessageBuilder::new().push("test").0;
///
/// assert_eq!(content, "test");
/// ```
pub fn build(self) -> String {
self.0
}
/// Mentions the [`GuildChannel`] in the built message.
///
/// This accepts anything that converts _into_ a [`ChannelId`]. Refer to
/// `ChannelId`'s documentation for more information.
///
/// Refer to `ChannelId`'s [Display implementation] for more information on
/// how this is formatted.
///
/// [`ChannelId`]: ../model/struct.ChannelId.html
/// [`GuildChannel`]: ../model/struct.GuildChannel.html
/// [Display implementation]: ../model/struct.ChannelId.html#method.fmt-1
pub fn channel<C: Into<ChannelId>>(mut self, channel: C) -> Self {
let _ = write!(self.0, "{}", channel.into().mention());
self
}
/// Displays the given emoji in the built message.
///
/// Refer to `Emoji`s [Display implementation] for more information on how
/// this is formatted.
///
/// [Display implementation]: ../model/struct.Emoji.html#method.fmt
pub fn emoji(mut self, emoji: Emoji) -> Self {
let _ = write!(self.0, "{}", emoji);
self
}
/// Mentions something that implements the [`Mentionable`] trait.
///
/// [`Mentionable`]: ../model/trait.Mentionable.html
pub fn mention<M: Mentionable>(mut self, item: M) -> Self {
let _ = write!(self.0, "{}", item.mention());
self
}
/// Pushes a string to the internal message content.
///
/// Note that this does not mutate either the given data or the internal
/// message content in anyway prior to appending the given content to the
/// internal message.
///
/// # Examples
///
/// ```rust
/// use serenity::utils::MessageBuilder;
///
/// let message = MessageBuilder::new().push("test");
///
/// assert_eq!(message.push("ing").0, "testing");
/// ```
pub fn push(mut self, content: &str) -> Self {
self.0.push_str(content);
self
}
/// Pushes a code-block to your message, with optional syntax highlighting.
pub fn push_codeblock(mut self, content: &str, language: Option<&str>) -> Self {
self.0.push_str("```");
if let Some(language) = language {
self.0.push_str(language);
}
self.0.push('\n');
self.0.push_str(content);
self.0.push_str("\n```");
self
}
/// Pushes an inline monospaced text to your message.
pub fn push_mono(mut self, content: &str) -> Self {
self.0.push('`');
self.0.push_str(content);
self.0.push('`');
self
}
/// Pushes an inline italicized text to your message.
pub fn push_italic(mut self, content: &str) -> Self {
self.0.push('_');
self.0.push_str(content);
self.0.push('_');
self
}
/// Pushes an inline bold text to your message.
pub fn push_bold(mut self, content: &str) -> Self {
self.0.push_str("**");
self.0.push_str(content);
self.0.push_str("**");
self
}
/// Pushes an underlined inline text to your message.
pub fn push_underline(mut self, content: &str) -> Self {
self.0.push_str("__");
self.0.push_str(content);
self.0.push_str("__");
self
}
/// Pushes a strikethrough inline text to your message.
pub fn push_strike(mut self, content: &str) -> Self {
self.0.push_str("~~");
self.0.push_str(content);
self.0.push_str("~~");
self
}
/// Pushes text to your message, but normalizing content - that means
/// ensuring that there's no unwanted formatting, mention spam etc.
pub fn push_safe(mut self, content: &str) -> Self {
let normalized = normalize(content)
.replace('*', "\\*")
.replace('`', "\\`")
.replace('_', "\\_");
self.0.push_str(&normalized);
self
}
/// Pushes a code-block to your message normalizing content.
pub fn push_codeblock_safe(mut self, content: &str, language: Option<&str>)
-> Self {
let content = &normalize(content)
.replace("```", "'''");
self.0.push_str("```");
if let Some(language) = language {
self.0.push_str(language);
}
self.0.push('\n');
self.0.push_str(content);
self.0.push_str("```");
self
}
/// Pushes an inline monospaced text to your message normalizing content.
pub fn push_mono_safe(mut self, content: &str) -> Self {
self.0.push('`');
self.0.push_str(&normalize(content).replace('`', "'"));
self.0.push('`');
self
}
/// Pushes an inline italicized text to your message normalizing content.
pub fn push_italic_safe(mut self, content: &str) -> Self {
self.0.push('_');
self.0.push_str(&normalize(content).replace('_', " "));
self.0.push('_');
self
}
/// Pushes an inline bold text to your message normalizing content.
pub fn push_bold_safe(mut self, content: &str) -> Self {
self.0.push_str("**");
self.0.push_str(&normalize(content).replace("**", " "));
self.0.push_str("**");
self
}
/// Pushes an underlined inline text to your message normalizing content.
pub fn push_underline_safe(mut self, content: &str) -> Self {
self.0.push_str("__");
self.0.push_str(&normalize(content).replace("__", " "));
self.0.push_str("__");
self
}
/// Pushes a strikethrough inline text to your message normalizing content.
pub fn push_strike_safe(mut self, content: &str) -> Self {
self.0.push_str("~~");
self.0.push_str(&normalize(content).replace("~~", " "));
self.0.push_str("~~");
self
}
/// Mentions the [`Role`] in the built message.
///
/// This accepts anything that converts _into_ a [`RoleId`]. Refer to
/// `RoleId`'s documentation for more information.
///
/// Refer to `RoleId`'s [Display implementation] for more information on how
/// this is formatted.
///
/// [`Role`]: ../model/struct.Role.html
/// [`RoleId`]: ../model/struct.RoleId.html
/// [Display implementation]: ../model/struct.RoleId.html#method.fmt-1
pub fn role<R: Into<RoleId>>(mut self, role: R) -> Self {
let _ = write!(self.0, "{}", role.into().mention());
self
}
/// Mentions the [`User`] in the built message.
///
/// This accepts anything that converts _into_ a [`UserId`]. Refer to
/// `UserId`'s documentation for more information.
///
/// Refer to `UserId`'s [Display implementation] for more information on how
/// this is formatted.
///
/// [`User`]: ../model/struct.User.html
/// [`UserId`]: ../model/struct.UserId.html
/// [Display implementation]: ../model/struct.UserId.html#method.fmt-1
pub fn user<U: Into<UserId>>(mut self, user: U) -> Self {
let _ = write!(self.0, "{}", user.into().mention());
self
}
}
impl fmt::Display for MessageBuilder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl Default for MessageBuilder {
fn default() -> MessageBuilder {
MessageBuilder(String::default())
}
}
fn normalize(text: &str) -> String {
// Remove invite links and popular scam websites, mostly to prevent the
// current user from triggering various ad detectors and prevent embeds.
text.replace("discord.gg", "discord\u{2024}gg")
.replace("discord.me", "discord\u{2024}me")
.replace("discordlist.net", "discordlist\u{2024}net")
.replace("discordservers.com", "discordservers\u{2024}com")
.replace("discordapp.com/invite", "discordapp\u{2024}com/invite")
// Remove right-to-left override and other similar annoying symbols
.replace('\u{202E}', " ") // RTL Override
.replace('\u{200F}', " ") // RTL Mark
.replace('\u{202B}', " ") // RTL Embedding
.replace('\u{200B}', " ") // Zero-width space
.replace('\u{200D}', " ") // Zero-width joiner
.replace('\u{200C}', " ") // Zero-width non-joiner
// Remove everyone and here mentions. Has to be put after ZWS replacement
// because it utilises it itself.
.replace("@everyone", "@\u{200B}everyone")
.replace("@here", "@\u{200B}here")
}