Skip to main content

EmbedBuilder

Struct EmbedBuilder 

Source
pub struct EmbedBuilder { /* private fields */ }
Expand description

Builds an embed — a rich content block for a message, an interaction reply or a webhook — and checks it against Discord’s limits.

Every setter takes and returns the builder (D-178), stores the value as given and never fails; build checks everything at the end (D-179) and returns the first problem as a ValidationError (D-182). build_unchecked skips the checks (D-180).

build checks what Discord checks, as measured on the live API (D-183, D-188, D-191):

PartRule
titleat most 256 characters
descriptionat most 4096 characters
fieldsat most 25; name at most 256, value at most 1024 characters
footer textat most 2048 characters
author nameat most 256 characters
all of the texts aboveat most 6000 characters together
colorat most 0xFFFFFF
url, author URLhttp:// or https://
image, thumbnail, iconshttp://, https:// or attachment://
the whole embeda non-blank title, description, footer or author name, a field, an image or a thumbnail

Characters are Unicode code points after trimming leading and trailing whitespace, the way Discord counts them; schemes are compared without regard to case. Empty or blank texts are allowed — Discord accepts them, as long as the embed has some content.

The 6000-character total also applies to all embeds of a message together (at most 10 embeds); check a whole list with validate_embeds.

discord.js counterpart: EmbedBuilder. Unlike discord.js, the setters do not throw, an emoji counts as one character (not two UTF-16 units), and empty field names and values are allowed only because Discord allows them.

§Examples

use djs_builders::{EmbedBuilder, EmbedFooterBuilder};

let embed = EmbedBuilder::new()
    .title("Server status")
    .url("https://example.com/status")
    .description("Everything is running.")
    .color(0x57_F287)
    .author("Status bot")
    .field("Uptime", "14 days")
    .inline_field("Ping", "42 ms")
    .inline_field("Players", "17")
    .footer(EmbedFooterBuilder::new("Updated").icon_url("https://example.com/icon.png"))
    .thumbnail("attachment://logo.png")
    .build()?;

assert_eq!(embed.title.as_deref(), Some("Server status"));
assert_eq!(embed.fields.len(), 3);
assert!(embed.fields[1].inline);

A problem is reported by build, not by the setter:

use djs_builders::{EmbedBuilder, ValidationError};

let error = EmbedBuilder::new()
    .title("Results")
    .url("ftp://example.com/results")
    .build()
    .unwrap_err();
assert_eq!(error.field(), "url");
assert!(matches!(error, ValidationError::InvalidUrl { .. }));

Send it with a message:

use djs_builders::EmbedBuilder;
use djs_model::rest::CreateMessage;

let message = CreateMessage::default().embed(EmbedBuilder::new().description("Hello!").build()?);
assert_eq!(
    serde_json::to_string(&message).unwrap(),
    r#"{"embeds":[{"description":"Hello!"}]}"#
);

Implementations§

Source§

impl EmbedBuilder

Source

pub fn new() -> Self

Creates a builder for an empty embed.

An embed needs some content before build accepts it: a title, a description, a field, an author, a footer, an image or a thumbnail.

discord.js counterpart: new EmbedBuilder().

Source

pub fn title(self, title: impl Into<CompactString>) -> Self

Sets the title (at most 256 characters), shown in bold at the top.

discord.js counterpart: EmbedBuilder#setTitle.

Source

pub fn url(self, url: impl Into<CompactString>) -> Self

