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

VSCode开发Spotify-Discord Bot遇Node.js语法错误及相关问题求助

解决Spotify-Discord Bot运行与调试错误

一、核心错误分析与修复

1. 模块语法混用错误(Cannot use import statement outside a module)

代码同时混用了CommonJS的require和ES模块的import,Node.js默认以CommonJS模式运行,因此触发语法错误。提供两种修复方案:

方案1:统一使用CommonJS语法

将所有import语句替换为require:

const discord = require('discord.js');
const client = new discord.Client({
    intents: [discord.GatewayIntentBits.Guilds, discord.GatewayIntentBits.GuildMessages, discord.GatewayIntentBits.MessageContent]
});

const spotify = require('spotify-web-api-js');
const spotifyAPI = new spotify();

const { MessageEmbed } = require('discord.js');

方案2:将项目设为ES模块

在项目根目录的package.json中添加"type": "module",然后将所有require替换为import:

{
  "type": "module"
}

修改后的代码片段:

import discord from 'discord.js';
const client = new discord.Client({
    intents: [discord.GatewayIntentBits.Guilds, discord.GatewayIntentBits.GuildMessages, discord.GatewayIntentBits.MessageContent]
});

import spotify from 'spotify-web-api-js';
const spotifyAPI = new spotify();

import { MessageEmbed } from 'discord.js';

2. Intents相关错误(TypeError: Cannot read properties of undefined (reading 'ALL') / Valid intents must be provided for the Client)

discord.js v14及以上版本移除了Intents.ALL,必须手动指定所需的网关意图:

  • 接收消息需启用Guilds、GuildMessages、MessageContent三个意图
  • 注意:MessageContent是特权意图,需在Discord开发者门户的Bot页面手动开启

修改Client初始化代码:

// CommonJS写法
const client = new discord.Client({
    intents: [
        discord.GatewayIntentBits.Guilds,
        discord.GatewayIntentBits.GuildMessages,
        discord.GatewayIntentBits.MessageContent
    ]
});

// ES模块写法
const client = new discord.Client({
    intents: [
        discord.GatewayIntentBits.Guilds,
        discord.GatewayIntentBits.GuildMessages,
        discord.GatewayIntentBits.MessageContent
    ]
});

3. 重复声明错误(SyntaxError: Identifier 'Discord' has already been declared)

该错误源于重复声明同名变量(如多次const discord = require('discord.js'),或同时使用import discord from...和const Discord = require...)。确保每个变量仅声明一次,统一命名风格即可解决。

二、修复后的完整代码示例(CommonJS版本)

const discord = require('discord.js');
const client = new discord.Client({
    intents: [
        discord.GatewayIntentBits.Guilds,
        discord.GatewayIntentBits.GuildMessages,
        discord.GatewayIntentBits.MessageContent
    ]
});

const spotify = require('spotify-web-api-js');
const spotifyAPI = new spotify();

const { MessageEmbed } = require('discord.js');

// Spotify Credentials
spotifyAPI.setAccessToken('HIDDEN');

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', message => { // discord.js v14中message事件已更名为messageCreate
    if (message.content.startsWith('!play')) {
        let songName = message.content.split(" ").slice(1).join(" ");
        spotifyAPI.searchTracks(songName)
        .then(function(data) {
            let song = data.tracks.items[0];
            if (!song) { // 新增判断,避免找不到歌曲时触发后续报错
                return message.channel.send("Sorry, I couldn't find the song you requested.");
            }
            let songName = song.name;
            let songUrl = song.preview_url;
            let songAuthor = song.artists[0].name;
            let songEmbed = new MessageEmbed()
            .setTitle(`Playing ${songName}`)
            .setURL(songUrl)
            .setAuthor(songAuthor)
            .setColor('#0099ff');
            message.channel.send({ embeds: [songEmbed] }); // v14中发送Embed需传入embeds数组
        }, function(err) {
            console.error(err);
            message.channel.send("Sorry, I couldn't find the song you requested. Please try again with a different name or check your internet connection.");
        });
    }
});

client.login('HIDDEN');

额外注意事项

  1. 确保discord.js版本匹配:若使用v14,安装命令为npm install discord.js
  2. 特权意图开启:进入Discord开发者门户的Bot页面,在"Privileged Gateway Intents"中开启"Message Content Intent"
  3. Spotify Token有效性:硬编码的AccessToken存在有效期限制,建议通过官方授权流程动态获取Token

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:41:04