You need to enable JavaScript to run this app. Node.js开发Discord机器人时,代码第14、18行报message未定义错误
优惠活动
大模型
产品
解决方案
定价
更多

Node.js开发Discord机器人时,代码第14、18行报message未定义错误

Discord.js 代码报错排查修正
  • 触发“第14行、18行message变量未定义”的核心诱因
    1. 如果你安装的是discord.js v14及以上版本,旧版的message事件已经被官方移除,替换为messageCreate事件。直接监听不存在的message事件会导致回调逻辑无法正常挂载,回调作用域内的message变量自然不会被识别,直接抛出未定义错误。
    2. 代码括号匹配错误:如果client.on('message', message => {对应的闭合大括号提前关闭,后续写在括号外的message.channel.send代码就会脱离message变量的作用域,触发未定义报错。可以逐行检查代码块的大括号缩进对齐,保证所有用到message的逻辑都在事件回调的函数体内。
  • 代码内现存的逻辑错误修正
    1. 第10行的判断逻辑完全写反:当前代码if(message.content.startsWith(prefix) ||message.author.bot) return;的含义是“只要消息带前缀、或是机器人发的消息就直接中断不处理”,完全违背前缀指令的设计逻辑,需要加上取反符号,修正为if(!message.content.startsWith(prefix) || message.author.bot) return;
    2. 第11行存在拼写错误:prefix.lenght为错误拼写,正确写法是prefix.length,拼写错误会直接打断回调代码的执行流程。
    3. 第11行的正则分割未转义特殊字符:正则表达式中+是匹配量词,直接写split(/+/)会触发语法错误,需要转义为split(/\+/)才能正确按前缀切割参数。
  • 新版本运行必需的配置补全
    如果你用的是v14及以上版本,初始化客户端时必须显式声明需要的Intents权限,否则机器人根本收不到消息事件,还要在Discord开发者后台开启Message Content Intent开关,不然就算代码写对也收不到用户发的消息内容。

以下是修正后可直接运行的参考代码

const Discord = require('discord.js');
// 新版本必须配置intents才能正常接收事件
const client = new Discord.Client({
  intents: [
    Discord.GatewayIntentBits.Guilds,
    Discord.GatewayIntentBits.GuildMessages,
    Discord.GatewayIntentBits.MessageContent
  ]
});
const prefix = '+';

client.once('ready' , () => {
    console.log('MemeStrifer is online')
});
// v14版本替换为messageCreate事件,v13及以下旧版本保留'message'事件名
client.on('messageCreate', message => {
    // 修正后的判断逻辑
    if(!message.content.startsWith(prefix) || message.author.bot) return;
    // 修正拼写、转义正则特殊字符
    const args = message.content.slice(prefix.length).split(/\+/);
    const command = args.shift().toLowerCase();

    if(command === 'blackhumour'){
        message.channel.send('What is the difference between a kid and a bowling ball? when you put your fingers in one it doesnt scream');
     } else if (command === 'sex') {
       message.channel.send('no you f***ing pervert');
     }
});

client.login('替换为你的机器人Token');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 07:12:00