Как сделать Embed в 2 линии и в 2 столбца? discord.py
Мне нужно сделать что бы Embed располагался так что бы 2 блока было в первом ряду и 2 блока во-втором ряду, но у меня получается только в первом ряду 2 блока во-втором 1 блок и еще третий ряд получается с 1 блоком: А мне нужно сделать что бы Монеты и Очки были на 1 линии, как это можно сделать?
@client.command() async def stat(ctx): await ctx.channel.purge(limit=1) emb = discord.Embed(title='Статистика', color=discord.Colour.blue()) emb.add_field(name='Name', value=f'', inline=True) emb.add_field(name='Ранг', value='На калибровке', inline=True) emb.add_field(name='Монеты', value='0', inline=False) emb.add_field(name='Очки', value='0', inline=True) await ctx.send(embed = emb)
Отслеживать
задан 6 фев 2022 в 11:28
141 10 10 бронзовых знаков
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
@client.command() async def stat(ctx): await ctx.channel.purge(limit=1) emb = discord.Embed(title='Статистика', color=discord.Colour.blue()) emb.add_field(name='Name', value=f'', inline=True) emb.add_field(name='Ранг', value='На калибровке', inline=True) emb.add_field(name='Монеты', value='0', inline=True) emb.add_field(name='Очки', value='0', inline=True) await ctx.send(embed = emb)
Отслеживать
ответ дан 12 фев 2022 в 15:52
Daniela SHABA Daniela SHABA
Ваш ответ можно улучшить с помощью дополнительной информации. Пожалуйста, нажмите править для добавления подробностей, например, цитат или документации, чтобы другие могли подтвердить правильность вашего ответа. Вы можете найти дополнительную информацию о том, как писать хорошие ответы в Справке.
12 фев 2022 в 15:56
добро пожаловать на Stack Overflow на русском! пожалуйста, постарайтесь оставлять чуть более развёрнутые ответы. дополнить ответ можно, нажав править
12 фев 2022 в 15:59
У вас в первой линии 3 столбца, а во второй 1 столбец, проверяйте пожалуйста код который вы написали
Как сделать embed сообщение в discord python
Быстрый переход в группу «Пользователи», без надобности написания постов и ожидания.
Покупка дает возможность:
Быть полноправным участником форума
Нормальное копирование кода
Создавать темы
Скачивать файлы
Доступ к архиву Pawno-Info
Маппинг для сервера
Если вы хотите обновить Ваш сервер новыми доработками — то зайдите в наш раздел. Большой выбор готовых решений от наших пользователей
Моды для сервера
Огромный выбор различных модификаций для Вашего сервера. Пролистайте эти темы! Возможно именно там Вы найдете то, что искали уже давно.
Программы для скриптера
Подборка удобных программ для скриптера
- Форумы
- Языки программирования
- Delphi, Pascal, Python
- Готовые решения
Вы используете устаревший браузер. Этот и другие сайты могут отображаться в нём некорректно.
Вам необходимо обновить браузер или попробовать использовать другой.
#V9GAS
✩ Помощник ✩
SUPPORT
Пользователь
Регистрация 8 Дек 2021 Сообщения 438 Лучшие ответы 4 Репутация 130 Возраст 18 Адрес Два Лохматых, проспект бородатых
Всем привет, поделюсь с вами как создать простейший красивый эмбед одним кодом. Данный эмбед под команду «help».
Начнём к программированию.
1. Сам код команды и эмбед.
bot.remove_command('help') @bot.command() async def help(ctx): embed = discord.Embed(color = 0xff9900, title = 'Помощь') await ctx.send( embed = embed )
Параметры:
@bot.command (Команда)
embed — Эмбед.
color — Цвет эмбеда.
Поздравляю вы создали эмбед под команду «help»
Поделиться:
- Партнеры Pawno Info
- Условия и правила
- Политика конфиденциальности
- Помощь
- Главная
- RSS
О нас
«Pawno Info» — портал о программировании номер один. Начните с нами изучать эти великолепные и бесконечные виртуальные миры. Научитесь создавать функции и скрипты используя наши уроки по программированию на различных языках. Задавайте вопросы которые Вас интересуют и получайте ответы от наших профессионалов. Будьте с нами. Будьте там, где лучшее.
Наши ссылки
Статистика форума
Темы 196,729 Сообщения 1,356,036 Пользователи 110,211 Новый пользователь lebedev
Портал о программировании Pawno-Info.Ru
Copyright © Pawno Info 2010-2023. Все права защищены
Created by Giness


