如何使用discord.py发送内嵌JSON的Discord embed富文本消息
解决方案
discord.py 内置了 Embed.from_dict() 方法,可以直接将你生成的JSON格式Embed配置转换为可直接发送的Embed对象,不需要手动逐个配置字段,具体实现代码如下:
直接嵌入JSON配置的示例代码
import discord from discord.ext import commands # 初始化机器人,注意开启对应intents权限 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents) @bot.command(name='安装指南') async def send_install_guide(ctx): # 填入你生成的完整JSON配置 msg_config = { "username": "", "avatar_url": "", "content": "@here", "embeds": [ { "title": "__Installation and Start-Up__", "color": 16514816, "description": "1. Install [vcredist](https://aka.ms/vs/16/release/vc_redist.x64.exe)\n2. Turn your antivirus on and add `Disturbed.exe` and the folder it's in to your antivirus or Windows Defender exceptions.\n3. Make sure background programs such as RAM cleaners (MSI Afterburner & CCleaner) don't interfere with the injection process.\n4. Make sure your GTA V is on the latest version.\n5. Run the game and start the injector. Wait for the game to fully load offline/online, then inject.", "timestamp": "", "url": "", "author": { "url": "" }, "image": { "url": "" }, "thumbnail": { "url": "" }, "footer": { "text": "", "icon_url": "" }, "fields": [] } ], "components": [] } # 转换JSON配置为Embed对象 target_embed = discord.Embed.from_dict(msg_config['embeds'][0]) # 发送消息,同时携带@here内容和富文本 await ctx.send(content=msg_config['content'], embed=target_embed) # 启动机器人 bot.run('你的机器人Token')
可选:从单独JSON文件读取配置
如果你把配置存为了单独的embed_config.json文件,可以用以下代码读取,不用硬编码到Python脚本里:
import json with open('embed_config.json', 'r', encoding='utf-8') as f: msg_config = json.load(f)
注意事项
- 配置中的空值字段不需要手动删除,discord.py会自动忽略无内容的配置项
- 如果需要同时发送多个Embed,最多支持同时发送10个,把所有Embed配置都转换为对象后传入
embeds参数即可:await ctx.send(content=msg_config['content'], embeds=[discord.Embed.from_dict(item) for item in msg_config['embeds']]) - 注意开启机器人的消息内容读取权限,否则无法响应命令调用
内容的提问来源于stack exchange,提问作者noname13321312312
相关产品推荐
相关产品推荐

