djs_builders/embed.rs
1//! [`EmbedBuilder`] and its pieces, [`EmbedAuthorBuilder`] and [`EmbedFooterBuilder`], plus
2//! the message-wide checks [`embed_length`] and [`validate_embeds`].
3
4use compact_str::CompactString;
5use djs_model::{
6 message::{Embed, EmbedAuthor, EmbedField, EmbedFooter, EmbedImage},
7 util::Timestamp,
8};
9
10use crate::{
11 ValidationError,
12 check::{self, WEB, WEB_OR_ATTACHMENT},
13};
14
15/// Discord's [embed limits](https://docs.discord.com/developers/resources/message#embed-object-embed-limits).
16mod limits {
17 pub(super) const TITLE: usize = 256;
18 pub(super) const DESCRIPTION: usize = 4096;
19 pub(super) const FIELDS: usize = 25;
20 pub(super) const FIELD_NAME: usize = 256;
21 pub(super) const FIELD_VALUE: usize = 1024;
22 pub(super) const FOOTER_TEXT: usize = 2048;
23 pub(super) const AUTHOR_NAME: usize = 256;
24 /// Across the texts of one embed — and of all embeds of a message.
25 pub(super) const TOTAL: usize = 6000;
26 /// Embeds in one message.
27 pub(super) const EMBEDS: usize = 10;
28 /// The largest RGB color.
29 pub(super) const COLOR: u32 = 0xFF_FFFF;
30}
31
32/// What an embed needs at least one of (D-191), for [`ValidationError::Empty`].
33const EMBED_CONTENT: &str =
34 "a title, a description, a field, an author, a footer, an image or a thumbnail";
35
36/// Builds an [embed](https://docs.discord.com/developers/resources/message#embed-object) — a
37/// rich content block for a message, an interaction reply or a webhook — and checks it
38/// against Discord's limits.
39///
40/// Every setter takes and returns the builder (D-178), stores the value as given and never
41/// fails; [`build`](Self::build) checks everything at the end (D-179) and returns the first
42/// problem as a [`ValidationError`] (D-182). [`build_unchecked`](Self::build_unchecked) skips
43/// the checks (D-180).
44///
45/// `build` checks what Discord checks, as measured on the live API (D-183, D-188, D-191):
46///
47/// | Part | Rule |
48/// |------|------|
49/// | [`title`](Self::title) | at most 256 characters |
50/// | [`description`](Self::description) | at most 4096 characters |
51/// | [`field`](Self::field)s | at most 25; name at most 256, value at most 1024 characters |
52/// | [`footer`](Self::footer) text | at most 2048 characters |
53/// | [`author`](Self::author) name | at most 256 characters |
54/// | all of the texts above | at most 6000 characters together |
55/// | [`color`](Self::color) | at most `0xFFFFFF` |
56/// | [`url`](Self::url), author URL | `http://` or `https://` |
57/// | [`image`](Self::image), [`thumbnail`](Self::thumbnail), icons | `http://`, `https://` or `attachment://` |
58/// | the whole embed | a non-blank title, description, footer or author name, a field, an image or a thumbnail |
59///
60/// Characters are Unicode code points after trimming leading and trailing whitespace, the way
61/// Discord counts them; schemes are compared without regard to case. Empty or blank texts
62/// are allowed — Discord accepts them, as long as the embed has some content.
63///
64/// The 6000-character total also applies to **all embeds of a message together** (at most
65/// 10 embeds); check a whole list with [`validate_embeds`].
66///
67/// discord.js counterpart: `EmbedBuilder`. Unlike discord.js, the setters do not throw, an
68/// emoji counts as one character (not two UTF-16 units), and empty field names and values
69/// are allowed only because Discord allows them.
70///
71/// # Examples
72///
73/// ```
74/// use djs_builders::{EmbedBuilder, EmbedFooterBuilder};
75///
76/// # fn main() -> Result<(), djs_builders::ValidationError> {
77/// let embed = EmbedBuilder::new()
78/// .title("Server status")
79/// .url("https://example.com/status")
80/// .description("Everything is running.")
81/// .color(0x57_F287)
82/// .author("Status bot")
83/// .field("Uptime", "14 days")
84/// .inline_field("Ping", "42 ms")
85/// .inline_field("Players", "17")
86/// .footer(EmbedFooterBuilder::new("Updated").icon_url("https://example.com/icon.png"))
87/// .thumbnail("attachment://logo.png")
88/// .build()?;
89///
90/// assert_eq!(embed.title.as_deref(), Some("Server status"));
91/// assert_eq!(embed.fields.len(), 3);
92/// assert!(embed.fields[1].inline);
93/// # Ok(())
94/// # }
95/// ```
96///
97/// A problem is reported by `build`, not by the setter:
98///
99/// ```
100/// use djs_builders::{EmbedBuilder, ValidationError};
101///
102/// let error = EmbedBuilder::new()
103/// .title("Results")
104/// .url("ftp://example.com/results")
105/// .build()
106/// .unwrap_err();
107/// assert_eq!(error.field(), "url");
108/// assert!(matches!(error, ValidationError::InvalidUrl { .. }));
109/// ```
110///
111/// Send it with a message:
112///
113/// ```
114/// use djs_builders::EmbedBuilder;
115/// use djs_model::rest::CreateMessage;
116///
117/// # fn main() -> Result<(), djs_builders::ValidationError> {
118/// let message = CreateMessage::default().embed(EmbedBuilder::new().description("Hello!").build()?);
119/// assert_eq!(
120/// serde_json::to_string(&message).unwrap(),
121/// r#"{"embeds":[{"description":"Hello!"}]}"#
122/// );
123/// # Ok(())
124/// # }
125/// ```
126#[derive(Clone, Debug, Default, PartialEq, Eq)]
127#[must_use = "a builder does nothing until `build` is called"]
128pub struct EmbedBuilder {
129 embed: Embed,
130}
131
132impl EmbedBuilder {
133 /// Creates a builder for an empty embed.
134 ///
135 /// An embed needs some content before [`build`](Self::build) accepts it: a title, a
136 /// description, a field, an author, a footer, an image or a thumbnail.
137 ///
138 /// discord.js counterpart: `new EmbedBuilder()`.
139 pub fn new() -> Self {
140 Self::default()
141 }
142
143 /// Sets the title (at most 256 characters), shown in bold at the top.
144 ///
145 /// discord.js counterpart: `EmbedBuilder#setTitle`.
146 pub fn title(mut self, title: impl Into<CompactString>) -> Self {
147 self.embed.title = Some(title.into());
148 self
149 }
150
151 /// Sets the URL the title links to (`http://` or `https://`).
152 ///
153 /// Embeds of one message that share a URL are shown as one by Discord, which is how
154 /// several images can appear in a single embed.
155 ///
156 /// discord.js counterpart: `EmbedBuilder#setURL`.
157 pub fn url(mut self, url: impl Into<CompactString>) -> Self {
158 self.embed.url = Some(url.into());
159 self
160 }
161
162 /// Sets the description (at most 4096 characters), the main text of the embed. It can
163 /// use markdown.
164 ///
165 /// discord.js counterpart: `EmbedBuilder#setDescription`.
166 pub fn description(mut self, description: impl Into<CompactString>) -> Self {
167 self.embed.description = Some(description.into());
168 self
169 }
170
171 /// Sets the color of the left border as an RGB integer (`0xRRGGBB`, at most `0xFFFFFF`).
172 ///
173 /// discord.js counterpart: `EmbedBuilder#setColor` with a number.
174 ///
175 /// # Examples
176 ///
177 /// ```
178 /// use djs_builders::EmbedBuilder;
179 ///
180 /// let embed = EmbedBuilder::new().title("x").color(0x58_65F2).build().unwrap();
181 /// assert_eq!(embed.color, Some(0x58_65F2));
182 /// ```
183 pub fn color(mut self, color: u32) -> Self {
184 self.embed.color = Some(color);
185 self
186 }
187
188 /// Sets the color of the left border from its red, green and blue parts.
189 ///
190 /// discord.js counterpart: `EmbedBuilder#setColor` with an `[r, g, b]` tuple.
191 ///
192 /// # Examples
193 ///
194 /// ```
195 /// use djs_builders::EmbedBuilder;
196 ///
197 /// let embed = EmbedBuilder::new().title("x").color_rgb(88, 101, 242).build().unwrap();
198 /// assert_eq!(embed.color, Some(0x58_65F2));
199 /// ```
200 pub fn color_rgb(self, red: u8, green: u8, blue: u8) -> Self {
201 self.color(u32::from_be_bytes([0, red, green, blue]))
202 }
203
204 /// Sets the author shown above the title: a name (at most 256 characters), or an
205 /// [`EmbedAuthorBuilder`] with a link and an icon too.
206 ///
207 /// discord.js counterpart: `EmbedBuilder#setAuthor`.
208 ///
209 /// # Examples
210 ///
211 /// ```
212 /// use djs_builders::{EmbedAuthorBuilder, EmbedBuilder};
213 ///
214 /// let plain = EmbedBuilder::new().author("Status bot").build().unwrap();
215 /// assert_eq!(plain.author.unwrap().name, "Status bot");
216 ///
217 /// let linked = EmbedBuilder::new()
218 /// .author(
219 /// EmbedAuthorBuilder::new("Status bot")
220 /// .url("https://example.com")
221 /// .icon_url("https://example.com/avatar.png"),
222 /// )
223 /// .build()
224 /// .unwrap();
225 /// assert_eq!(linked.author.unwrap().url.as_deref(), Some("https://example.com"));
226 /// ```
227 pub fn author(mut self, author: impl Into<EmbedAuthorBuilder>) -> Self {
228 self.embed.author = Some(Box::new(author.into().author));
229 self
230 }
231
232 /// Sets the footer: a text (at most 2048 characters), or an [`EmbedFooterBuilder`] with
233 /// an icon too. A [`timestamp`](Self::timestamp) is shown next to it.
234 ///
235 /// discord.js counterpart: `EmbedBuilder#setFooter`.
236 ///
237 /// # Examples
238 ///
239 /// ```
240 /// use djs_builders::{EmbedBuilder, EmbedFooterBuilder};
241 ///
242 /// let embed = EmbedBuilder::new()
243 /// .footer(EmbedFooterBuilder::new("Page 1 of 3").icon_url("attachment://icon.png"))
244 /// .build()
245 /// .unwrap();
246 /// assert_eq!(embed.footer.unwrap().text, "Page 1 of 3");
247 /// ```
248 pub fn footer(mut self, footer: impl Into<EmbedFooterBuilder>) -> Self {
249 self.embed.footer = Some(Box::new(footer.into().footer));
250 self
251 }
252
253 /// Adds a field on its own line: a `name` (at most 256 characters) above a `value` (at
254 /// most 1024). An embed has at most 25 fields.
255 ///
256 /// discord.js counterpart: `EmbedBuilder#addFields` with `{ name, value }`.
257 pub fn field(
258 mut self,
259 name: impl Into<CompactString>,
260 value: impl Into<CompactString>,
261 ) -> Self {
262 self.embed.fields.push(EmbedField::new(name, value, false));
263 self
264 }
265
266 /// Adds an inline field, shown next to the inline fields around it (up to three per
267 /// row on desktop).
268 ///
269 /// discord.js counterpart: `EmbedBuilder#addFields` with `{ name, value, inline: true }`.
270 pub fn inline_field(
271 mut self,
272 name: impl Into<CompactString>,
273 value: impl Into<CompactString>,
274 ) -> Self {
275 self.embed.fields.push(EmbedField::new(name, value, true));
276 self
277 }
278
279 /// Adds several fields at once, after those already added.
280 ///
281 /// discord.js counterpart: `EmbedBuilder#addFields`.
282 ///
283 /// # Examples
284 ///
285 /// ```
286 /// use djs_builders::EmbedBuilder;
287 /// use djs_model::message::EmbedField;
288 ///
289 /// let scores = [("Ada", 31), ("Grace", 27)];
290 /// let embed = EmbedBuilder::new()
291 /// .title("Scores")
292 /// .fields(scores.iter().map(|(name, score)| EmbedField::new(*name, score.to_string(), true)))
293 /// .build()
294 /// .unwrap();
295 /// assert_eq!(embed.fields[1].value, "27");
296 /// ```
297 pub fn fields(mut self, fields: impl IntoIterator<Item = EmbedField>) -> Self {
298 self.embed.fields.extend(fields);
299 self
300 }
301
302 /// Sets the large image below the fields: a link (`http://`, `https://`) or a file
303 /// uploaded with the message (`attachment://name.png`).
304 ///
305 /// discord.js counterpart: `EmbedBuilder#setImage`.
306 pub fn image(mut self, url: impl Into<CompactString>) -> Self {
307 self.embed.image = Some(Box::new(EmbedImage::new(url)));
308 self
309 }
310
311 /// Sets the small image in the top-right corner, with the same URLs as
312 /// [`image`](Self::image).
313 ///
314 /// discord.js counterpart: `EmbedBuilder#setThumbnail`.
315 pub fn thumbnail(mut self, url: impl Into<CompactString>) -> Self {
316 self.embed.thumbnail = Some(Box::new(EmbedImage::new(url)));
317 self
318 }
319
320 /// Sets the time shown in the footer, in each viewer's time zone.
321 ///
322 /// A timestamp alone is not content: an embed with only a timestamp is rejected.
323 ///
324 /// discord.js counterpart: `EmbedBuilder#setTimestamp` with a date.
325 pub fn timestamp(mut self, timestamp: Timestamp) -> Self {
326 self.embed.timestamp = Some(timestamp);
327 self
328 }
329
330 /// Sets the time shown in the footer to now (the system clock).
331 ///
332 /// discord.js counterpart: `EmbedBuilder#setTimestamp()` without an argument.
333 ///
334 /// # Panics
335 ///
336 /// If the system clock is set before 1970 (see [`Timestamp::now`]).
337 pub fn timestamp_now(self) -> Self {
338 self.timestamp(Timestamp::now())
339 }
340
341 /// Checks the embed against Discord's limits (see the [type docs](Self)) and returns it.
342 ///
343 /// discord.js counterpart: `EmbedBuilder#toJSON` (which does not validate; the setters
344 /// do).
345 ///
346 /// # Errors
347 ///
348 /// The first [`ValidationError`] found, checking the parts in this order: title,
349 /// description, URL, color, fields, footer, image, thumbnail, author, the 6000-character
350 /// total ([`TooLong`](ValidationError::TooLong) with the field `embed`), and finally
351 /// whether the embed has any content ([`Empty`](ValidationError::Empty)).
352 pub fn build(self) -> Result<Embed, ValidationError> {
353 validate(&self.embed)?;
354 Ok(self.embed)
355 }
356
357 /// Returns the embed without any check (D-180) — for example when Discord has raised a
358 /// limit before this crate has. Discord rejects an invalid embed with
359 /// `50035 Invalid Form Body`.
360 ///
361 /// discord.js counterpart: `EmbedBuilder#toJSON` with `disableValidators()`.
362 #[must_use]
363 pub fn build_unchecked(self) -> Embed {
364 self.embed
365 }
366}
367
368/// Starts from an existing embed — for example one received in a message, to send it again
369/// with changes. Every part is kept; a setter replaces its part (and
370/// [`field`](EmbedBuilder::field) adds after the existing fields).
371///
372/// discord.js counterpart: `EmbedBuilder.from(embed)` / `new EmbedBuilder(data)`.
373///
374/// # Examples
375///
376/// ```
377/// use djs_builders::EmbedBuilder;
378/// use djs_model::message::Embed;
379///
380/// let received: Embed = serde_json::from_str(r#"{"title":"Poll","description":"Open"}"#).unwrap();
381/// let closed = EmbedBuilder::from(received).description("Closed").build().unwrap();
382/// assert_eq!(closed.title.as_deref(), Some("Poll"));
383/// assert_eq!(closed.description.as_deref(), Some("Closed"));
384/// ```
385impl From<Embed> for EmbedBuilder {
386 fn from(embed: Embed) -> Self {
387 Self { embed }
388 }
389}
390
391/// Checks everything [`EmbedBuilder::build`] documents, in that order.
392fn validate(embed: &Embed) -> Result<(), ValidationError> {
393 let mut total = 0;
394 if let Some(title) = &embed.title {
395 total += check::text(|| "title".into(), title, limits::TITLE)?;
396 }
397 if let Some(description) = &embed.description {
398 total += check::text(|| "description".into(), description, limits::DESCRIPTION)?;
399 }
400 if let Some(url) = &embed.url {
401 check::url(|| "url".into(), url, WEB)?;
402 }
403 if let Some(color) = embed.color
404 && color > limits::COLOR
405 {
406 return Err(ValidationError::OutOfRange {
407 field: "color".into(),
408 min: 0,
409 max: limits::COLOR.into(),
410 actual: color.into(),
411 });
412 }
413 check::count(|| "fields".into(), embed.fields.len(), limits::FIELDS)?;
414 for (index, field) in embed.fields.iter().enumerate() {
415 total += check::text(
416 || format!("fields[{index}].name").into(),
417 &field.name,
418 limits::FIELD_NAME,
419 )?;
420 total += check::text(
421 || format!("fields[{index}].value").into(),
422 &field.value,
423 limits::FIELD_VALUE,
424 )?;
425 }
426 if let Some(footer) = &embed.footer {
427 total += validate_footer(footer, &IN_EMBED_FOOTER)?;
428 }
429 if let Some(image) = &embed.image {
430 check::url(|| "image.url".into(), &image.url, WEB_OR_ATTACHMENT)?;
431 }
432 if let Some(thumbnail) = &embed.thumbnail {
433 check::url(|| "thumbnail.url".into(), &thumbnail.url, WEB_OR_ATTACHMENT)?;
434 }
435 if let Some(author) = &embed.author {
436 total += validate_author(author, &IN_EMBED_AUTHOR)?;
437 }
438 if total > limits::TOTAL {
439 return Err(ValidationError::TooLong {
440 field: "embed".into(),
441 max: limits::TOTAL,
442 actual: total,
443 });
444 }
445 if !has_content(embed) {
446 return Err(ValidationError::Empty {
447 field: "embed".into(),
448 needs: EMBED_CONTENT,
449 });
450 }
451 Ok(())
452}
453
454/// Whether Discord counts `embed` as having content (D-191): blank texts, the URL, the
455/// timestamp and the color do not count; any field, even one with blank texts, does.
456fn has_content(embed: &Embed) -> bool {
457 let text = |text: Option<&str>| text.is_some_and(|text| !check::is_blank(text));
458 text(embed.title.as_deref())
459 || text(embed.description.as_deref())
460 || !embed.fields.is_empty()
461 || text(embed.footer.as_ref().map(|footer| footer.text.as_str()))
462 || text(embed.author.as_ref().map(|author| author.name.as_str()))
463 || embed.image.is_some()
464 || embed.thumbnail.is_some()
465}
466
467/// Returns the number of characters of `embed` that count toward Discord's 6000-character
468/// limit: its title, description, field names and values, footer text and author name, each
469/// measured in Unicode code points after trimming (D-183).
470///
471/// discord.js counterpart: `embedLength` (which counts UTF-16 code units, untrimmed).
472///
473/// # Examples
474///
475/// ```
476/// use djs_builders::{EmbedBuilder, embed_length};
477///
478/// let embed = EmbedBuilder::new()
479/// .title(" Hi ") // 2: surrounding whitespace is not counted
480/// .description("🔥🔥🔥") // 3: one per code point
481/// .field("a", "bc") // 3
482/// .build_unchecked();
483/// assert_eq!(embed_length(&embed), 8);
484/// ```
485#[must_use]
486pub fn embed_length(embed: &Embed) -> usize {
487 let mut total = 0;
488 for text in [&embed.title, &embed.description].into_iter().flatten() {
489 total += check::length(text);
490 }
491 for field in &embed.fields {
492 total += check::length(&field.name) + check::length(&field.value);
493 }
494 if let Some(footer) = &embed.footer {
495 total += check::length(&footer.text);
496 }
497 if let Some(author) = &embed.author {
498 total += check::length(&author.name);
499 }
500 total
501}
502
503/// Checks the limits that apply to all embeds of one message together: at most 10 embeds
504/// and at most 6000 characters across them (see [`embed_length`]).
505///
506/// The embeds themselves are not checked again; build each with [`EmbedBuilder::build`].
507///
508/// discord.js counterpart: none (`@discordjs/builders` checks each embed alone).
509///
510/// # Errors
511///
512/// [`ValidationError::TooMany`] for more than 10 embeds, then
513/// [`ValidationError::TooLong`] for more than 6000 characters, both with the field `embeds`.
514///
515/// # Examples
516///
517/// ```
518/// use djs_builders::{EmbedBuilder, ValidationError, validate_embeds};
519///
520/// let page = EmbedBuilder::new().description("x".repeat(4000)).build().unwrap();
521/// assert!(validate_embeds(std::slice::from_ref(&page)).is_ok());
522/// assert_eq!(
523/// validate_embeds(&[page.clone(), page]),
524/// Err(ValidationError::TooLong { field: "embeds".into(), max: 6000, actual: 8000 })
525/// );
526/// ```
527pub fn validate_embeds(embeds: &[Embed]) -> Result<(), ValidationError> {
528 check::count(|| "embeds".into(), embeds.len(), limits::EMBEDS)?;
529 let total = embeds.iter().map(embed_length).sum();
530 if total > limits::TOTAL {
531 return Err(ValidationError::TooLong {
532 field: "embeds".into(),
533 max: limits::TOTAL,
534 actual: total,
535 });
536 }
537 Ok(())
538}
539
540/// The paths of an author's parts in a [`ValidationError`].
541struct AuthorPaths {
542 name: &'static str,
543 url: &'static str,
544 icon_url: &'static str,
545}
546
547const IN_EMBED_AUTHOR: AuthorPaths = AuthorPaths {
548 name: "author.name",
549 url: "author.url",
550 icon_url: "author.icon_url",
551};
552
553const ALONE_AUTHOR: AuthorPaths = AuthorPaths {
554 name: "name",
555 url: "url",
556 icon_url: "icon_url",
557};
558
559/// Checks an author and returns the length of its name.
560fn validate_author(author: &EmbedAuthor, paths: &AuthorPaths) -> Result<usize, ValidationError> {
561 let length = check::text(|| paths.name.into(), &author.name, limits::AUTHOR_NAME)?;
562 if let Some(url) = &author.url {
563 check::url(|| paths.url.into(), url, WEB)?;
564 }
565 if let Some(icon_url) = &author.icon_url {
566 check::url(|| paths.icon_url.into(), icon_url, WEB_OR_ATTACHMENT)?;
567 }
568 Ok(length)
569}
570
571/// The paths of a footer's parts in a [`ValidationError`].
572struct FooterPaths {
573 text: &'static str,
574 icon_url: &'static str,
575}
576
577const IN_EMBED_FOOTER: FooterPaths = FooterPaths {
578 text: "footer.text",
579 icon_url: "footer.icon_url",
580};
581
582const ALONE_FOOTER: FooterPaths = FooterPaths {
583 text: "text",
584 icon_url: "icon_url",
585};
586
587/// Checks a footer and returns the length of its text.
588fn validate_footer(footer: &EmbedFooter, paths: &FooterPaths) -> Result<usize, ValidationError> {
589 let length = check::text(|| paths.text.into(), &footer.text, limits::FOOTER_TEXT)?;
590 if let Some(icon_url) = &footer.icon_url {
591 check::url(|| paths.icon_url.into(), icon_url, WEB_OR_ATTACHMENT)?;
592 }
593 Ok(length)
594}
595
596/// Builds the [author](https://docs.discord.com/developers/resources/message#embed-object-embed-author-structure)
597/// of an embed — a name with an optional link and icon — for [`EmbedBuilder::author`].
598///
599/// A plain name converts into it, so `.author("Bot")` is enough when there is no link or
600/// icon. [`EmbedBuilder::build`] checks it as part of the embed; [`build`](Self::build) checks
601/// it on its own.
602///
603/// discord.js counterpart: the `EmbedAuthorOptions` passed to `EmbedBuilder#setAuthor`.
604///
605/// # Examples
606///
607/// ```
608/// use djs_builders::{EmbedAuthorBuilder, EmbedBuilder};
609///
610/// let embed = EmbedBuilder::new()
611/// .author(EmbedAuthorBuilder::new("Ada").icon_url("https://example.com/ada.png"))
612/// .build()
613/// .unwrap();
614/// assert_eq!(embed.author.unwrap().icon_url.as_deref(), Some("https://example.com/ada.png"));
615/// ```
616#[derive(Clone, Debug, PartialEq, Eq, Hash)]
617#[must_use = "a builder does nothing until it is passed to `EmbedBuilder::author` or built"]
618pub struct EmbedAuthorBuilder {
619 author: EmbedAuthor,
620}
621
622impl EmbedAuthorBuilder {
623 /// Creates an author named `name` (at most 256 characters).
624 ///
625 /// discord.js counterpart: the `name` of `EmbedAuthorOptions`, given to `EmbedBuilder#setAuthor`.
626 pub fn new(name: impl Into<CompactString>) -> Self {
627 Self {
628 author: EmbedAuthor::new(name),
629 }
630 }
631
632 /// Sets the URL the name links to (`http://` or `https://`; not `attachment://`).
633 ///
634 /// discord.js counterpart: the `url` of `EmbedAuthorOptions`.
635 pub fn url(mut self, url: impl Into<CompactString>) -> Self {
636 self.author.url = Some(url.into());
637 self
638 }
639
640 /// Sets the icon shown before the name: a link (`http://`, `https://`) or an uploaded
641 /// file (`attachment://name.png`).
642 ///
643 /// discord.js counterpart: the `iconURL` of `EmbedAuthorOptions`.
644 pub fn icon_url(mut self, url: impl Into<CompactString>) -> Self {
645 self.author.icon_url = Some(url.into());
646 self
647 }
648
649 /// Checks the author on its own and returns it; the paths in a [`ValidationError`] are
650 /// `name`, `url` and `icon_url`.
651 ///
652 /// discord.js counterpart: `EmbedAuthorOptions`, checked by `EmbedBuilder#setAuthor`.
653 ///
654 /// # Errors
655 ///
656 /// [`ValidationError::TooLong`] for a name above 256 characters,
657 /// [`ValidationError::InvalidUrl`] for a URL with a scheme Discord does not allow.
658 pub fn build(self) -> Result<EmbedAuthor, ValidationError> {
659 validate_author(&self.author, &ALONE_AUTHOR)?;
660 Ok(self.author)
661 }
662
663 /// Returns the author without any check (D-180).
664 ///
665 /// discord.js counterpart: `EmbedAuthorOptions` with validation off (`disableValidators`).
666 #[must_use]
667 pub fn build_unchecked(self) -> EmbedAuthor {
668 self.author
669 }
670}
671
672/// Builds the [footer](https://docs.discord.com/developers/resources/message#embed-object-embed-footer-structure)
673/// of an embed — a text with an optional icon — for [`EmbedBuilder::footer`].
674///
675/// A plain text converts into it, so `.footer("Page 1")` is enough when there is no icon.
676/// [`EmbedBuilder::build`] checks it as part of the embed; [`build`](Self::build) checks it on
677/// its own.
678///
679/// discord.js counterpart: the `EmbedFooterOptions` passed to `EmbedBuilder#setFooter`.
680///
681/// # Examples
682///
683/// ```
684/// use djs_builders::{EmbedBuilder, EmbedFooterBuilder};
685///
686/// let embed = EmbedBuilder::new()
687/// .footer(EmbedFooterBuilder::new("Powered by djs-rs").icon_url("https://example.com/i.png"))
688/// .build()
689/// .unwrap();
690/// assert_eq!(embed.footer.unwrap().icon_url.as_deref(), Some("https://example.com/i.png"));
691/// ```
692#[derive(Clone, Debug, PartialEq, Eq, Hash)]
693#[must_use = "a builder does nothing until it is passed to `EmbedBuilder::footer` or built"]
694pub struct EmbedFooterBuilder {
695 footer: EmbedFooter,
696}
697
698impl EmbedFooterBuilder {
699 /// Creates a footer with `text` (at most 2048 characters).
700 ///
701 /// discord.js counterpart: the `text` of `EmbedFooterOptions`, given to `EmbedBuilder#setFooter`.
702 pub fn new(text: impl Into<CompactString>) -> Self {
703 Self {
704 footer: EmbedFooter::new(text),
705 }
706 }
707
708 /// Sets the icon shown before the text: a link (`http://`, `https://`) or an uploaded
709 /// file (`attachment://name.png`).
710 ///
711 /// discord.js counterpart: the `iconURL` of `EmbedFooterOptions`.
712 pub fn icon_url(mut self, url: impl Into<CompactString>) -> Self {
713 self.footer.icon_url = Some(url.into());
714 self
715 }
716
717 /// Checks the footer on its own and returns it; the paths in a [`ValidationError`] are
718 /// `text` and `icon_url`.
719 ///
720 /// discord.js counterpart: `EmbedFooterOptions`, checked by `EmbedBuilder#setFooter`.
721 ///
722 /// # Errors
723 ///
724 /// [`ValidationError::TooLong`] for a text above 2048 characters,
725 /// [`ValidationError::InvalidUrl`] for an icon with a scheme Discord does not allow.
726 pub fn build(self) -> Result<EmbedFooter, ValidationError> {
727 validate_footer(&self.footer, &ALONE_FOOTER)?;
728 Ok(self.footer)
729 }
730
731 /// Returns the footer without any check (D-180).
732 ///
733 /// discord.js counterpart: `EmbedFooterOptions` with validation off (`disableValidators`).
734 #[must_use]
735 pub fn build_unchecked(self) -> EmbedFooter {
736 self.footer
737 }
738}
739
740/// Implements the conversions of a plain text (and of the finished model type) into a piece
741/// builder.
742macro_rules! from_text {
743 ($builder:ident, $model:ident, $part:ident) => {
744 impl From<&str> for $builder {
745 fn from(text: &str) -> Self {
746 Self::new(text)
747 }
748 }
749
750 impl From<&String> for $builder {
751 fn from(text: &String) -> Self {
752 Self::new(text)
753 }
754 }
755
756 impl From<String> for $builder {
757 fn from(text: String) -> Self {
758 Self::new(text)
759 }
760 }
761
762 impl From<CompactString> for $builder {
763 fn from(text: CompactString) -> Self {
764 Self::new(text)
765 }
766 }
767
768 impl From<$model> for $builder {
769 fn from($part: $model) -> Self {
770 Self { $part }
771 }
772 }
773 };
774}
775
776from_text!(EmbedAuthorBuilder, EmbedAuthor, author);
777from_text!(EmbedFooterBuilder, EmbedFooter, footer);