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

使用Python requests调用Discord API创建频道返回400 Bad Request求解决

问题根因

本次400错误的核心原因是请求体格式和声明的内容类型不匹配:
你在请求头中指定了Content-Type: application/json,但调用requests.post时使用了data参数传参,requests会默认将入参字典序列化为application/x-www-form-urlencoded格式的表单数据,和声明的内容类型不符,导致Discord无法正确解析请求内容。

修复方案

方案1:使用requests内置的json参数传参(推荐)

直接将data参数替换为json参数,requests会自动将字典序列化为JSON格式,同时自动添加正确的Content-Type请求头,不需要手动声明该头字段:

import requests
API_URL = "https://discord.com/api/v9"
# 替换为你实际的服务器ID、机器人令牌
guild_id = "你的服务器ID"
the_bot_token = "你的机器人令牌"
res = requests.post(
    f"{API_URL}/guilds/{guild_id}/channels",
    json={"name": "my channel name", "permission_overwrites": [], "type": 0},
    headers={"authorization": f"Bot {the_bot_token}"}
)
print(res.status_code)
print(res.text)

方案2:手动序列化JSON字符串

如果需要保留data参数的写法,需要先将入参字典手动序列化为JSON字符串:

import requests
import json
API_URL = "https://discord.com/api/v9"
# 替换为你实际的服务器ID、机器人令牌
guild_id = "你的服务器ID"
the_bot_token = "你的机器人令牌"
res = requests.post(
    f"{API_URL}/guilds/{guild_id}/channels",
    data=json.dumps({"name": "my channel name", "permission_overwrites": [], "type": 0}),
    headers={"authorization": f"Bot {the_bot_token}", "Content-Type": "application/json"}
)
print(res.status_code)
print(res.text)

额外校验项

如果修改后仍报错,请逐一核对以下内容:

  • 机器人已被邀请到对应服务器,且拥有管理频道(Manage Channels)权限
  • 传入的guild_id是合法的字符串格式服务器ID,无拼写错误
  • 机器人令牌the_bot_token正确,无多余空格、拼写错误
  • 频道名称符合Discord规范,无禁用特殊字符,长度在1-100字符之间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:36:03