Перейти к содержимому

Что такое эмбеды в дискорде

  • автор:

Using Webhooks and Embeds

As moderators work towards bringing improvements to our communities, you need to consider every tool available at your disposal. One great feature that is often overlooked by moderators is webhooks, which can prove to be incredibly powerful when implemented well, especially for server automation. In this article we will be introducing webhooks, exploring how they work, and how they compare to bots in addition to going over some of the best practices when utilizing webhooks in the context of moderation on Discord.

Before we begin, we highly recommend you check out the Intro to Webhooks article published by Discord.

What is a Webhook?

A webhook is sort of a “reverse API”: rather than an application you own (like a bot) calling another application to receive data when it wants it, a webhook is something you can give to someone else's application to send data to you directly as soon as there’s something to share. This makes the process very convenient and efficient for both providers and users.

Now let’s apply this definition to a more tangible example. Let’s say you aren’t around to reply to new e-mails for a while. Through the power of webhooks you could have a setup that replies automatically! When an event happens on a service (like receiving an email), that service activates your webhook and sends you the data relevant to the event that happened. That way, you have exactly the information you need to automatically reply to each new e-mail you receive.

So what does this mean for your server? Basically, Discord provides you with the ability to have a webhook that sends a message to your server when it’s activated, with the option to send the message to any channel along with having a cool name and avatar of your choice.

For example, let’s say you’re waiting for the latest chapter of your favorite webcomic series to release. You can set up a webhook that’s connected with an RSS feed. The feed will activate the webhook when the chapter is released and a message will be posted on your server to notify you about it. This can be applied to many different things — the potential is limitless!

If the service is capable of sending JSON Webhooks, Discord can often use these to create visually appealing embeds when it sends a message out. However, it can also accept raw text messages to pass along as well.

Usage of Webhooks

Webhooks are a great tool for services that have events that you’re interested in latching onto. This can be incredibly useful for Content Creator communities where their latest YouTube videos or Twitter posts can be funneled into channels for followers to have easy viewing access in your Discord community. You could also use this for a community that’s oriented towards an open-source technology by having events from GitHub be submitted directly to your server for people to keep track of.

There are a lot of platforms out there that provide you with the ability to handle everything by yourself- from creating the Webhook through your Discord Server Settings to plugging it into the platform you want updates from. However, this often requires you to be more familiar with at least some level of programming as many of these platforms require developer accounts. There can be a few hoops to jump through to get everything set up just right. This can often turn people off from using these types of webhooks.

However, times are changing and the barrier to entry when dabbling into the world of webhooks is much lower. These days, multiple third-party services exist that have handled all the hard techy stuff for you. They can interface with the platforms that would normally require you to do extra work to get the data you want. IFTTT and Zapier are two such services that lets you plug-and-play several useful platforms directly into your Discord server through a clean web interface that allows you to customize the type of data your webhook receives, and thus what messages are sent to your server. Just keep in mind that some services have restrictions on how many events can be sent to one webhook, so you may have to create multiple distinct webhooks for multiple functionalities. Note that these options and restrictions are entirely platform-dependent. Discord has no problems handling whatever data is thrown at its webhooks when activated, even if it’s from different sources.

There’s another use-case for Webhooks that is more unique. While they’re very useful for automated messages, they’re also great for one-off embed messages that have a very polished look! You have the ability to customize the name and the avatar of the webhook, but if you’re technologically-inclined you can create your own JSON data to activate the webhook with. This allows you to fully define the aesthetics of an embed in your message, giving a clean look to whatever information you’re sending. One possible application is nice formatting for your server rules and information, rather than just sending multiple plain text messages.

Of course, there are other possible uses, the only limit is your creativity! If you’re not too keen on developing JSON data by hand, or have no idea what a “JSON” is, services like Discohook also make it easy for anyone to take advantage of this use case. As a note, the websites linked here are not endorsed by Discord and are only a suggestion from the authors of the article.

How do I set up a webhook?

The process of setting up webhooks can be roughly explained in five simple steps!

Step 1: In your Discord server, you will need to create a webhook and copy the webhook URL. This URL is the path for your webhook to receive an HTTP POST request from a service when an event occurs.

