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

使用Discord.js与REST添加斜杠命令时遇Unexpected token '?'错误求助

解决Discord.js + @discordjs/rest 中的 Unexpected token '?' 错误

问题描述

尝试使用Discord.js与@discordjs/rest为Discord机器人添加斜杠命令时,运行代码始终在REST模块中触发SyntaxError: Unexpected token '?'错误。

运行代码

const { SlashCommandBuilder, Routes } = require('discord.js');
const { REST } = require('@discordjs/rest');
var clientId = //myClientId
var guildId = //myGuildId

const commands = [
    new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!')
]
    commands.map(command => command.toJSON());

const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);

(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

        await rest.put(
        Routes.applicationCommands(clientId),
        { body: commands },
    );

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();

报错信息

/home/runner/TinkerTank/node_modules/@discordjs/rest/dist/lib/CDN.cjs:53
      extension: extension ?? "png"
                            ^

SyntaxError: Unexpected token '?'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/runner/TinkerTank/node_modules/@discordjs/rest/dist/index.cjs:5:13)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)

错误原因

  1. Node.js版本过低:报错中的??是空值合并运算符,该语法仅支持Node.js 14.0.0及以上版本,当前环境Node版本不足导致无法识别该语法。
  2. 代码逻辑问题:commands.map(command => command.toJSON())未将转换后的JSON数组赋值给变量,导致后续上传的是原始SlashCommandBuilder实例数组,而非Discord API要求的JSON格式数据。

解决步骤

1. 升级Node.js版本

  • 执行node -v检查当前版本,若低于14.0.0需升级:
    • 使用nvm(Node版本管理器):nvm install 18,之后执行nvm use 18切换到LTS版本
    • 直接从Node.js官方渠道下载对应版本安装包覆盖安装

2. 修复代码中的数组转换问题

修改命令数组处理逻辑,确保map转换后的JSON数组被正确赋值:

// 方式一:链式调用直接赋值
const commands = [
    new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!')
].map(command => command.toJSON());

// 方式二:拆分逻辑更清晰
const commandBuilders = [
    new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!')
];
const commands = commandBuilders.map(command => command.toJSON());

3. 重新运行代码

完成版本升级和代码修复后,再次执行部署脚本即可正常注册斜杠命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:33:34