Создание embed discord js

Обновлено: 03.07.2024

Начнём. Ссылка на мой youtube канал.

Discord bot туториал. Туториал по созданию ботов для дискорда на node.js используя discord.js.

Creation date : 06.12.2019

Давайте начнём создание бота. Если у вас установлена node.js, то пропустите сделающие 2 строчки. Заходим на сайт node.js, скачиваем, устанавливаем. Скриншотов процесса установки нету, тк переустанавливать node.js нету желания. Но там всё интуитивно понятно.

Создание файлов, инициализация проекта, установка библиотек.

Создаём папку bot. Желательно не использовать кирилицу, юникод и т. п. в названии. Сразу же создаём файл index.js или bot.js. Это не несёт особого смысла. Можно назвать как угодно, но принятно index.js / bot.js. Это будет главный файл бота, т.е. первым запускается, в нём основной код бота. Далее открываем консоль / терминал если у вас linux. Для быстрого открытия консоли на windows можно нажать WIN + R, ввести cmd. Далее переходим в папку бота, думаю как это сделать через консоль всем понятно. Пишим : npm init - инициализация проекта. Жмём enter до конца. Если ошибка в package name, то напишите bot. npm i discord.js - установка библиотеки discord.js.

Далее рекомендую установить один из следующих редакторов кода :

Если очень слабый компьюер можете поставить notepad++, но это для постоянной основы не самый хороший вариант. Лично я использую Atom.

Вы можете зарегистрировать его на сайте discord developers. Жмём кнопку "New Application". Вводим название бота. Жмём "Create". Переходим во вкладку "Bot", нажимаем "Add Bot", затем "Yes, do it!" Находим строку "token", немного ниже есть кнопка "Copy", нажимаем. Теперь в вашем буфере обмена есть токен бота.

Создадим первый код. Пишем :

Открываем консоль, переходим в папку проекта и пишем :

в зависимости от названия файла. Если у вас windows, то вы можете создать файл start.bat с текстом

Если линукс, то вы можете создать файл start.sh

Это будет запускать бота. Далее я не буду говорить про запуск. Делайте это сами.

Создаем файл config.json с конфигурацией нашего бота.

В начале кода бота напишем :

Еще вы можете создать конфиг прямо в коде бота.

Но второй вариант крайне не рекомендуется использовать, ведь для того что-бы изменить конфиг бота нам придется изменять его код.

Давайте залогируем тег автора.

Также можно писать не

.startsWith проверят начинается ли строка с символов в аргументах.

Также даже начинающим программистам будет очень полезна в боте команда !eval для выполнения кода не пиша его в коде бота, т.е. вы пишите !eval какой-то код и бот выполняет этот код.
Я нашёл хороший туториал по этой команде на github. Рекомендую ознакомиться и взять себе команду в код бота. Принцип её работы мы разберём позже. Тык.

Image alt

Это называется RichEmbed (Embed). Давайте отправим простой эмбед похожий на данный. (Картинка ниже)

Image alt

Для этого создадим новую команду !ping .

В Embed есть много различных параметров, вы можете прочесть их далее, либо посмотреть на оффициальном сайте discord.js

Давайте сделаем команду для получения информации о пользователе. Команда взята из моего бота. Будем использовать библиотеку moment.js , устанавливаем npm i moment.js

Image alt

Мой дискорд сервер!

Прошу зайти на мой дискорд сервер, ведь я долго делал туториал, а вам не сложно зайти на мой сервер в виде благодарности.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

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.

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




Some footer text here • 01/01/2018

discord.js features the MessageEmbed

open in new window utility class for easy construction and manipulation of embeds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

The .setColor() method accepts a ColorResolvable

open in new window , e.g. an integer, HEX color string, an array of RGB values or specific color strings.

The above example chains the manipulating methods to the newly created 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).

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

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.

You can upload images with your embedded message and use them as source for embed fields that support image URLs by constructing a MessageAttachment

open in new window from them to send as message option alongside the embed. The 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 .

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

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

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!

To edit the content of an embed you need to pass a new 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.

You can check your discord.js version with the list command. Should it still show v12.x, uninstall and re-install discord.js and make sure the entry in your package.json does not prevent a major version update. Please refer to the npm documentation

discord.js v13 makes the switch to Discord API v9! In addition to this, the new major version also includes a bunch of cool new features.

discord.js now has support for slash commands! Refer to the slash commands section of this guide to get started.

