Francefire
Francefire

Reputation: 81

"If" Statement Acting Like "While" Loop

I've started creating a Discord bot. Here's the problem: the bot is spamming. I want him to send only one message when the condition is true. I'm using an if statement, but it acts like a while loop. Here's the code:

const Discord = require("discord.js");
const client = new Discord.Client();
const token = 'TotallyNotMyRealToken';

client.login(token);

client.on('message', message => 
{
    if(message.content.includes("text"))
    {
        message.channel.send(" reply text");
    }
})

When I type "text" (for example), it sends "reply" until the script stops.
Could you please help me solve the issue?

Upvotes: 1

Views: 392

Answers (2)

Francefire
Francefire

Reputation: 81

After reading again my code, the problem is that the replies contains "text".

I found a solution :

const Discord = require("discord.js");
const bot = new Discord.Client();
const token = 'NDA1ODQxMjg5NzU0NTc0ODQ5.DUqQww.HwSaa8TagR1mMGsVpdMDUm6-7tI';

bot.login(token);

bot.on('message', message => 
{    
   messageInput = message.content.toLowerCase();
   botId = bot.user.discriminator
   userId = message.author.discriminator
   console.log(botId)
   console.log(userId)
   console.log(messageInput)
    if(userId !== botId)
    {
        if(messageInput.includes("text"))
        {
            message.channel.send(" reply text ");
    }
}

})

Upvotes: 2

MicFin
MicFin

Reputation: 2501

You are sending a message "reply text" which itself includes the word "text".

Change your example to use a different phrase.

client.on('message', message => 
{
    if(message.content.includes("text"))
    {
        message.channel.send(" this is a reply");
    }
})

Additionally, upon further discussion in the comments, if you would like a client to ignore its own messages, you could try something like:

client.on('message', message => 
{
    if(message.content.includes("text") && message.author.user.id !== client.user.id)
    {
        message.channel.send(" reply text");
    }
})

See https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=client

Upvotes: 2

Related Questions