请求正文包含无效的 JSON

问题描述 投票:0回答:2

我正在尝试使用 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,但结果始终相同。

python-requests discord
2个回答
0
投票

我通过更换让它工作

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

requests.post(url, json=data)

0
投票

试试这个。我认为请求库可能添加了一个名为

content-type
的标头,它与您的标头
Content-Type
冲突,这使得 Discord API 返回错误:

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, json=data)
© www.soinside.com 2019 - 2024. All rights reserved.