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

Node.js Discord Bot(discord.js)else语句异常触发问题求助

问题分析与修复方案

你的代码出现这个问题有两个核心原因:

  1. 频道判断逻辑错误:你直接把message.channel(这是一个Channel对象)和字符串'aim-reception'做相等比较,这永远不会成立——对象和字符串在JavaScript里不可能相等,所以无论你在哪个频道发命令,都会直接进入else分支。
  2. 未过滤机器人自身消息:当机器人发送Please Use the channel #aim-reception这条提示时,会再次触发message事件,导致无限循环发送提示。

修复后的完整代码

const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();

// Create an event listener for new guild members
client.on('guildMemberAdd', member => {
 // Send the message to a designated channel on a server:
 const channel = member.guild.channels.find(ch => ch.name === 'member-log');
 // Do nothing if the channel wasn't found on this server
 if (!channel) return;
 // Send the message, mentioning the member
 channel.send(`Welcome to the server, ${member}`);
});

client.on('message', message => {
 // 首先忽略机器人自己发送的消息,避免无限循环
 if (message.author.bot) return;

 // 正确判断频道名称:比较channel对象的name属性
 if (message.channel.name === 'aim-reception') {
  if (message.content.startsWith(`${prefix}hi`)) {
   console.log(`${message.author} used the "${prefix}hi" command in channel ${message.channel.name}`);
   message.channel.send(`Hello ${message.author}!`);
  }
 } else {
  // 只有当用户发送指定命令时才提示,避免普通消息也触发提示
  if (message.content.startsWith(`${prefix}hi`)) {
    message.channel.send('Please Use the channel #aim-reception');
  }
 }
});

client.once('ready', () => {
 console.log('Bot is now connected');
});

client.login(token);

关键修改说明

  • 修正频道判断:将message.channel === 'aim-reception'改为message.channel.name === 'aim-reception',这样才是在比较频道的名称字符串。
  • 添加机器人消息过滤:增加if (message.author.bot) return;,确保机器人不会响应自己发送的消息,彻底解决无限循环问题。
  • 优化提示触发逻辑:在else分支里增加了对命令的判断,只有当用户在错误频道发送${prefix}hi命令时才提示,避免用户发普通消息也被打扰。

另外,如果你担心频道名称可能被修改,也可以改用频道ID来判断(message.channel.id === '你的频道ID'),这样更稳定,因为ID不会随名称变化而改变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:59:20