Step 2: From this menu, you have the ability to style your webhook with a name and avatar. We recommend at least a name to distinguish its purpose.

Step 3: If you’re using a third-party service to handle events or send messages, plug your webhook URL into the service and configure the type of events that the service should trigger for.

Step 4: If your third-party service allows you to, configure additional options that will change the look and content of your message to the way you like.

Step 5: Now that you’ve created the connection, when the event happens, the data will be sent directly to Discord and your webhook will post a message in your preferred channel!

What is an Embed?

We’ve been talking about embeds a lot, but we haven’t quite explained what they are yet! In simple terms, embedding refers to the integration of links, images, GIFs, videos and other forms of content into messages on social media. An embed itself is a part of the message that visually represents content in order to increase engagement.

As a user of Discord, you have probably seen embeds more than a few times. They often are created automatically by Discord when a user sends a link, such as allowing you to view a YouTube video within Discord when a YouTube URL is shared. But did you know that Discord Bots and Webhooks can create their own embeds with all kinds of data? They’re pretty flexible! They can have colored borders, images, text fields, and other kinds of fancy properties.

If you're a developer, the options available to you to create a good-looking embed are powerful and versatile. For non-developers, platforms may give you visualizations that help you plug-and-play data into a website for customization purposes. There are also online tools to help you do this too!

Here are several of those properties that can be modified in an embed in order to style it, to give you an idea of what’s possible when you have the ability to style your messages:

Эмбеды

Возможно, вы видели некоторые специальные сообщения в Discord (часто отправляемые ботами/вебхуками), которые имеют цветную рамку, встроенные изображения, текстовые поля и другие свойства. Эти элементы называются Эмбедами, и в этом разделе будет рассказано, как вы можете создать и отправить их с помощью своего бота. Это делается с помощью объекта Embed .

В этом разделе будут подробно рассмотрены атрибуты и методы, используемые в эмбедах. Таким образом, мы рекомендуем перейти к нужной вам теме через оглавление.

Предпросмотр эмбеда​

Вот пример того, как может выглядеть эмбед. Мы рассмотрим конструкцию эмбеда в следующей части этой статьи.

Автор эмбеда

Футер эмбеда • 01/01/2077

Код для этого эмбеда приведен ниже.

Нет строгой необходимости использовать все элементы, представленные выше. Вы можете оставить некоторые из них в соответствии с вашими потребностями.

Цвет вставки (с помощью параметра color ) принимает экземпляр Colour , шестнадцатеричная строка или целое число.

Чтобы добавить пустое поле для эмбеда, вы можете использовать embed.add_field(name='\u200b', value='\u200b') .

Создание эмбеда​

Вы можете использовать Embed для создания эмбедов и манипулирования ими.

Установка автора​

Вы можете указать автора эмбеда с помощью метода set_author . Обратите внимание, что этот код запускается после того, как вы определили embed через embed = disnake.Embed(. ) .

Автор эмбеда

Поскольку в этом случае мы установили URL-адрес, нажатие на "Автор эмбеда" перенаправит пользователя на сайт disnake.dev .

Установка футера​

Вы можете указать футер эмбеда с помощью метода set_footer . Обратите внимание, что этот код запускается после того, как вы определили embed через embed = disnake.Embed(. ) .

Автор эмбеда
Футер эмбеда

Установка миниатюры​

Вы можете указать миниатюру с помощью метода set_thumbnail . Обратите внимание, что этот код запускается после того, как вы определили embed через embed = disnake.Embed(. ) .

Автор эмбеда

It is shown in the top-right corner of the embed. You can set this as a URL, but disnake also allows you to use a locally stored file instead, using the file parameter.

Футер эмбеда • 01/01/2077

Использование временных отметок​

Временные отметки отображаются возле футера эмбеда, указывая время, в которое было отправлен/инициирован эмбед. Это можно сделать с помощью параметра timestamp disnake.Embed() . Обратите внимание, что вам нужно будет импортировать пакет datetime в ваш код.

Автор эмбеда
Футер эмбеда • 01/01/2077

Добавление полей​

Поля эмбеда имеют два параметра — название (или заголовок) и значение внутри с помощью метода add_field . Также можно использовать markdown в обоих параметрах.