Уважаемый Гость.
Пожалуйста — воздержитесь от любых комментариев на форуме относительно ситуации в мире.
В личных сообщениях, в темах и где бы то не было.
Помните — это закончится в любом случае, а слова, сказанные (или написанные) Вами — не забудутся никогда.
МЫ ЗА МИР.
(Любые сообщения относительно ситуации в мире(не важно с каким смыслом) буду удаляться. А пользователи — блокироваться безвозвратно. )
Как отправить Эмбед сообщение в Discord
Обсудим все существующие способы отправки Эмбед сообщений а существует их достаточно. Быстро и понятно.
18 августа 2023, пятница 10:36
KalIvan [ ] для раздела Блоги
реклама
Всем привет други и подруги !
В этой статье мы поговорим про такой стиль сообщений Discord как эмбед. Да да я про то красивое сообщение с цветной полоской с лева.
реклама

И так я знаю всего 2 способа отправки таких сообщений:
1)Через скрипт на Python
реклама
И так преступим, для первого способа вам не понадобится каких либо трудных действий, но судите сами если у вас нет Python и вы за программирование не шарите то смотрите второй способ.
Скрипт на Python (Этот способ подойдёт для тех кто хочет создать бота для сервера и чтоб этот бот постоянно кому-то что-то кидал, а если вам на 1 раз то луч второй способ)
реклама
Для создания Эмбед сообщения можно использовать 2 библиотеки разницы нет покажу обе.
disnake
Что бы пользоваться этой библиотекой вам надо её установить разумеется как это делать если не знаете то погуглите там ничего сложного нет.
И так приступим к написанию кода.

- Импортируем библиотеку и с помощью второй строки упрощаем жизнь.
- Также прописывайте это (чтоб дать боту дефолтные разрешения )
реклама

3. Далее надо создать префикс обязательно (это такой символ с помощью которого бот понимает ,что это команда для него). В моём примере префиксом является » # » но вы можете выбрать любой свой.

4. Можно создать команду чтоб понять что код запущен и ошибок в нём нет.


5. Создаём сам эмбед.В данном случае команда называется embed а это значит чтоб вызвать эмбед в сообщениях нужно использовать эту команду #embed
title — это заголовок эмбеда
description — это описание
embed.description — также может что либо в ставить в описание.
embed.add_field — это пункты
name — имя пункта
value — что ты хочешь написать в пункте.
color=disnake.Color.from_rgb — команда для выбора цвета полосы с лева (в RGB) код цвета можно узнать в гугле ну а также есть базовые цвета в самой библиотеке к примеру вот.

ОБЯЗАТЕЛЬНО В НУТРИ НАШЕЙ ФУНКЦИИ ПРОПИСЫВАЕМ ЭТО ЧТОБ БОТ ОТПРАВИЛ СООБЩЕНИЕ ТУДА ОТ КУДА ОНО БЫЛО ВЫЗВАНО

И в конце скрипта ставим эту команду и в кавычках токен вашего бота

ВСЁ ДРУЗЬЯ БОТ ГОТОВ ЗАПУСКАЕМ СКРИПТ А СЛЕДОВАТЕЛЬНО БОТА
Выглядит примерно так по итогу.

discord.py
В плане кода вся та же дичь ток disnake меняем на discord

