discord.js bot replies to itself

2019-01-28 00:48发布

问题:

I am currently coding my first discord bot, it can already play YouTube music.

if (message.content.includes("Good Job") || 
    message.content.includes("good job")) {
    message.channel.sendMessage("Good Job everyone :smirk:");
}

As you see, if someone types "good job" (this is just an example) then the bot will reply with "good job everyone :smirk:), but then the spam will begin: the bot reads his own message and replies to it.

How can I prevent the bot from answering itself?

回答1:

Use this in the on message event:

if (message.author.bot) return;

for more info: https://anidiotsguide.gitbooks.io/discord-js-bot-guide/coding-guides/a-basic-command-handler.html



回答2:

The reason why your bot replies to yourself is because where you put:

if (message.content.includes("Good Job") || message.content.includes("good job"))

It is basically checking the chat if a piece of text includes the words "Good Job" or "good job". As your bot sends:

message.channel.sendMessage("Good Job everyone :smirk:");

as an answer, it creates a loop because that message includes the words "Good Job", basically running the code again and again and again.

Of course, the easiest way of fixing this is for you to change the answer it gives to not include the words Good Job, but there is better solution to make sure it doesn't happen for all of the commands you might make.

As @Jörmungandr said, under the message event include:

if (message.author.bot) return;

to make sure it doesn't happen. It essentially checks if the author of the message is a bot and if it is, it ignores it.

discord.js



回答3:

You can simply just check if the user sending the message is a bot. For example:

if (!msg.author.bot) {
    <Your code to execute if the user is not a bot.>
} 

Hope this was helpful, thank you!