【问题标题】:"If" Statement Acting Like "While" Loop“If”语句的作用类似于“While”循环
【发布时间】:2018-07-04 04:28:27
【问题描述】:

我已经开始创建 Discord 机器人。这是问题所在:该机器人正在发送垃圾邮件。我希望他在条件为真时只发送一条消息。我正在使用if 语句,但它的作用类似于while 循环。代码如下:

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");
    }
})

当我输入“文本”(例如)时,它会发送“回复”,直到脚本停止。
你能帮我解决这个问题吗?

【问题讨论】:

  • 您收到一条消息并无条件发送另一条消息。您还会收到并再次发送回复,一次又一次,...
  • @zerkms 除非他回复的消息包含text,否则他应该很好。如果是这样,那就太搞笑了。
  • @vzwick 确实如此,我觉得很愚蠢
  • @Francefire 不要为此自责——我们都去过那里。至少你没有删除生产数据库。

标签: javascript node.js discord.js


【解决方案1】:

再次阅读我的代码后,问题是回复包含“文本”。

我找到了解决办法:

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 ");
    }
}

})

【讨论】:

  • if (message.content.includes("text") && message.client.user.id !== client.user.id) ;)
【解决方案2】:

您正在发送一条消息“回复文本”,该消息本身包含“文本”一词。

更改您的示例以使用不同的短语。

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

此外,在 cmets 中进一步讨论后,如果您希望客户端忽略其自己的消息,您可以尝试以下操作:

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

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

【讨论】:

  • 所以我尝试了您的解决方案,但没有成功,所以我使用了 console.log 来帮助我找到问题,而且似乎 message.client.user.id 和 client.user.id给出了相同的值,发现我应该使用 message.author.user.id 并且它可以工作,谢谢;)
  • 恭喜!很好的故障排除!
猜你喜欢
  • 2015-05-19
  • 2013-06-09
  • 2014-01-21
  • 2015-11-08
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
相关资源
最近更新 更多