discord.js bot replies to itself

こ雲淡風輕ζ 提交于 2019-12-18 05:47:06

问题


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:


// In message event
if(message.author.id === client.user.id) return;

// I would recommend a variable like this for splits on words
// const args = message.content.trim().split(/\s+/g); 
// You could also .slice() off a prefix if you have one

if(/good job/i.test(message.content)) {
  message.channel.send('Good job everyone :smirk:'); // sendMessage is deprecated, use send instead
}



回答4:


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!



来源:https://stackoverflow.com/questions/46157012/discord-js-bot-replies-to-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!