In addition to the interactionCreate event covered in the above guide, this release also includes the new Client events applicationCommandCreate , applicationCommandDelete , and applicationCommandUpdate .

discord.js now has support for message components! This introduces the MessageActionRow , MessageButton , and MessageSelectMenu classes, as well as associated interactions and collectors.

Refer to the message components section of this guide to get started.

discord.js now has support for threads! Threads are a new type of sub-channel that can be used to help separate conversations into a more meaningful flow.

Refer to the threads section of this guide to get started.

Support for voice has been separated into its own module. You now need to install and use @discordjs/voice

open in new window for interacting with the Discord Voice API.

Refer to the voice section of this guide to get started.

A popular request that has finally been heard - the Client class now has a new option, makeCache . It accepts a CacheFactory .

Additional flexibility can be gained by providing a function which returns a custom cache implementation. Keep in mind this should still maintain the Collection / Map -like interface for internal compatibility.

Additionally, all messages sent by bots now support up to 10 embeds. As a result, the embed option was removed and replaced with an embeds array, which must be in the options object.

The code and split options have also been removed. This functionality will now have to be handled manually, such as via the Formatters.codeBlock and Util.splitMessage helpers.

Many methods in discord.js that were documented as accepting strings would also accept other types and resolve this into a string on your behalf. The results of this behavior were often undesirable, producing output such as [object Object] .

discord.js now enforces and validates string input on all methods that expect it. Users will need to manually call toString() or utilize template literals for all string inputs as appropriate.

The shortcuts Intents.ALL , Intents.NON_PRIVILEGED , and Intents.PRIVILEGED have all been removed to discourage bad practices of enabling unused intents.

The concept of extendable Structures has been completely removed from discord.js. For more information on why this decision was made, refer to this pull request

There is no swap-in replacement for this, as the intention is to change the code design rather than enable something equally bad.

For some real-world example of the alternatives provided in the PR, you may have been extending the Guild class with guild-specific settings:

This functionality can be replicated using the WeakMap or Collection example, even attaching it to the Client if necessary:

All Collector related classes and methods (both .create*() and .await*() ) now take a single object parameter which also includes the filter.

Some commonly used naming conventions in discord.js have changed.

The casing of thingID properties has changed to thingId . This is a more-correct casing for the camelCase used by discord.js as Id is an abbreviation of Identifier, not an acronym.

This includes: afkChannelId , applicationId , channelId , creatorId , guildId , lastMessageId , ownerId , parentId , partyId , processId , publicUpdatesChannelId , resolveId , rulesChannelId , sessionId , shardId , systemChannelId , webhookId , widgetChannelId , and workerId .

clientOptions.disableMentions has been removed and replaced with clientOptions.allowedMentions ! The Discord API now allows bots much more granular control over mention parsing, down to the specific id.

The new MessageOptions.allowedMentions.repliedUser boolean option determines if the reply will notify the author of the original message.

Note that this will disable all other mentions in this message. To enable other mentions, you will need to include other allowedMentions fields. See the above "Allowed Mentions" section for more.

Bitfields are now BigInt s instead of Number s. This can be handled using the BigInt() class, or the n-suffixed BigInt literal

In addition, the usage of string literals for bitfield flags such as Permissions and UserFlags is discouraged; you should use the flag instead.

On Discord API v8 and later, DM Channels do not emit the CHANNEL_CREATE event, which means discord.js is unable to cache them automatically. In order for your bot to receive DMs, the CHANNEL partial must be enabled.

Webpack builds are no longer supported.

The CUSTOM_STATUS type has been renamed to CUSTOM .

The APIMessage class has been renamed to MessagePayload , resolving a naming clash with an interface in the discord-api-types library which represents raw message data objects.

The Client Emoji manager is now a BaseGuildEmojiManager , providing cache resolution only and removing methods that would fail to create emojis as there was no Guild context.

This method has been renamed to fetchGuildWidget to better represent its functionality.

To generate an invite link with slash commands permissions:

To generate an invite link for a bot and define required permissions:

Previously when a token had reached its 1000 login limit for the day, discord.js would treat this as a rate limit and silently wait to login again, but this was not communicated to the user. This will now instead cause an error to be thrown.

The Client timeout methods have all been removed. These methods existed for the purpose of caching timeouts internally so they could be cleared when the Client is destroyed. Since timers now have an unref method in Node, this is no longer required.

To reduce caching, discord.js will no longer store an edit history. You will need to implement this yourself if required.

