You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Discord机器人Node.js脚本出现'Uncaught syntax error: unexpected identifier'错误如何解决?

Troubleshooting "Unexpected Identifier" Error in Your Discord Bot Code

Hey there! Let's work through this syntax error you're facing—this is a common hiccup for new Discord bot devs, so we'll get you sorted quickly.

First, let's break down the most likely causes and fixes:

1. Check Your Node.js Version

Discord.js (especially recent versions like v14+) requires Node.js v16.9.0 or higher to support modern ES6 syntax (like arrow functions and template strings, which your code uses). If you're running an older Node version, it'll throw syntax errors like the one you're seeing.

  • Run this command in your terminal to check your version:
    node -v
    
  • If it's below v16.9.0, upgrade to the latest LTS version (v20.x is a safe bet). Most package managers (like npm or nvm) make this easy—for example, with nvm you can run nvm install --lts.

2. Verify Code & Discord.js Version Compatibility

You mentioned copying code from the official docs, but if you installed the latest Discord.js (v14) while using older v12/v13 syntax, you might run into issues (though this usually causes runtime, not syntax, errors—but it's worth checking).

The code you shared uses legacy syntax that doesn't work with v14:

  • The message event was renamed to messageCreate
  • You need to specify intents to access message content (Discord's API requires this now)

Here's the updated v14-compatible version of your code:

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

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

client.on('messageCreate', msg => {
  if (msg.content === 'ping') {
    msg.reply('Pong!');
  }
});

client.login('your-bot-token-here');

3. Check for Hidden Characters or Copy-Paste Issues

Sometimes copying code from web pages can sneak in invisible special characters that break syntax. Try these steps:

  • Delete the existing code and re-type it manually (or use a "plain text" paste option if your editor supports it)
  • Double-check that all backticks (`) around the template string are English-language, not Chinese or other characters
  • Run your code through a simple online syntax checker to spot typos or invalid characters

4. Rule Out Nodemon Issues

Occasionally nodemon can cache old code or have environment quirks. Try running your bot directly with Node to see if the error persists:

node index.js

If this works but nodemon doesn't, try restarting nodemon or clearing its cache with nodemon --clean index.js.


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

火山引擎 最新活动