Автор эмбеда
Футер эмбеда • 01/01/2077

Эти атрибуты также полностью поддерживают использование markdown, а также выделение ссылок. Вы также можете вставлять поля в определенную позицию с указанным индексом, используя embed.insert_field_at(index, . ) .

Добавление изображений​

Это можно сделать с помощью методв set_image , который принимает либо ссылку, либо объект File .

Автор эмбеда

Футер эмбеда • 01/01/2077

Отправка эмбеда​

Как только эмбед будет создан, вам также нужно отправить его в канал. Это означает, что вам нужно вызвать метод send(embed=embed) для объекта, например объекта TextChannel (т.е. message.channel.send ) или объекта Context ( ctx.send ). В противном случае эмбед не будет отправлен.

Словарь в эмбед​

Тип данных dict (и, по сути, файл json ) может быть преобразован в вложение, используя метод Embed.from_dict() . Мы можем воссоздать вставку, сделанную в начале этой страницы, используя то же самое.

Это даст точно такой же результат, как и встраивание, показанное здесь. Обратите внимание, что временная отметка, передаваемая через словарь, должна быть в формате ISO8601 (что было достигнуто здесь с помощью datetime.datetime.now().isoformat() ). Вы можете узнать больше о формате вложений dict в официальной документации Discord.

