[PYTHON] How to embed multiple embeds in one message with Discord.py

At first

The content explained in this article is not particularly difficult, so it is a fairly simple explanation. Please note. We will use Webhooks this time, but I think that even people who are not familiar with how to use Webhooks can understand it. However, it does not explain how to create a webhook or how to get a link, so please see other articles.

Development environment

・ Editor --Atom · Execution shell-PlatformIO IDE Terminal (Atom extension) | It's just a command prompt. · Python --Python 3.9.1 ・ Discord.py --discord.py 1.5.1.

The main subject from here

All chords

import discord
from discord.ext import commands
import requests
import json

bot = commands.Bot(command_prefix='!')

TOKEN = ''

webhook_url = ''

main_content = {
    "username": "Webhooks username",
    "avatar_url": "https://1.bp.blogspot.com/-d3vDLBoPktU/WvQHWMBRhII/AAAAAAABL6E/Grg-XGzr9jEODAxkRcbqIXu-mFA9gTp3wCLcBGAs/s400/internet_404_page_not_found.png ",
    "content": "Webhooks content",

    "embeds": [
        {
            "title": "first embeds title",
            "description": "first embeds description",
            "color": 0x00ffff,
        },
        {
            "title": "second embeds title",
            "description": "second embeds description",
            "color": 0xff0000,
        }
    ]
}


@bot.event
async def on_ready():
    print('ready')


@bot.command()
async def test(ctx):
    requests.post(webhook_url, json.dumps(main_content), headers={'Content-Type': 'application/json'})
    return


bot.run(TOKEN)

Commentary

Module import

import discord
from discord.ext import commands
import requests
import json

From above,

・ Modules essential for developing Discord.py -Modules that are essential for using the command framework -Module for sending webhooks -Module used to recognize that part of the code is written in a json file

is.

Variable definition

TOKEN = ''

webhook_url = ''

main_content = {
    "username": "Webhooks username",
    "avatar_url": "https://1.bp.blogspot.com/-d3vDLBoPktU/WvQHWMBRhII/AAAAAAABL6E/Grg-XGzr9jEODAxkRcbqIXu-mFA9gTp3wCLcBGAs/s400/internet_404_page_not_found.png ",
    "content": "Webhooks content",

    "embeds": [
        {
            "title": "first embeds title",
            "description": "first embeds description",
            "color": 0x00ffff,
        },
        {
            "title": "second embeds title",
            "description": "second embeds description",
            "color": 0xff0000,
        }
    ]
}

I will not explain about TOKEN because it is a matter of course. (~~ I can't say it's just annoying ~~)

・ Webhook_url --URL of the webhook to use -Main_content --Information about the webhook to send

About webhook_url

For the time being

ch_webhooks = await message.channel.webhooks()
webhook = discord.utils.get(ch_webhooks, name='test')
webhook_url = webhook.token

But you can get it.

About main_content

I will explain in detail the main_content variable, which can be said to be the most important in this code. Depending on the person, it may be understandable at a glance, but for the time being.

username --The username to use when sending webhooks. avatar_url --The URL of the icon to use when sending a webhook. content --What to fill in the webhook.

And embeds, which is an element for sending multiple Embeds. By the way, if you only need to use Embed, you don't need the above three.

