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

Discord.js Bot加载RPC时出现connection closed错误求助

问题分析与解决方案

核心错误

你混淆了Bot账号状态设置和用户端Rich Presence的实现逻辑:

  • discord-rpc是给桌面应用(如游戏、工具)做用户账号Rich Presence用的,依赖本地Discord客户端的IPC连接;而Bot账号是通过Discord网关远程连接的,根本用不了这个库的IPC传输,这就是你触发connection closed错误的直接原因。
  • Bot账号的在线活动状态,直接用discord.js自带的API就能实现,不需要额外引入discord-rpc。

代码里的具体问题

  1. 语法错误:声明RPC.Client后直接写intents配置块,这部分属于discord.js的Client配置,位置完全错误。
  2. 变量名混乱:setActivity函数里用了未定义的rpc变量,你实际声明的是client(而且还是RPC的Client,不是discord.js的Bot客户端)。
  3. 登录逻辑错误:RPC.Client的登录参数格式不对,且Bot的登录必须用discord.js的Client实例,而非RPC的Client。
  4. 参数格式错误:WOKCommands的testServers和botOwners要求传入数组,你传了单个字符串。

修正后的代码

const { Client, GatewayIntentBits } = require("discord.js");
const WOK = require('wokcommands');
const path = require('path');
const dotenv = require("dotenv");

dotenv.config();

// 创建正确的discord.js Bot客户端,配置合法的intents
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.GuildPresences,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers,
    ],
});

// 设置Bot的在线活动状态
function setActivity() {
    client.user.setActivity({
        details: 'Text Based Roleplay',
        state: 'Playing Grand Theft Auto: RP',
        startTimestamp: Date.now(), // 用当前时间作为开始时间,或替换为数字类型的目标时间戳
        largeImageKey: 'rpc_icon', // 需在Discord开发者面板的Rich Presence-Art Assets中上传并命名该图片
        largeImageText: 'Carl Johnson',
        buttons: [
            { label: 'YouTube', url: 'https://www.youtube.com' },
            { label: 'Google', url: 'https://www.google.ca' }
        ]
    });
}

client.on('ready', (c) => {
    console.log(` ${c.user.tag} is Online!`);
    setActivity();

    // 初始化WOKCommands,修正参数格式
    new WOK({
        client, 
        commandsDir: path.join(__dirname, 'commands'),
        featuresDir: path.join(__dirname, 'features'),
        testServers: ['1087164983055499315'],
        botOwners: ['1071740521497763900'],
    });
});

// 用Bot专属Token登录
client.login(process.env.TOKEN);

关键修改说明

  1. 移除discord-rpc依赖,改用discord.js原生的client.user.setActivity方法实现Bot状态展示。
  2. 修正discord.js Client的声明语法,将intents配置放入正确的位置。
  3. 调整WOKCommands的testServers和botOwners为数组格式,符合库的参数要求。
  4. 修正startTimestamp格式:必须传入数字类型的时间戳,而非字符串。
  5. 注意:largeImageKey对应的图片需要在Discord开发者面板中,进入Bot所属应用的Rich Presence > Art Assets页面上传并命名为rpc_icon,否则无法正常显示。

内容的提问来源于stack exchange,提问作者Peter Cloutier-Jabalee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:34:57