Примечания​

  • Для отображения полей рядом друг с другом необходимо, чтобы по крайней мере для двух последовательных полей было установлено значение inline=True .
  • Временная отметка автоматически настраивает часовой пояс в зависимости от устройства пользователя.
  • Упоминания любого рода в эмбедах будут корректно отображаться только в пределах описания и значений полей эмбеда.
  • Упоминания во вложениях не будут вызывать уведомление.
  • Эмбеды позволяют маскировать ссылки (например, [Guide](https://guide.disnake.dev/ 'optional hovertext') ), но только в описании и значениях полей.

Ограничения​

Есть несколько ограничений, о которых следует помнить при планировании ваших эмбедов из-за ограничений API. Вот краткий список ограничений:

  • Заголовок эмбеда ограничен 256 символами.
  • Описание эмбеда ограничен 4096 символами.
  • Максимум 25 полей.
  • Название поля ограничено 256 символами и их значение 1024 символами.
  • Текст футера ограничен 2048 символами.
  • Имя автора ограничено 256 символами.
  • Сумма всех символов из всех структур эмбеда в сообщении не должна превышать 6000 символов.
  • Одно сообщение может содержать до 10 эмбедов.

Получившийся код​

Код, представленный на этой странице, можно найти в нашем репозитории GitHub здесь.

# Embeds

If you have been around on Discord for a bit, chances are you have seen these special messages, often sent by bots. They can have a colored border, embedded images, text fields, and other fancy properties.

In the following section, we will explain how to compose an embed, send it, and what you need to be aware of while doing so.

# Embed preview

Here is an example of how an embed may look. We will go over embed construction in the next part of this guide.

Guide Bot

Some name

Some footer text here • 01/01/2018

# Using the embed constructor

discord.js features the RichEmbed

(opens new window) utility class for easy construction and manipulation of embeds.

In version 12, the receiving and outgoing embed classes have unified; you will need to use Discord.MessageEmbed() as a constructor instead.

You don’t need to include all the elements showcased above. If you want a simpler embed, leave some out.

The .setColor() method accepts an integer, HEX color string, an array of RGB values or specific color strings. You can find a list of them at the discord.js documentation

.addBlankField() is a convenience method for .addField(‘\u200b’, ‘\u200b’) , used to add a spacer to the embed. It can also be used inline by passing true as the first parameter.

.addBlankField() was a convenience method to add a spacer to the embed. To add a blank field you can now use .addField(‘\u200b’, ‘\u200b’) instead.

The above example chains the manipulating methods to the newly created RichEmbed MessageEmbed object. If you want to modify the embed based on conditions, you will need to reference it as the constant exampleEmbed (for our example).

# Attaching images

You can use the .attachFiles() method to upload images alongside your embed and use them as source for embed fields that support image urls. The method accepts the source file as file path FileOptions

(opens new window) , BufferResolvable (including a URL to an external image), or Attachment objects inside an array.

You can then reference and use the images inside the embed itself with attachment://fileName.extension .

If you plan to attach the same image repeatedly, consider hosting it online and providing the URL in the respective embed field instead. This also makes your bot respond faster since it doesn’t need to upload the image with every response depending on it.

If the images don’t display inside the embed but outside of it, double-check your syntax to make sure it’s as shown above.

# Using an embed object

You don’t need to include all the elements showcased above. If you want a simpler embed, leave some out.

The color field has to be an integer for embed objects! If you have a hex color string (e.g. ‘#7289da’ ), you can replace the # with 0x to use it as a number: 0x7289da .

If you want to modify the embed object based on conditions, you will need to reference it directly (as exampleEmbed for our example). You can then (re)assign the property values as you would with any other object.

# Attaching images

You can upload images with your embedded message and use them as source for embed fields that support image urls by constructing an Attachment

(opens new window) from them to send as message option alongside the embed. The file attachment parameter takes a BufferResolvable or Stream including the URL to an external image.

You can then reference and use the images inside the embed itself with attachment://fileName.extension .

If you plan to attach the same image repeatedly, consider hosting it online and providing the URL in the respective embed field instead. This also makes your bot respond faster since it doesn’t need to upload the image with every response depending on it.

If the images don’t display inside the embed but outside of it, double-check your syntax to make sure it’s as shown above.

# Resending and editing

We will now explain how to edit embedded message content and resend a received embed.

# Resending a received embed

To forward a received embed you retrieve it from the messages embed array ( message.embeds ) and pass it to the RichEmbed MessageEmbed constructor. The constructed RichEmbed MessageEmbed can then be edited before sending it again.

You cannot resend the received embed structure! The MessageEmbed returned from message.embeds contains circular structures and needs to be converted to a RichEmbed object before sending. We deliberately create a new Embed here instead of just modifying message.embeds[0] directly to keep the cache valid. If we were not to do this, the embed in cache on the original message would diverge from what the actual embed looks like, which can result in unexpected behavior down the line!

# Editing the embedded message content

To edit the content of an embed you need to pass a new RichEmbed MessageEmbed structure or embed object to the messages .edit() method.

If you want to build the new embed data on a previously sent embed template, make sure to read the caveats in the previous section.

# Notes

  • To display fields side-by-side, you need at least two consecutive fields set to inline
  • The timestamp will automatically adjust the timezone depending on the user’s device
  • Mentions of any kind will only render correctly in field values and descriptions
  • Mentions in embeds will not trigger a notification
  • Embeds allow masked links (e.g. [Guide](https://discordjs.guide/ ‘optional hovertext’) ), but only in description and field values

# Embed limits

There are a few limits to be aware of while planning your embeds due to the API’s limitations. Here is a quick reference you can come back to:

Creating embeds on Discord using Carl Bot.

Priya Sharma

Discord has become increasingly popular this year. It has features that are appreciated by gamers and study groups alike. What makes discord so special is the ability to automate various tasks using bots. There are several popular bots each special in their own way with new ones releasing every day.

One bot-specific feature is the ability to post embeds. Embeds are rich-text messages that allow markdown as well as the ability to add authors, titles, and footers. Embeds are systematic messages that make your server look professional. They can be used to create custom announcements, custom welcome messages, or even add a list of roles that can be attained by reactions. In this article, we’ll be learning how to create embeds using carl-bot with minimum coding.

The rawest way to create an embed would be by using JSON and then posting it using your custom bot. But, not all of us are familiar with JSON or deploying custom bots for that matter. That’s where pre-built bots come in. The most user-friendly bot interface I have found so far is of carl bot although you can also look into other options like Dyno. Make sure you invite carl bot into your server by using this link.

Carl bot supports both text commands as well as passing instructions through its web interface. We will look into the web dashboard in this article. Once you head over to https://carl.gg/, log in to your discord account by clicking on the login button. Authorize carl bot to access details like servers you are in and your avatar (this is necessary for the web dashboard to get linked to your account so that everything happens in the right server). Once that’s done, you’ll see all the servers you can manage (make sure you have the manage servers permission before trying to send embed messages).

Grayed-out servers mean that you have the necessary permission but the carl bot isn’t in the server. For example, in the image above, AI adda, Choices After Dark, etc. are colored and hence ready to be customized. Array Alacrity, Bot banaenge, etc. don’t have carl bot invited. Click on the server of your choice to open a detailed dashboard that looks like this —

The side menu has all the different categories you can customize. For this article, our category of interest is “Embeds” which is at the bottom left of the screen.

Here’s some info about various fields you can customize:
1. Normal text with the embed: This text is sent as the message along with the embed. It looks like a normal text message.
2. Toggle Colour Picker: Clicking it opens a color editor that allows you to customize embed color. The embed color is the color of the strip on the left of the embed. The top embed example has an embed color of orange. You can also choose to provide the hex code or RGBA value if the color picker is not convenient.
3. Icon Url: Here, you can provide the URL (link) to the image you want to display as an icon beside the author/name field. It is the smallest image on an embed after the footer icon. Make sure the URL you enter ends with .png or .jpg
4. Name: Name of the author or authority that is sending the embed. Appears on the very top of the embed with size smaller than that of title.
5. Name URL: URL that is to be hyperlinked with Name field text. Could be the company website or information about the author.
6. Title: The title of the embed, appears right below Author and is the largest text in size.
7. Title URL: URL that is to be hyperlinked with Title field text. Can be an external link to embed information.
8. Description: The heart and soul of your embed where you can post all information. This field supports markdown as well.
9. Adding Fields: If your description happens to have several sub-topics, it is recommended to use fields. Right below the description section, there’s a button to add a field. You can create a maximum number of 25 fields.
9.1. Field Title: A field title is the sub-title or sub-heading to your embed. It is bolder and slightly larger than the description text. Though, it does not support hyperlinks.
9.2. Field Description: Description for that sub-topic.
9.3. Inline Toggle: The inline toggle when enabled, allows you to create multiple columns each having different fields. Useful to save space and display content sideways. If it is disabled, the fields appear one below the other.
10. Image URL: URL for the big image at the bottom of the embed. Just like the Icon URL, make sure your link ends with .png or .jpg (or .gif). This big image can also be a gif.
11. Thumbnail URL: Thumbnails are small images displayed on top right corner of the Embed. It is larger than Icon but much smaller than Image.
12. Footer: The footer represents the tiny text at the very bottom of embed that can be used as log message or disclaimer.
13. Footer Icon: The footer icon is a tiny icon image on bottom left corner of screen, right besides the footer. This field requires a URL with .png or .jpg.
14. Date: This date is to be printed besides the footer, you can either use current date and time or a specific date. Useful for logging.
15. Destination: This drop-down has a list of all the channels in your server and you can select the one where you want to post your embed message in. This is also the last option in our embed builder.

None of the fields mentioned above are necessary so you can play with a combination of different field types to create various kinds of embed messages.

Things to take care of when writing embeds using carl bot’s embed builder —

  • URL fields must be an HTTP/HTTPS formatted URL (begins with http:// or https://).
  • All Title fields, the (Author’s) Name field, and the Footer cannot properly display Discord mentions or named links, and have limited support of markdown formatting.
  • If an additional field exists, neither the title nor the description can be empty.
  • “Name” must have a value for “Name URL” to work.
  • “Title” must have a value for “Title URL” to work.
  • “Name” must have a value for “Icon URL” to display.
  • “Footer” must have a value for the “Footer icon” to display.
  • In addition to the stated character limits for each field provided below the embed builder’s text boxes, the sum of all characters in an embed must not exceed 6000 characters.
  • Do not put values in the JSON “timestamp”: field if you don’t know the correct format for them. The correct format is ISO 8601: yyyy-mm-ddTHH:MM:SS.000Z
  • It is advisable to save the JSON code of your embed by clicking on the COPY TO CLIPBOARD option below preview (on right side) and then pasting it somewhere you can easily access. This will be helpful when we’d want to edit the embed (tutorial coming soon!)

Thank you so much for hanging this long. If you followed along the tutorial, you must have made some beautiful embeds. You can look for more information about embeds in carl bot’s documentation.

Do let me know what discord topic should I write about next! Byeeee!

PS. I will make a separate post about markdown language supported by discord text and embed messages.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *