【问题标题】:The request body contains invalid JSON请求正文包含无效的 JSON
【发布时间】:2022-01-04 22:21:15
【问题描述】:

我正在尝试使用 Python 请求 POST 到不和谐的 webhook URL,但是只要存在 embeds 字段,它就会返回 {'code': 50109, 'message': 'The request body contains invalid JSON.'}。如果我删除embeds 并留下content,它将发送而不会出现任何错误。

我的代码是:

url = "https://discord.com/api/webhooks/[redacted]/[redacted]"

headers = {
    "Content-Type": "application/json"
}

data = {
  "username": "Webhook",
  "content": "Hello, World!",
  "embeds": [{
    "title": "Hello, Embed!",
    "description": "This is an embedded message."
  }]
}

res = requests.post(url, headers=headers, data=data)

我尝试了不同版本的 Discord API,但结果始终相同。

【问题讨论】:

  • 我通过/usr/bin/jq 运行了您的数据元素,并且解析正确。您注意到,如果您不包含 embeds 元素,那么请求就可以了。这意味着您的 embeds 元素的格式是不和谐的。我建议尝试 (1) 将 embeds 元素内容全部放在 1 行,以及 (2) 像 /usr/bin/jq 那样对其进行格式化并直接传递 - 包括额外的空格+换行符。
  • @James McPherson 我尝试了您的两个建议,但仍然返回相同的错误。
  • 我建议重新检查您尝试使用的特定 webhook 的 API 文档,并确认您的有效负载数据包含接收方期望的元素。

标签: python-requests discord


【解决方案1】:

我通过替换让它工作了

requests.post(url, headers=headers, data=data)

requests.post(url, json=data)

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2021-04-08
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多