简体   繁体   中英

Discord Bot Development: How do I stop this infinite loop?

This calls and retrieves a dog url from random.dog, when posting the link to log it stops at one, however when using message.channel.send below it runs an infinite loop of the call, what would be the best way to prevent this and to only send one link then stop till it is called again?

const animals = require('relevant-animals')

client.on("message", (message) => {                   
if(message.content.includes("dog")){ 
animals.dog().then(s => message.channel.send(s)) ; 
animals.dog().then(s => console.log(s)) ;
};

Below is console log after one request it sends one link这是一个请求后的控制台日志,它发送一个链接

Below is after it is sent to the channel, it just posts links non stop rather than just the one as shown in the console

这是发送到频道之后

Your bot is responding to itself. You can exclude it for replying to itself by using message.author.bot .

if(!message.author.bot) {
   // Do something if message doesn't come from a bot.
}

Hope this will help!

You could just do this:

if(message.author.bot) return;

This wouldn't only stop bot from executing commands etc. on itself, it would prevent any bot from using your bot.

Since it checks for author of message if bot property returns true it would return; .

And if bot property returns false it would work as normally - only for users like you and me, and many others!

You can try this by doing the following code:

console.log(message.author.bot);

It will log the boolean value of bot property of the messages author. You can read more about booleans (true/false) here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM