提问者:小点点

如何在discord bot中突破节点js中的else语句


我正在使用discord.JS模块在节点JS中创建一个discord bot,并且我希望仅当用户在discord服务器上的特定预定义通道中发送特定文本命令时才发送预定义消息,否则,如果用户在任何其他通道中发送命令,则向同一通道发送消息,通知用户使用预定义通道来执行命令。例如。

据我所知,带有bug的代码是:

client.on('message', message => {

    //Check message channel
    if (message.channel === 'aim-reception') {

        if (message.content.startsWith(`${prefix}hi`)) {
            console.log(`${message.author} used the "!hi" command in channel ${message.channel}`);
            message.channel.send(`Hello ${message.author}!`);
        }
    } else return message.channel.send('Please Use the channel #aim-reception');
});

下面是index.js文件的完整代码:

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 => {

    //Check message channel
    if (message.channel === 'aim-reception') {

        if (message.content.startsWith(`${prefix}hi`)) {
            console.log(`${message.author} used the "!hi" command in channel ${message.channel}`);
            message.channel.send(`Hello ${message.author}!`);
        }
    } else return message.channel.send('Please Use the channel #aim-reception');
});

/**
 * The ready event is vital, it means that only _after_ this 
 * will your bot start reacting to information
 * received from Discord
 */
client.once('ready', () => {
    console.log('Bot is now connected');

});

client.login(token);

即使使用的通道是正确的,它仍然跳过if条件,并且无限期地循环else语句。

discord服务器中错误的快照


共2个答案

匿名用户

1.使用文档中的通道属性,您将看到TextChannel对象具有TextChannel.name属性。

当您比较message.channel==='aim-receiver'时,您将对象与字符串进行比较,字符串将始终返回false。请改用message.channel.name==='aim-receiver'

2.忽略bot消息,或者至少忽略你的bot自己的消息

message事件将触发任何消息,包括您的bot自己的消息,因此请尝试忽略所有bot消息,或者至少忽略它们自己的消息。否则,机器人就会反复回复自己的消息。

client.on('message', message => {
  // ignore bot messages
  if (message.author.bot) return;
  // ...
});

// or

client.on('message', message => {
  // ignore own messages
  if (message.author.id === client.user.id) return;
  // ...
});

匿名用户

您需要忽略bots,您正在创建一个无限循环,其中:

您将发送消息->;您的机器人接收它->;您的机器人发送一条消息->;您的机器人收到它自己的消息->;发送消息->;。。。

在消息处理程序的开头放置:

if (message.author.bot) {
  return;
}

或者如果您只想忽略您自己的bot:

if (message.client.user.id === message.author.id) {
  return;
}