You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用requests模块在Discord.py中发送Embed?代码报错求解决

问题分析与解决方法

你的代码存在三个核心问题:

  • 语法错误:字典data内部使用=赋值,Python字典的键值对必须用:分隔。
  • 对象类型不匹配:直接把discord.Embed实例塞进字典,requests.post的json参数只接受可序列化为JSON的原生Python类型(如字典、列表),不支持discord.py的自定义对象。
  • Webhook格式错误:Discord Webhook要求Embed内容放在embeds数组中,而非单个embed字段。

修正后的代码

import discord
from discord.ext import commands
import requests

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.command()
async def ping(ctx):
    await ctx.send(f"pong <@{ctx.author.id}>!")
    url = "你的Webhook URL"
    
    # 手动构造符合Discord规范的Embed字典
    embed_data = {
        "title": "test",
        "description": "test",
        "color": discord.Colour.blue().value  # 转换为Discord要求的十进制颜色值
    }
    
    # Webhook请求体必须将Embed放入embeds数组
    data = {
        "embeds": [embed_data]
    }
    
    # 发送请求并打印响应信息用于排查
    response = requests.post(url, json=data)
    print(response.status_code)  # 204表示请求成功
    print(response.text)

bot.run("你的Bot Token")

关键说明

  1. 颜色值处理:discord.Colour.blue().value会将颜色对象转换为Discord要求的十进制整数,直接用Colour对象会导致序列化失败。
  2. 数组格式要求:即使只发送一个Embed,也要放在embeds数组里,这是Discord Webhook的强制格式。
  3. 错误排查:打印response.status_code和response.text可以快速定位问题,比如400代表请求格式错误,401代表Webhook URL无效。

内容的提问来源于stack exchange,提问作者Javian Thor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:05:15