These methods existed to provide access to a cached array of Collection values and keys respectively, which other Collection methods relied on internally. Those other methods have been refactored to no longer rely on cache, so those arrays and these methods have been removed.

You should instead construct an array by spreading the iterators returned by the base Map class methods:

Colors have been updated to align with the new Discord branding.

These methods have been removed, with functionality replaced by the new GuildBanManager .

This method has been removed, with functionality replaced by the new GuildInviteManager .

This method has been removed, with functionality replaced by the new PermissionOverwriteManager .

These methods have been removed from GuildChannel and placed only on subclasses for which invites can be created. These are TextChannel , NewsChannel , VoiceChannel , StageChannel , and StoreChannel .

On these subclasses, the method now supports additional options:

  • targetUser to target the invite to join a particular streaming user
  • targetApplication to target the invite to a particular Discord activity
  • targetType defines the type of the target for this invite; user or application

This method has been removed, with functionality replaced by the new PermissionOverwriteManager .

This method no longer returns a Collection of PermissionOverwrites, instead providing access to the PermissionOverwriteManager .

This method has been removed, with functionality replaced by the new PermissionOverwriteManager .

None of these properties were actually provided by Discord, instead relying on potentially inaccurate client cache, and have been removed.

The Message.delete() method no longer accepts any options, requiring a timed-delete to be performed manually.

reason is no longer a parameter as it is not used by the API.

The MessageManager.delete() method no longer accepts any additional options, requiring a timed-delete to be performed manually.

reason is no longer a parameter as it is not used by the API.

Permissions.FLAGS.MANAGE_EMOJIS is now Permissions.FLAGS.MANAGE_EMOJIS_AND_STICKERS .

The before option has been removed as it was not supported by the API.

The spawnTimeout param has been renamed to timeout .

These methods have both been replaced by a singular TextChannel.sendTyping() . This method automatically stops typing after 10 seconds, or when a message is sent.

Neither of these properties were actually provided by Discord, instead relying on potentially inaccurate client cache, and have been removed.

The User.locale property has been removed, as this property is not exposed to bots.

The User.presence property has been removed. Presences are now only found on GuildMember .

As discord.js no longer caches typing event data, the User.typingIn() method has been removed.

As discord.js no longer caches typing event data, the User.typingSinceIn() method has been removed.

As discord.js no longer caches typing event data, the User.typingDurationIn() method has been removed.

The deprecated UserFlags DISCORD_PARTNER and VERIFIED_DEVELOPER / EARLY_VERIFIED_DEVELOPER have been removed in favor of their renamed versions.

The new flag DISCORD_CERTIFIED_MODERATOR has been added.

Shortcuts to Util methods which were previously exported at the top level have been removed.

The WebhookClient constructor no longer accepts id, token as the first two parameters, instead taking a data object. This object supports an additional option url , allowing creation of a WebhookClient from a webhook URL.

A new activity type COMPETING has been added.

Provides API support for slash commands.

Provides API support for creating, editing and deleting slash commands.

Provides API support for creating, editing, and deleting permission overwrites on slash commands.

Provides an enumerated bitfield for ClientApplication flags.

The new BaseGuild class is extended by both Guild and OAuth2Guild .

The new BaseGuildTextChannel class is extended by both TextChannel and NewsChannel .

The new BaseGuildVoiceChannel class is extended by both VoiceChannel and StageChannel .

Provides gateway support for a MessageComponentInteraction coming from a button component.

Checks and typeguards if a channel is Text-Based; one of TextChannel , DMChannel , NewsChannel or ThreadChannel .

Checks and typeguards if a channel is a ThreadChannel .

Checks and typeguards if a channel is Voice-Based; VoiceChannel or StageChannel .

Emitted when a guild application command is created.

Emitted when a guild application command is deleted.

Emitted when a guild application command is updated.

Emitted when an interaction is created.

Emitted when a stage instance is created.

Emitted when a stage instance is deleted.

Emitted when a stage instance gets updated, e.g. change in topic or privacy level.

Emitted when a custom sticker is created in a guild.

Emitted when a custom sticker is deleted in a guild.

Emitted when a custom sticker is updated in a guild.

Emitted when a thread is created or when the client user is added to a thread.

Emitted when a thread is deleted.

Emitted when the client user gains access to a text or news channel that contains threads.

Emitted when members are added or removed from a thread. Requires the GUILD_MEMBERS privileged intent.

