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

如何修复Discord OAuth2 guild.join scope添加用户进服务器的400错误

问题:Discord OAuth2授权后自动加入服务器时返回400错误

我正在开发一款Discord应用,希望通过Discord OAuth2 API让用户授权后自动加入指定服务器。以下是我的Flask代码,但add_user_to_server函数总是返回400错误,Flask应用本身除了favicon的404外无其他异常,多次调试仅得到400状态码,无法定位具体问题:

from flask import Flask, request
import requests
import json

app = Flask(__name__)

def add_user_to_server(token: str, user_id: str, server_id: str) -> bool:
    url = f'https://discordapp.com/api/v8/guilds/{server_id}/members/{user_id}'
    headers = {
        'Authorization': f'Bot {token}'
    }
    response = requests.put(url, headers=headers)
    if response.status_code == 201:
        print(f'User {user_id} added to server with ID {server_id}')
        return True
    else:
        print(f'Error adding user {user_id} to server with ID {server_id}')
        return False

# The callback URL for OAuth2 authorization
@app.route('/auth/callback')
def callback():
    code = request.args.get('code')

    # Exchange the authorization code for an access token
    url = 'https://discord.com/api/oauth2/token'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    data = {
        'client_id': '',
        'client_secret': '',
        'grant_type': 'authorization_code',
        'code': code,
        'redirect_uri': 'http://127.0.0.1:5000/auth/callback',
        'scope': 'identify guilds.join'
    }
    response = requests.post(url, headers=headers, data=data).json()
    access_token = response['access_token']

    # Get the user ID from the access token
    url = 'https://discord.com/api/users/@me'
    headers = {
        'Authorization': f'Bearer {access_token}'
    }
    response = requests.get(url, headers=headers).json()
    user_id = response['id']

    # Add the user to the server
    invite_code = '1075365992399650836'
    bot_token = 'sike'
    add_user_to_server(bot_token, user_id, invite_code)

    return 'Successfuly authorised with Discord, you may now close this window.'

if __name__ == '__main__':
    app.run(debug=True)

错误排查与修复方案

1. 缺少必填请求体参数

Discord的PUT /guilds/{guild_id}/members/{user_id} API要求必须在请求体中传入用户的OAuth2 access_token,否则直接返回400错误。你的代码仅发送了请求头,未包含该核心参数。

修改add_user_to_server函数,补充请求体及必要头信息:

def add_user_to_server(bot_token: str, user_id: str, server_id: str, user_access_token: str) -> bool:
    url = f'https://discord.com/api/v10/guilds/{server_id}/members/{user_id}'
    headers = {
        'Authorization': f'Bot {bot_token}',
        'Content-Type': 'application/json'
    }
    # 必须传入用户授权后获取的access_token
    data = {
        'access_token': user_access_token
    }
    response = requests.put(url, headers=headers, json=data)
    # 打印错误详情,便于调试
    if response.status_code == 201:
        print(f'用户 {user_id} 已成功加入服务器 {server_id}')
        return True
    else:
        print(f'添加用户失败,状态码: {response.status_code},错误信息: {response.text}')
        return False

2. API版本过时

你使用的v8版本Discord API已停止维护,需升级到当前稳定的v10版本,同时将域名从discordapp.com改为discord.com,避免兼容性问题。

3. 变量名混淆与参数传递错误

代码中错误地将服务器ID存放在invite_code变量中,易造成混淆;同时调用add_user_to_server时需传入用户的access_token。修改回调函数中的调用逻辑:

# 替换为你的真实服务器ID
server_id = '1075365992399650836'
bot_token = '你的真实Bot Token'
# 传入用户授权后获取的access_token
add_user_to_server(bot_token, user_id, server_id, access_token)

4. Bot权限与服务器配置检查

  • 确保Bot已加入目标服务器,且拥有MANAGE_GUILD(管理服务器)权限;
  • 确认目标服务器成员数量未达上限;
  • 验证Bot Token有效,未过期或被撤销权限。

5. 完善错误调试逻辑

在错误分支中打印response.text,Discord API会返回具体错误原因(如参数缺失、权限不足等),帮助快速定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:52:41