Sets the URL the title links to (http:// or https://).

Embeds of one message that share a URL are shown as one by Discord, which is how several images can appear in a single embed.

discord.js counterpart: EmbedBuilder#setURL.

Source

pub fn description(self, description: impl Into<CompactString>) -> Self

Sets the description (at most 4096 characters), the main text of the embed. It can use markdown.

discord.js counterpart: EmbedBuilder#setDescription.

Source

pub fn color(self, color: u32) -> Self

Sets the color of the left border as an RGB integer (0xRRGGBB, at most 0xFFFFFF).

discord.js counterpart: EmbedBuilder#setColor with a number.

§Examples
use djs_builders::EmbedBuilder;

let embed = EmbedBuilder::new().title("x").color(0x58_65F2).build().unwrap();
assert_eq!(embed.color, Some(0x58_65F2));
Source

pub fn color_rgb(self, red: u8, green: u8, blue: u8) -> Self

Sets the color of the left border from its red, green and blue parts.

discord.js counterpart: EmbedBuilder#setColor with an [r, g, b] tuple.

§Examples
use djs_builders::EmbedBuilder;

let embed = EmbedBuilder::new().title("x").color_rgb(88, 101, 242).build().unwrap();
assert_eq!(embed.color, Some(0x58_65F2));
Source

pub fn author(self, author: impl Into<EmbedAuthorBuilder>) -> Self

Sets the author shown above the title: a name (at most 256 characters), or an EmbedAuthorBuilder with a link and an icon too.

discord.js counterpart: EmbedBuilder#setAuthor.

§Examples
use djs_builders::{EmbedAuthorBuilder, EmbedBuilder};

let plain = EmbedBuilder::new().author("Status bot").build().unwrap();
assert_eq!(plain.author.unwrap().name, "Status bot");

let linked = EmbedBuilder::new()
    .author(
        EmbedAuthorBuilder::new("Status bot")
            .url("https://example.com")
            .icon_url("https://example.com/avatar.png"),
    )
    .build()
    .unwrap();
assert_eq!(linked.author.unwrap().url.as_deref(), Some("https://example.com"));
Source

pub fn footer(self, footer: impl Into<EmbedFooterBuilder>) -> Self

Sets the footer: a text (at most 2048 characters), or an EmbedFooterBuilder with an icon too. A timestamp is shown next to it.

discord.js counterpart: EmbedBuilder#setFooter.

§Examples
use djs_builders::{EmbedBuilder, EmbedFooterBuilder};

let embed = EmbedBuilder::new()
    .footer(EmbedFooterBuilder::new("Page 1 of 3").icon_url("attachment://icon.png"))
    .build()
    .unwrap();
assert_eq!(embed.footer.unwrap().text, "Page 1 of 3");
Source

pub fn field( self, name: impl Into<CompactString>, value: impl Into<CompactString>, ) -> Self

Adds a field on its own line: a name (at most 256 characters) above a value (at most 1024). An embed has at most 25 fields.

discord.js counterpart: EmbedBuilder#addFields with { name, value }.

Source

pub fn inline_field( self, name: impl Into<CompactString>, value: impl Into<CompactString>, ) -> Self

Adds an inline field, shown next to the inline fields around it (up to three per row on desktop).

discord.js counterpart: EmbedBuilder#addFields with { name, value, inline: true }.

Source

pub fn fields(self, fields: impl IntoIterator<Item = EmbedField>) -> Self

Adds several fields at once, after those already added.

discord.js counterpart: EmbedBuilder#addFields.

§Examples
use djs_builders::EmbedBuilder;
use djs_model::message::EmbedField;

let scores = [("Ada", 31), ("Grace", 27)];
let embed = EmbedBuilder::new()
    .title("Scores")
    .fields(scores.iter().map(|(name, score)| EmbedField::new(*name, score.to_string(), true)))
    .build()
    .unwrap();
assert_eq!(embed.fields[1].value, "27");
Source

pub fn image(self, url: impl Into<CompactString>) -> Self

Sets the large image below the fields: a link (http://, https://) or a file uploaded with the message (attachment://name.png).

discord.js counterpart: EmbedBuilder#setImage.

Source

pub fn thumbnail(self, url: impl Into<CompactString>) -> Self

Sets the small image in the top-right corner, with the same URLs as image.

discord.js counterpart: EmbedBuilder#setThumbnail.

Source

pub fn timestamp(self, timestamp: Timestamp) -> Self

Sets the time shown in the footer, in each viewer’s time zone.

A timestamp alone is not content: an embed with only a timestamp is rejected.

discord.js counterpart: EmbedBuilder#setTimestamp with a date.

Source

pub fn timestamp_now(self) -> Self

Sets the time shown in the footer to now (the system clock).

discord.js counterpart: EmbedBuilder#setTimestamp() without an argument.

§Panics

If the system clock is set before 1970 (see [Timestamp::now]).

Source

pub fn build(self) -> Result<Embed, ValidationError>

Checks the embed against Discord’s limits (see the type docs) and returns it.

discord.js counterpart: EmbedBuilder#toJSON (which does not validate; the setters do).

§Errors

The first ValidationError found, checking the parts in this order: title, description, URL, color, fields, footer, image, thumbnail, author, the 6000-character total (TooLong with the field embed), and finally whether the embed has any content (Empty).

Source

pub fn build_unchecked(self) -> Embed

Returns the embed without any check (D-180) — for example when Discord has raised a limit before this crate has. Discord rejects an invalid embed with 50035 Invalid Form Body.

discord.js counterpart: EmbedBuilder#toJSON with disableValidators().

Trait Implementations§

Source§

impl Clone for EmbedBuilder

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for EmbedBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for EmbedBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for EmbedBuilder

Source§

impl From<Embed> for EmbedBuilder

Starts from an existing embed — for example one received in a message, to send it again with changes. Every part is kept; a setter replaces its part (and field adds after the existing fields).

discord.js counterpart: EmbedBuilder.from(embed) / new EmbedBuilder(data).

§Examples

use djs_builders::EmbedBuilder;
use djs_model::message::Embed;

let received: Embed = serde_json::from_str(r#"{"title":"Poll","description":"Open"}"#).unwrap();
let closed = EmbedBuilder::from(received).description("Closed").build().unwrap();
assert_eq!(closed.title.as_deref(), Some("Poll"));
assert_eq!(closed.description.as_deref(), Some("Closed"));
Source§

fn from(embed: Embed) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for EmbedBuilder

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for EmbedBuilder

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.