Эмбед будет выглядеть абсолютно так же.
Discohook (вот ссылка https://discohook.org/)
Для этого вам нужно создать вебхук на сервере


Тут на вкладке канал можно выбрать на какой канал отправится сообщение
И сразу же копируем URL вебхука

Кликаем на Clear ALL
вставляем ссылку на наш вебхук
Тыкаем ниже кнопку Add Embed
и настраиваем что хотим и заодно видим с права как будет выглядеть наш эмбед.

Когда всё настроили кликаем по кнопке Send

И всё сообщение на сервере.
Эмбед
Эмбед — особый формат сообщений. Есть миф, что их могут (без модификаций и селфботов) отправлять только боты, однако это не так. Вы уже сталкивались с эмбедами, когда делились с друзьями сайтами или видео c Youtube.
Эмбеды есть следующих типов:
| Тип | Доступен для | Описание | Пример | Настройка |
|---|---|---|---|---|
| rich | Боты, вебхуки (для пользователей только с модификациями/селфботами) | Самый красивый и многофункциональный вид эмбедов | ![]() |
Через API |
| link | Все | Появляется при отправлении ссылки без <> | ![]() |
Создателем сайта |
| video | Все | Появляется при отправлении ссылки на видео без <> | ![]() |
Создателем сайта |
- 1 Как прислать эмбед?
- 1.1 Способ для ботов (rich)
- 1.1.1 API
- 1.1.2 JavaScript
- 1.1.3 Python
- 1.1.4 Discord Bot Maker
- 1.2.1 Создаём (Генерируем) эмбед
Как прислать эмбед? [ ]
Способ для ботов (rich) [ ]
API [ ]
JavaScript [ ]
Python [ ]
Discord Bot Maker [ ]
1. Для начала нам нужно создать команду, у нас это будет тест-эмбеда-для-вики
2. Потом, нажмите «Create» и нажмите на «Send Message», потом выберите категорию «Messaging» и там выберите «Create Embed Messagse»

2.1. Вписываем заголовок эмбеда, URL, Автора, цвет, изображение. Потом пишем в «Variable Name», например, «varembed» и сохраняем.
3. Нажимаем опять кнопку «Create», выбираем ту же самую категорию и выбираем уже «Set Embed Description».
3.1. Вписываем «Variable Name», который мы написали в прошлом событии, у нас это был «varembed», вписываем.
3.2. А дальше просто пишем, что у нас будет в эмбеде, у нас это «embed test».
4. Дальше создаём ещё одно событие в команде, выбираем также «Messaging», но функцию уже выбираем «Send Embed Message».
4.1. Вписываем «Variable Name», в нашем случае это «varembed». Потом можем выбрать куда сообщение придёт и готово!
Эмбед с помощью Discord Bot Maker был создан, осталось запустить вашего бота и продемонстрировать эту команду.
BetterDiscord [ ]
В интернете можно найти плагин, который сможет отсылать эмбеды (типа link), в данном случае опишется плагин «Safe Embed Generator».
1. Скачиваем плагин по ссылке *клик*.
1.1 Перекидываем в папку с плагинами, на Windows %APPDATA%\Roaming\BetterDiscord\plugins, на Linux $HOME/.config/BetterDiscord/plugins
1.2 Подключаем его в настройках пользователя во вкладке «Plugins».
Создаём (Генерируем) эмбед [ ]
1. Нажимаем на кнопку в поле ввода сообщения.
2. Когда вы видите это, не бойтесь. Заполняйте всё как вам надо, сбоку появится превью эмбеда. Как и в Discord Bot Maker тут можно выбрать цвет, картинку, автора, заголовок.
3. Когда вы всё заполнили, можете нажимать «Send», и у вас отправится эмбед!
Send an Embed with a Discord Bot in Python

Upgrade your bot’s messages and make them a little more custom using embeds!
By Drew Seewald on November 24th, 2020

When your Discord bot responds to your server, you don’t always want a boring default message to be sent back. Maybe you have links or images that you want to send back in chat. With Python and Discord.py, this is super easy to do in your Discord bot!
Note: This is tested on version 1.4.1 of the Discord.py module. You will encounter issues if you are using a version lower than 1.0. It is recommended that you migrate your code to a more current version.
Building Embeds
Embeds in Discord are simple and have a very clean, formatted look to them. In this tutorial we will go through how to create an embed and customize every part of it.
The embed below is similar to what we will be making. It has a lot going on. There are multiple pictures, links, and text fields that we are able to edit.
You’ll know how to make this embed by the end of the tutorial!

Creating the Initial Embed
Title, Description, and color (color is the bar to the left side)

When creating an embed, you need to initialize an embed object using the Embed() function from the discord package. We will be using 4 arguments to get started:
- title: a string to set the title. This is the first line on our blank embed
- url: a string to set the link for the title. When you click on title in the final embed it will take you to this link
- description: a string to set the description. This is the darker 2 red lines above
- color: a color object. This will color the left edge of the embed.
Let’s create a new command in the bot code. Call it embed. All this command will do is build the embed and send it to the channel. In the command build the initial embed object like so:
@client.command() async def embed(ctx): embed=discord.Embed(title="Sample Embed", url="https://realdrewdata.medium.com/", description="This is an embed that will show how to build an embed and the different components", color=0xFF5733) await ctx.send(embed=embed)Start the bot. Go to the server where you joined your bot. Send the embed command we just created. Your bot will return the embed to you!

You have multiple options when it comes to colors. You can continue to look up HEX color codes with a tool like Google’s Color Picker, or you can use the built in colors inside discord.Color. To use the built in colors, you just use the classmethod of that color’s name. To turn the example blue, you would change it like this (change in bold):
@client.command() async def embed(ctx): embed=discord.Embed(title="Sample Embed", url="https://realdrewdata.medium.com/", description="This is an embed that will show how to build an embed and the different components", color=**discord.Color.blue()**) await ctx.send(embed=embed)
Now the embed is blue!
A full list of the color classmethods available for color in Discord.py are available in the documentation.
Adding an Author

The author is the text at the very top, and the icon is the circle next to that. Once we have our initial embed object, we can use the .set_author() method on it to add the information for the author. For the author, there are 3 arguments to know:
- name: a string with the author’s name
- url: a string with a link for the author text
- icon_URL: a string with the URL location of the picture to use in the author icon
In action, this will look something like this:
embed.set_author(name="RealDrewData", url="https://twitter.com/RealDrewData", icon_url="https://pbs.twimg.com/profile_images/1327036716226646017/ZuaMDdtm_400x400.jpg")Running the bot and using the command in Discord will return the embed with the author information filled in.

If you want the author name and icon to be the person who called the command, you can pull that information from the ctx, or context of the command. ctx.author.display_name will pull the username (or nickname if they have one set for the guild) of the person who used the embed command. ctx.author.avatar_url will retrieve the URL of their avatar to use in the embed (changes in bold).
embed.set_author(name=**ctx.author.display_name**, url="[https://twitter.com/RealDrewData](https://twitter.com/RealDrewData)", icon_url=**ctx.author.avatar_url**)Once the .set_author method is updated, you will see that the icon and author name are updated to match the person who called the embed function.

Thumbnails

Our next step will be to add the thumbnail. This is the image that goes at the top right of the embed. To add this, we will use the .set_thumbnail() method on our initial embed object. The .set_thumbnail() method takes a single argument that we need to know about:
- url: a string with the URL location of the picture to use for the embed picture
In action, it will look like this:
embed.set_thumbnail(url="https://i.imgur.com/axLm3p6.jpeg")Simple as that, our embed now has a thumbnail at the to right.

Adding Fields

When creating embeds, you have the ability to create a number of text fields with more information. To add these fields, we will use the .add_field() method on our embed object. There are 3 arguments that this method can take that you need to know about:
- name: a string with the title of the field
- value: a string with the body text of the field
- inline: boolean specifying whether the field is inline
Our code will look like this to add a field:
embed.add_field(name="Field 1 Title", value="This is the value for field 1. This is NOT an inline field.", inline=False)
Field 1 is not inline, meaning that it will take up the entire line of the embed. If we want to put multiple fields next to each other, we can set inline=True. This will put the next 2 fields we create on the same line. The code will look like this:
embed.add_field(name="Field 2 Title", value="It is inline with Field 3", inline=True) embed.add_field(name="Field 3 Title", value="It is inline with Field 2", inline=True)And our resulting embed has both fields on the same line.

Adding a Footer

The final part to customize on our embed is the footer. This is done by using the .set_footer() method on the embed object. This method has only 1 argument, but it is a good place to play around and use information from the ctx variable to enhance it.
- text: a string with text to display in the footer
A simple footer is added by doing something like this:
embed.set_footer(text="This is the footer. It contains text at the bottom of the embed")
We can also do some simple string formatting to customize the text with information from ctx. To have it say “Information requested by: subpar”, we can type the sentence with <> as a placeholder for the name variable. Using the .format() string method, we can replace the placeholder with ctx.author.display_name. (Changes in bold)
embed.set_footer(text=**"Information requested by: <>".format(ctx.author.display_name)**)When we request the embed now, we will see this output:

Conclusion
In this post you learned how to create an embed, adding features such as an author, thumbnail, and fields to make it look more interesting. Experiment with the different elements and get your embeds exactly how you like them.
If you are still having trouble creating your own embed, check out the visual embed creator put together by orels1. It has an easy to use interface that allows you to preview your embed and get the code to quickly implement it in your Discord bot.
Code Reference
#### Create the initial embed object #### embed=discord.Embed(title="Sample Embed", url="https://realdrewdata.medium.com/", description="This is an embed that will show how to build an embed and the different components", color=0x109319) # Add author, thumbnail, fields, and footer to the embed embed.set_author(name="RealDrewData", url="https://twitter.com/RealDrewData", icon_url="https://pbs.twimg.com/profile_images/1327036716226646017/ZuaMDdtm_400x400.jpg") embed.set_thumbnail(url="https://i.imgur.com/axLm3p6.jpeg") embed.add_field(name="Field 1 Title", value="This is the value for field 1. This is NOT an inline field.", inline=False) embed.add_field(name="Field 2 Title", value="It is inline with Field 3", inline=True) embed.add_field(name="Field 3 Title", value="It is inline with Field 2", inline=True) embed.set_footer(text="This is the footer. It contains text at the bottom of the embed") #### Useful ctx variables #### ## User's display name in the server ctx.author.display_name ## User's avatar URL ctx.author.avatar_urlКак сделать текст в EMBED discord.py?
Мне нужно добавить обычный текст в EMBED на discord.py. Я знаю, что есть emb.add_field(), но он добавляет текст в две строки, а мне нужно в одну. Как это осуществить?
- Вопрос задан более трёх лет назад
- 8698 просмотров
Комментировать
Решения вопроса 1

embed_obj = discord.Embed(description = "текст") # или embed_obj = discord.Embed() embed_obj.description = "текст"
«Шпаргалка» по виду эмбедов:

Ответ написан более трёх лет назад
Комментировать
Нравится 4 Комментировать
Эмбеды
Возможно, вы видели некоторые специальные сообщения в Discord (часто отправляемые ботами/вебхуками), которые имеют цветную рамку, встроенные изображения, текстовые поля и другие свойства. Эти элементы называются Эмбедами, и в этом разделе будет рассказано, как вы можете создать и отправить их с помощью своего бота. Это делается с помощью объекта Embed .
В этом разделе будут подробно рассмотрены атрибуты и методы, используемые в эмбедах. Таким образом, мы рекомендуем перейти к нужной вам теме через оглавление.
Предпросмотр эмбеда
Вот пример того, как может выглядеть эмбед. Мы рассмотрим конструкцию эмбеда в следующей части этой статьи.
Disnake Bot Bot 05/16/2023
Автор эмбеда
Описание эмбеда
Обычный заголовок
Обычное значение
Встроенный заголовок
Встроенное значение
Встроенный заголовок
Встроенное значение
Встроенный заголовок
Встроенное значение
Футер эмбеда • 01/01/2077
Код для этого эмбеда приведен ниже.
import disnake from disnake.ext import commands # Внутри команды, прослушивателя событий и т.д. embed = disnake.Embed( title="Заголовок эмбеда", description="Описание эмбеда", color=disnake.Colour.yellow(), timestamp=datetime.datetime.now(), ) embed.set_author( name="Автор эмбеда", url="https://disnake.dev/", icon_url="https://disnake.dev/assets/disnake-logo.png", ) embed.set_footer( text="Футер эмбеда", icon_url="https://disnake.dev/assets/disnake-logo.png", ) embed.set_thumbnail(url="https://disnake.dev/assets/disnake-logo.png") embed.set_image(url="https://disnake.dev/assets/disnake-thin-banner.png") embed.add_field(name="Обычный заголовок", value="Обычное значение", inline=False) embed.add_field(name="Встроенный заголовок", value="Встроенное значение", inline=True) embed.add_field(name="Встроенный заголовок", value="Встроенное значение", inline=True) embed.add_field(name="Встроенный заголовок", value="Встроенное значение", inline=True) await ctx.send(embed=embed)Нет строгой необходимости использовать все элементы, представленные выше. Вы можете оставить некоторые из них в соответствии с вашими потребностями.
Цвет вставки (с помощью параметра color ) принимает экземпляр Colour , шестнадцатеричная строка или целое число.
Чтобы добавить пустое поле для эмбеда, вы можете использовать embed.add_field(name=’\u200b’, value=’\u200b’) .
Создание эмбеда
Вы можете использовать Embed для создания эмбедов и манипулирования ими.
embed = disnake.Embed( title="Заголовок эмбеда", description="Описание эмбеда", colour=0xF0C43F, )Disnake Bot Bot 05/16/2023
Заголовок эмбеда
Описание эмбедаУстановка автора
Вы можете указать автора эмбеда с помощью метода set_author . Обратите внимание, что этот код запускается после того, как вы определили embed через embed = disnake.Embed(. ) .
embed.set_author( name="Автор эмбеда", url="https://disnake.dev/", icon_url="https://disnake.dev/assets/disnake-logo.png", )Disnake Bot Bot 05/16/2023
Автор эмбеда
Заголовок эмбеда
Описание эмбедаПоскольку в этом случае мы установили URL-адрес, нажатие на «Автор эмбеда» перенаправит пользователя на сайт disnake.dev .
Установка футера
Вы можете указать футер эмбеда с помощью метода set_footer . Обратите внимание, что этот код запускается после того, как вы определили embed через embed = disnake.Embed(. ) .
embed.set_footer( text="Футер эмбеда", icon_url="https://disnake.dev/assets/disnake-logo.png", )Disnake Bot Bot 05/16/2023
Автор эмбеда
Заголовок эмбеда
Описание эмбедаФутер эмбеда
Установка миниатюры
Вы можете указать миниатюру с помощью метода set_thumbnail . Обратите внимание, что этот код запускается после того, как вы определили embed через embed = disnake.Embed(. ) .
embed.set_thumbnail(url="https://disnake.dev/assets/disnake-thin-banner.png")Disnake Bot Bot 05/16/2023
Автор эмбеда
Embed Thumbnail
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 в ваш код.
import datetime # Внутри команды, прослушивателя событий и т.д. embed = disnake.Embed( title="Эмбед!", description="Описание", colour=0xF0C43F, timestamp=datetime.datetime.now(), )Disnake Bot Bot 05/16/2023
Автор эмбеда
Временные отметки
Футер эмбеда • 01/01/2077
Добавление полей
Поля эмбеда имеют два параметра — название (или заголовок) и значение внутри с помощью метода add_field . Также можно использовать markdown в обоих параметрах.
# Обычные поля embed.add_field(name="Обычный заголовок", value="Обычное значение", inline=False) # Встроенные поля embed.add_field(name="Встроенный заголовок", value="Встроенное значение", inline=True) embed.add_field(name="Встроенный заголовок", value="Встроенное значение", inline=True) embed.add_field(name="Встроенный заголовок", value="Встроенное значение", inline=True)Disnake Bot Bot 05/16/2023
Автор эмбеда
Заголовок эмбеда
Описание эмбеда
Обычный заголовок
Обычное значение
Встроенный заголовок
Встроенное значение
Встроенный заголовок
Встроенное значение
Встроенный заголовок
Встроенное значениеФутер эмбеда • 01/01/2077
Эти атрибуты также полностью поддерживают использование markdown, а также выделение ссылок. Вы также можете вставлять поля в определенную позицию с указанным индексом, используя embed.insert_field_at(index, . ) .
Добавление изображений
Это можно сделать с помощью методв set_image , который принимает либо ссылку, либо объект File .
# Используя ссылку embed.set_image(url="https://disnake.dev/assets/disnake-thin-banner.png") # Используя локальный файл embed.set_image(file=disnake.File("path/to/file.png"))Disnake Bot Bot 05/16/2023
Автор эмбеда
Изображения

Футер эмбеда • 01/01/2077
Отправка эмбеда
Как только эмбед будет создан, вам также нужно отправить его в канал. Это означает, что вам нужно вызвать метод send(embed=embed) для объекта, например объекта TextChannel (т.е. message.channel.send ) или объекта Context ( ctx.send ). В противном случае эмбед не будет отправлен.
Словарь в эмбед
Тип данных dict (и, по сути, файл json ) может быть преобразован в вложение, используя метод Embed.from_dict() . Мы можем воссоздать вставку, сделанную в начале этой страницы, используя то же самое.
embed_dict = "title": "Заголовок эмбеда", "description": "Описание эмбеда", "color": 0xFEE75C, "timestamp": datetime.datetime.now().isoformat(), "author": "name": "Автор эмбеда", "url": "https://disnake.dev/", "icon_url": "https://disnake.dev/assets/disnake-logo.png", >, "thumbnail": "url": "https://disnake.dev/assets/disnake-logo.png">, "fields": [ "name": "Обычный заголовок", "value": "Обычное значение", "inline": "false">, "name": "Встроенный заголовок", "value": "Встроенное значение", "inline": "true">, "name": "Встроенный заголовок", "value": "Встроенное значение", "inline": "true">, "name": "Встроенный заголовок", "value": "Встроенное значение", "inline": "true">, ], "image": "url": "https://disnake.dev/assets/disnake-thin-banner.png">, "footer": "text": "Футер эмбеда", "icon_url": "https://disnake.dev/assets/disnake-logo.png">, > await channel.send(embed=disnake.Embed.from_dict(embed_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 здесь.
How can I send an embed via my Discord bot, w/python?
I’ve been working a new Discord bot. I’ve learnt a few stuff,and, now, I’d like to make the things a little more custom. I’ve been trying to make the bot send embeds, instead, of a common message.
embed=discord.Embed(title="Tile", description="Desc", color=0x00ff00) embed.add_field(name="Fiel1", value="hi", inline=False) embed.add_field(name="Field2", value="hi2", inline=False) await self.bot.say(embed=embed)When executing this code, I get the error that ‘Embed’ is not a valid member of the module ‘discord’. All websites, show me this code, and I have no idea of any other way to send a embed.
1,143 11 11 silver badges 21 21 bronze badges
asked Jul 1, 2017 at 14:36
Norberto A. Norberto A.
358 2 2 gold badges 9 9 silver badges 23 23 bronze badgesThe discord.py error handling ignores errors like these, since in production a single error could cuase your whole bot to break. Hence, i recommend putting a try except block inside the function everytime you are testing, it will help alot in terms of understanding the error
Jul 7, 2021 at 2:53
6 Answers 6
To get it to work I changed your send_message line to await message.channel.send(embed=embed)
Here is a full example bit of code to show how it all fits:
@client.event async def on_message(message): if message.content.startswith('!hello'): embedVar = discord.Embed(title="Title", description="Desc", color=0x00ff00) embedVar.add_field(name="Field1", value="hi", inline=False) embedVar.add_field(name="Field2", value="hi2", inline=False) await message.channel.send(embed=embedVar)I used the discord.py docs to help find this. https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.send for the layout of the send method.
Before version 1.0: If you’re using a version before 1.0, use the method await client.send_message(message.channel, embed=embed) instead.
answered Jul 1, 2017 at 16:41
1,143 11 11 silver badges 21 21 bronze badgesSomehow now, it gives me a new error. «expected an intend block», and the arrow shows the error in the ‘d’ of the «embed = «
Jul 1, 2017 at 17:05
Make sure you haven’t by accident indented something. Check the indentation of the if statement and that line.
Jul 1, 2017 at 17:11
I’m not sure then. Sorry. Try asking in this discord server discord.gg/discord-api or you could try reporting it as a issue on the github. Also someone else seems to of had this issue so maybe monitor that post as well stackoverflow.com/questions/44474955/….
Jul 2, 2017 at 15:08
You should pick a different name for variable «embed», not sure if it can cause errors, bat anyways, embed=embed is not that clear..
Jul 2, 2020 at 13:35
@WiseMan I’ve changed it to embedVar . Do you think that name is suitably clear or have any other suggestions?
Jul 2, 2020 at 22:35
When executing this code, I get the error that ‘Embed’ is not a valid member of the module ‘discord’. All websites, show me this code, and I have no idea of any other way to send a embed.
This means you’re out of date. Use pip to update your version of the library.
pip install --upgrade discord.py45.3k 8 8 gold badges 79 79 silver badges 120 120 bronze badges
answered Jul 8, 2017 at 4:23
1,758 1 1 gold badge 18 18 silver badges 13 13 bronze badges
It says that there’s a syntax error in the install bit.
Jul 13, 2017 at 8:25
Where does it say you’re getting a syntax error? You run this command in the command line
Jul 14, 2017 at 4:36I had done this in the bot’s script, lmao. Anyways, I tried run this in the cmds thing, and it didn’t work. Let me send print. prntscr.com/fvjbff What am I doing wrong?
Jul 14, 2017 at 7:35
@Norby I’m a little late, but you haven’t added pip to path
Aug 24, 2018 at 4:12@bot.command() async def displayembed(ctx): embed = discord.Embed(title="Your title here", description="Your desc here") #,color=Hex code embed.add_field(name="Name", value="you can make as much as fields you like to") embed.set_footer(name="footer") #if you like to await ctx.send(embed=embed)169 2 2 silver badges 12 12 bronze badges
answered Mar 25, 2020 at 11:39
29 4 4 bronze badges
maybe you should point out what was wrong with the code posted in the question
Mar 25, 2020 at 11:57how about put @client.event instead of the @bot.command() it fixed everything when I put @client.event. @bot.command() does not work you can type
@client.event async def displayembed(ctx): embed = discord.Embed(title="Your title here", description="Your desc here") #,color=Hex code embed.add_field(name="Name", value="you can make as much as fields you like to") embed.set_footer(name="footer") #if you like to await ctx.send(embed=embed)2,646 4 4 gold badges 20 20 silver badges 26 26 bronze badges
answered Jan 19, 2021 at 21:16
XxCascoplaysXx XxCascoplaysXx
31 1 1 bronze badgeFor anyone coming across this in 2022:
how about put @client.event instead of the @bot.command() it fixed everything when I put @client.event. @bot.command() does not work you can type
To this ^, I don’t recommend using @client.event / @bot.event as you’d want to register your commands as a command.
If you want to simply make a command with an embed in your main.py file, make sure you have something like:
import discord from discord.ext import commands intents = discord.Itents.default() bot = commands.Bot(command_prefix='YOURPREFIX', description='description', intents=intents) @bot.command(name="embed") async def embed(ctx): embed = discord.Embed(title='Title', description='Desc', color=discord.Color.random()) embed.add_field(name="Name", value="Value", inline=False) await ctx.send(embed=embed)However, I personally like separating my commands into a /commands folder and with separate files for all of them as it’s good practice for neater code.
For that, I use cogs.
/commands/embed.py
from discord.ext import commands import discord class EmbedCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="embed") async def embed(self, ctx): embed = discord.Embed(title='Title', description='Desc', color=discord.Color.random()) embed.add_field(name="Name", value="Value", inline=False) await ctx.send(embed=embed)Then import it all into your main.py file:
from commands.embed import EmbedCog bot.add_cog(EmbedCog(bot))
- 1.1 Способ для ботов (rich)



