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

使用Guilds.Join权限实现用户自动加入Discord服务器遇401错误

问题描述

我拥有一个网站,当用户通过OAuth2链接完成授权后,已获取用户密钥,想要让该用户加入Discord支持服务器。尝试多种方式后始终返回{"message": "401: Unauthorized", "code": 0}错误。我确认OAuth2代码可用,且执行添加操作的Bot已加入目标服务器。

相关Python代码

async def join_server(user_token: str, guild_id: int):
    headers = {
        'Authorization': f'Bot {user_token}'
    }

    try:
        response = requests.put(f'https://discord.com/api/v10/guilds/{guild_id}/members/@me', headers=headers) # 我也尝试把@me换成用户ID,但没用
        print(response.status_code)
        print(response.text)  # 打印响应内容
        return response.status_code
    except requests.exceptions.RequestException as e:
        print(f"发生错误: {e}")
        return 500  # 返回错误状态码    
问题分析与解决方案

核心错误点

  1. 授权凭证误用:你把用户的OAuth2 token当成Bot token传入请求头的Bot {user_token}字段,这里必须使用Discord Bot专属的token,而非用户授权得到的token。
  2. API端点选择错误:/guilds/{guild_id}/members/@me是用户主动加入服务器的接口,仅能使用用户自身的token(不带Bot前缀),无法实现Bot主动拉人操作。
  3. 缺少必要权限与参数:Bot拉人需要特定权限,且必须在请求体中携带用户的OAuth2 access token。

修正步骤

  1. 配置Bot权限与意图:

    • 给Bot分配MANAGE_GUILD和CREATE_INSTANT_INVITE权限
    • 在Discord开发者门户的Bot页面开启服务器成员意图(Server Members Intent)
  2. 使用正确的API调用方式:
    调用/guilds/{guild_id}/members/{user_id}接口,用Bot token做授权,请求体中传入用户的OAuth2 access token。同时异步函数中建议使用aiohttp替代同步的requests,避免阻塞。

修正后的代码

import aiohttp

async def join_server(bot_token: str, user_token: str, guild_id: int, user_id: int):
    headers = {
        'Authorization': f'Bot {bot_token}',
        'Content-Type': 'application/json'
    }
    payload = {
        'access_token': user_token
    }

    try:
        async with aiohttp.ClientSession() as session:
            async with session.put(
                f'https://discord.com/api/v10/guilds/{guild_id}/members/{user_id}',
                headers=headers,
                json=payload
            ) as response:
                print(response.status)
                print(await response.text())
                return response.status
    except aiohttp.ClientError as e:
        print(f"发生错误: {e}")
        return 500

额外注意

  • 确保Bot已加入目标服务器
  • 用户的OAuth2授权必须包含guilds.join scope,否则无法通过Bot完成拉人
  • 定期检查Bot token和用户token的有效性,避免过期导致的授权失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 04:56:26