基于Discord API的自定义API请求头部错误问题求助
问题排查与修复方案
1. 清理Embed中的空值字段
你的to_discord_embed方法会将所有可选字段(即使为None)都加入Embed结构,但Discord API不接受包含null值的字段,这可能导致请求被判定为格式错误,进而触发类似头部错误的提示。
修改to_discord_embed方法,过滤掉值为None的字段:
def to_discord_embed(self): embed = {} if self.title is not None: embed["title"] = self.title if self.description is not None: embed["description"] = self.description if self.url is not None: embed["url"] = self.url if self.timestamp is not None: embed["timestamp"] = self.timestamp if self.color is not None: embed["color"] = self.color # 仅当footer有有效字段时添加 footer = {} if self.footer_text is not None: footer["text"] = self.footer_text if self.footer_icon is not None: footer["icon_url"] = self.footer_icon if footer: embed["footer"] = footer # 仅当author有有效字段时添加 author = {} if self.author_text is not None: author["name"] = self.author_text if self.author_icon is not None: author["icon_url"] = self.author_icon if author: embed["author"] = author if self.image_url is not None: embed["image"] = {"url": self.image_url} if self.thumbnail_url is not None: embed["thumbnail"] = {"url": self.thumbnail_url} return {"embeds": [embed]}
2. 升级Discord API版本
当前代码使用的v9版本已被官方弃用,可能导致请求被拒绝。将API URL中的v9替换为v10:
discord_api_url = f"https://discord.com/api/v10/channels/{channel_id}/messages"
3. 严格校验Authorization头部
确保:
- Bot令牌未过期或被重置(前往Discord开发者后台确认状态)
- 调用API时,
Authorization头部格式严格为Bot YOUR_TOKEN_HERE(注意Bot后有一个空格) - 令牌前后无多余空格或特殊字符
4. 修正Required字段模型定义
description字段标注为必填,但默认值设为None,会导致FastAPI允许该字段为空,而Discord API要求Embed必须包含核心内容。修正模型:
description: str = Field(..., description="Required - Description of the embed")
将None改为...,强制校验该字段不为空。
5. 检查Bot与频道权限
- 确认Bot在目标频道拥有发送消息和嵌入链接的权限
- 检查频道是否启用消息审核、是否限制Bot的发送权限
内容的提问来源于stack exchange,提问作者xKing28
相关产品推荐
相关产品推荐

