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

Discord机器人JS代码报错‘Declaration or statement expected’求排查修复

Fixing the "Declaration or statement expected" Error in Your Discord.js Bot

Hey there! That syntax error is caused by a missing closing curly brace in your message event handler. Let's break down the issue and fix it step by step.

The Root Cause

In your message event callback, the if (message.content == "hello") block doesn't have a closing }. This throws off the JavaScript parser, which expects a proper declaration or statement after the incomplete block—hence the "Declaration or statement expected" error.

Fixed Code

const Discord = require("discord.js");
const TOKEN = "BEEP";
const PREFIX = "$$";
var bot = new Discord.Client();

bot.on("ready", function() {
    console.log("ThunderBird is a go");
    bot.user.setPresence({ game: { name: "Choccy Milk", type: 0 } });
});

bot.on("message", function(message) {
    // Ignore messages from the bot itself
    if (message.author.equals(bot.user)) return;

    // Respond to "hello"
    if (message.content == "hello") { 
        message.channel.send("Hi, how are you!");
    } // <-- This closing brace was missing

    // Ignore messages that don't start with the prefix
    if (!message.content.startsWith(PREFIX)) return;

    var args = message.content.substring(PREFIX.length).split(" ");
    switch (args[0]) {
        case "ping": 
            message.channel.send("Pong!"); 
            break;
    }
});

bot.login(TOKEN);

Key Fixes Explained

  • Added the missing } to close the if (message.content == "hello") block, restoring proper code structure.
  • Cleaned up indentation to make the code's logical flow easier to read (this helps catch missing braces in the future!).

Quick Bonus Tip

For better practice, consider using strict equality (===) instead of loose equality (==) when comparing strings, like:

if (message.content === "hello") { ... }

This avoids unexpected type coercion issues down the line.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:49:42