Emitted when a thread is updated, e.g. name change, archive state change, locked state change.

This parameter is now optional and will fall back to a function that always returns true if not provided.

Provides gateway support for slash command interactions. For more information refer to the slash commands section of the guide.

Provides access to the new GuildInviteManager .

Provides improved API support for handling and caching bans.

Now supports setting the position property.

Now supports fetching the channels of a Guild.

Retrieves a list of the active threads in a Guild.

Now supports specifying the AFK and system channels when creating a new guild.

Now supports fetching multiple guilds, returning a Promise<Collection<Snowflake, OAuth2Guild>> if used in this way.

Provides API support for the GET /guilds//emojis endpoint.

Several methods were added to GuildMemberManager to provide API support for uncached members.

Gets the managed role this member created when joining the guild if any.

Gets the premium subscriber (booster) role if present on the member.

The datetime at which the GuildPreview was created.

Provides API support for server templates

A Collection of Roles which are managed by the integration.

Provides gateway support for slash command and message component interactions.

For more information refer to the slash commands and message components sections of the guide.

Provides a way for users to collect any type of Interaction. This class has a more flexible design than other Collectors, able to be bound to any Guild, Channel, or Message as appropriate. TypeScript developers can also leverage generics to define the subclass of Interaction that will be returned.

Provides webhook support specifically for interactions, due to their unique qualities.

Provides API support for the partial Guild data available from an Invite .

Provides API support for bots to inviting users to stage instances.

A shortcut method to create a promisified InteractionCollector which resolves to a single MessageComponentInteraction .

A shortcut method to create an InteractionCollector for components on a specific message.

Checks permissions to see if a Message can be crossposted.

Editing and/or removing attachments when editing a Message is now supported.

Now supports both <:name:id> and <a:name:id> as valid inputs.

Removes the attachments from a message. Requires MANAGE_MESSAGES to remove attachments from messages authored by other users.

Starts a ThreadChannel using this message as the starter message.

A Collection of Stickers in the message.

A builder class which makes constructing action row type message components easier.

The media type of a MessageAttachment.

A builder class which makes constructing button type message components easier.

Provides gateway support for receiving interactions from message components. Subclass of Interaction .

Replaces all fields in the embed with the new array of fields provided.

embed.setFields(newFields) is equivalent to embed.spliceFields(0, embed.fields.length, newFields) .

Methods were added to MessageManager to provide API support for uncached messages.

Checks if the author of a message being replied to has been mentioned.

A builder class which makes constructing select menu type message components easier.

Provides API support for bots to follow announcements in other channels.

Allows conversion between NewsChannel and TextChannel.

Static bitfield representing the permissions required to moderate a stage channel.

Replaces the createOverwrite , updateOverwrite , and overwritePermissions methods of GuildChannel , aligning the design with other Managers.

Tags for roles belonging to bots, integrations, or premium subscribers.

Gets the managed role a bot created when joining the guild, if any.

Gets the premium subscriber (booster) role for the Guild, if any.

Provides gateway support for a MessageComponentInteraction coming from a select menu component.

Provides API support for stage channels.

Provides API support for stage instances. Stage instances contain information about live stages.

Provides API support for the bot to create, edit, and delete live stage instances, and stores a cache of stage instances.

Provides API support for Discord Stickers.

Provides API support for Discord Sticker packs.

A shortcut method to create a promisified InteractionCollector which resolves to a single MessageComponentInteraction .

A shortcut method to create an InteractionCollector for components on a specific channel.

Allows conversion between TextChannel and NewsChannel .

Provides access to the ThreadManager for this channel.

Provides API support for thread channels.

Provides API support for the bot to create, edit, and delete threads, and stores a cache of ThreadChannels .

Represent a member of a thread and their thread-specific metadata.

Provides API support for the bot to add and remove members from threads, and stores a cache of ThreadMembers .

Represents a typing state for a user in a channel.

Webhooks can now delete messages that were sent by the Webhook.

Webhooks can now edit messages that were sent by the Webhook.

Webhooks can now fetch messages that were sent by the Webhook.

Webhooks can now have a sourceGuild and sourceChannel if the message is being crossposted.

A number of new formatter functions are provided in the Util class, to easily handle adding markdown to strings.

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.

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 footer text here • 01/01/2018

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).

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.

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

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.

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.

We will now explain how to edit embedded message content and resend 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!

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.

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:

Читайте также: