使用Python Requests调用Discord API加入服务器时持续返回400错误
遇到的问题
我在开发一个使用Python和Requests模块加入Discord服务器的函数时,持续收到错误码400。
我的代码
def joiner(): invite_code = input("Enter the invite code: ") with open('tokens.json', 'r') as file: tokens = json.load(file) tokens = tokens.get('token',[]) for token in tokens: headers = { "Authorization": f"{token}" } url = f"https://discord.com/api/v9/invites/{invite_code}" if "discord.gg/" in url: url = url.removeprefix('discord.gg/') response = requests.post(url, headers=headers) if response.status_code == 200: print(f"Token: {token} has successfully joined the server!") else: print(f"Failed to join the server with token: {token}. Status code: {response.status_code}")
报错信息
Failed to join the server with token: <token>. Status code: 400
(注:上述报错信息并非完全真实,我将真实token替换为了<token>)
问题分析与修复方案
1. URL处理逻辑错误
当前的URL处理完全错误:如果用户输入完整邀请链接(比如discord.gg/abc123),拼接后的URL会变成https://discord.com/api/v9/invites/discord.gg/abc123,而url.removeprefix('discord.gg/')因为目标字符串不是URL开头,根本不会生效,最终请求的URL格式错误,直接导致400。
正确做法是先处理invite_code,提取真正的邀请码:
# 处理邀请码,去掉可能的完整链接前缀 if "discord.gg/" in invite_code: invite_code = invite_code.split("discord.gg/")[-1] # 再拼接正确的API URL url = f"https://discord.com/api/v9/invites/{invite_code}"
2. 缺少必要请求头与请求体
Discord的邀请加入API要求POST请求必须携带Content-Type: application/json头,同时需要传递空的JSON请求体,否则会返回400错误。
3. 令牌格式验证
如果是用户令牌,Authorization头直接填令牌即可;如果是机器人令牌,需要加上Bot 前缀(比如"Authorization": f"Bot {token}"),请根据你的令牌类型调整。
修正后的完整代码
import requests import json def joiner(): invite_code = input("Enter the invite code: ") # 处理邀请码,提取有效部分 if "discord.gg/" in invite_code: invite_code = invite_code.split("discord.gg/")[-1] with open('tokens.json', 'r') as file: tokens = json.load(file) tokens = tokens.get('token', []) for token in tokens: headers = { "Authorization": token, # 如果是机器人令牌,改为 f"Bot {token}" "Content-Type": "application/json" } url = f"https://discord.com/api/v9/invites/{invite_code}" # 发送POST请求,携带空JSON体 response = requests.post(url, headers=headers, json={}) if response.status_code == 200: print(f"Token: {token} 成功加入服务器!") else: # 打印响应内容可排查具体错误 print(f"Token: {token} 加入失败,状态码: {response.status_code}") print("错误详情:", response.text)
额外排查建议
- 检查
tokens.json格式是否正确,需为{"token": ["token1", "token2"]}这类结构 - 如果仍报错,通过
response.text查看Discord返回的具体错误信息,比如令牌无效、邀请码过期、账号被限制等
内容的提问来源于stack exchange,提问作者pydal1
相关产品推荐
相关产品推荐