As you can see, embeds is a plural, that is, a list (array) type. So there is a [ after the colon. (It was annoying to look up the official name)

What is different from this Embed definition method and the normal d.py Embed definition method is that, for example, title ='title' was changed to"title": "title". It's just that. After that, there is a {} to represent it as one unit, and that's it. Example: ↓

discord.Embed(title='title', description='description', color=0x00ffff, url='url').set_author(name='author_name', url='author_url', icon_url='author_icon_url')

#But,
{
    "embeds":[{
        "title": "title",
        "description": "description",
        "color": 0x00ffff,
        "url": "url",
        "author":{
            "name": "author_name",
            "url": "author_url",
            "icon_url": "author_icon_url"
        }
    }]
}

#Just become.

By the way, if you don't have to comply with PEP8, you don't have to think about indentation.

So, when using multiple Embeds, it looks like this

{
    "embeds":[
    {
        "title": "title",
        "description": "description",
        "color": 0x00ffff,
        "url": "url",
        "author":{
            "name": "author_name",
            "url": "author_url",
            "icon_url": "author_icon_url"
        }
    },
    {
        "title": "title",
        "description": "description",
        "color": 0x00ffff,
        "url": "url",
        "author":{
            "name": "author_name",
            "url": "author_url",
            "icon_url": "author_icon_url"
    }
    ]
}

Separate them with commas and incorporate two or more elements. Rumor has it that up to 10 Embeds can be embedded. I haven't tried it. If anyone has verified it, I would be grateful if you could let me know in the comments.

on_ready

@bot.event
async def on_ready():
    print('ready')

Needless to say, all you have to do is check if the bot has started successfully. I don't need a detailed explanation.

Send Embed

@bot.command()
async def test(ctx):
    requests.post(webhook_url, json.dumps(main_content), headers={'Content-Type': 'application/json'})
    return

For the time being, the command test is used here, but of course you can do other than that.

Now, let's take a look inside requests.post.

webhook_url --URL of the webhook defined (acquired) above main_content --The one that is packed with the information of the Webhook message defined above (json.dumps () is the one to convert to json format. Required.) headers-I don't really understand this either. However, it will not be sent successfully without this. The one that should be written for the time being.

Yes, the explanation is over. It was easy, wasn't it?

Referenced articles

Use discord webhook in python requests post

Recommended Posts

How to embed multiple embeds in one message with Discord.py
How to do zero-padding in one line with OpenCV
How to adapt multiple machine learning libraries in one shot
How to check ORM behavior in one file with django
How to convert 0.5 to 1056964608 in one shot
Two ways to display multiple graphs in one image with matplotlib
How to display legend marks in one with Python 2D plot
How to calculate "xx time" in one shot with Python timedelta
How to title multiple figures with matplotlib
How to work with BigQuery in Python
How to deal with memory leaks in matplotlib.pyplot
How to send a message to LINE with curl
[REAPER] How to play with Reascript in Python
How to embed a variable in a python string
Save multiple models in one form with Django
[Python] How to draw multiple graphs with Matplotlib
How to deal with run-time errors in subprocess.call
Easily log in to AWS with multiple accounts
How to use tkinter with python in pyenv
How to return multiple indexes with index method
How to drop Google Docs in one folder in a .txt file with python
How to convert / restore a string with [] in python
How to get multiple model objects randomly in Django
How to write string concatenation in multiple lines in Python
How to do hash calculation with salt in Python
How to define Decorator and Decomaker in one function
Explain in detail how to make sounds with python
How to deal with pyenv initialization failure in fish 3.1.0
How to run tests in bulk with Python unittest
How to load files in Google Drive with Google Colaboratory
How to access with cache when reading_json in pandas
How to display multiple images of galaxies in tiles
How to retrieve multiple arrays using slice in python.
How to deal with Executing transaction: failed in Anaconda
Summary of how to share state with multiple functions
How to start the code written in Atom with one command without starting teminal
How to install NPI + send a message to line with python
[TensorFlow 2 / Keras] How to run learning with CTC Loss in Keras
How to slice a block multiple array from a multiple array in Python
How to output a document in pdf format with Sphinx
How to extract any appointment in Google Calendar with Python
How to register the same data multiple times with one input on the Django management screen
[Python] How to write an if statement in one sentence.
How to define multiple variables in a python for statement
How to update with SQLAlchemy?
[Django] How to give input values in advance with ModelForm
How to manipulate the DOM in an iframe with Selenium
How to cast with Theano
[AWS] How to deal with "Invalid codepoint" error in CloudSearch
How to write type hints for variables that are assigned multiple times in one line
How to Alter with SQLAlchemy?
For beginners, how to deal with common errors in keras
How to separate strings with','
How to RDP with Fedora31
How to develop in Python
How to create dataframes and mess with elements in pandas
How to turn the for statement when there are multiple values for one key in the dictionary
Try HeloWorld in your own language (with How to & code)
I wanted to delete multiple objects in s3 with boto3
How to Delete with SQLAlchemy?
How to log in to AtCoder with Python and submit automatically