discord.js 响应用户消息调用函数时出现无限循环
discord.js Infinite loop occurs when function is called in response to user's message
我目前正在使用 JavaScript 开发 Discord 机器人。当用户说出数组中的任何内容时,机器人会发送随机生成的消息:
const wordCombos = ["word1","word2","word3","word4"];
randomText 是生成随机生成消息的函数,它使用 for 循环将数组中的单词随机添加到字符串中。 getRandom 函数就在它的正下方。
function randomText(out)
{
var lengthOf = getRandom(2, 6);
var words = ["random1","random2","random3","random4","random5"];
var keySmash = "";
for (var i=0; i < lengthOf; i++)
{
var wordsRandom = getRandom(0, words.length);
keySmash += words[wordsRandom];
}
out(keySmash);
}
function getRandom(min, max)
{
return Math.floor((Math.random() * max) + min);
}
当用户发送包含数组 wordCombos 中的单词的消息时,它会调用该函数。发生这种情况时,无限循环开始,用户收到随机生成的垃圾邮件。
client.on('message', msg =>
{
if(wordCombos.some(word => msg.content.includes(word)))
{
randomText((out) => {msg.channel.send(out);});
}
});
我曾尝试使用一个使用布尔值的 while 循环,但是该程序要么只 运行 一次,要么再次导致无限循环。
欢迎任何反馈。
所以可能导致您的代码 运行 那样的事情是您的机器人也在响应它发送给自己的消息。要解决这个问题,您应该在代码的开头部分之后添加此代码 if (message.author.bot) return;
,这样它就可以用作过滤器。
client.on('message', msg =>
{
//message.author.bot returns a boolean
//true if the user who posted is the bot, else it returns false
if (message.author.bot) return;
if(wordCombos.some(word => msg.content.includes(word)))
{
randomText((out) => {msg.channel.send(out);});
}
});
为了完成 PerplexingParadox 的回复,我认为您应该像这样在您的情况下使用 includes() :
if (wordCombos.includes(msg.content))
{
randomText((out) => {msg.channel.send(out);});
}
我想也是一样的。 :)
我目前正在使用 JavaScript 开发 Discord 机器人。当用户说出数组中的任何内容时,机器人会发送随机生成的消息:
const wordCombos = ["word1","word2","word3","word4"];
randomText 是生成随机生成消息的函数,它使用 for 循环将数组中的单词随机添加到字符串中。 getRandom 函数就在它的正下方。
function randomText(out)
{
var lengthOf = getRandom(2, 6);
var words = ["random1","random2","random3","random4","random5"];
var keySmash = "";
for (var i=0; i < lengthOf; i++)
{
var wordsRandom = getRandom(0, words.length);
keySmash += words[wordsRandom];
}
out(keySmash);
}
function getRandom(min, max)
{
return Math.floor((Math.random() * max) + min);
}
当用户发送包含数组 wordCombos 中的单词的消息时,它会调用该函数。发生这种情况时,无限循环开始,用户收到随机生成的垃圾邮件。
client.on('message', msg =>
{
if(wordCombos.some(word => msg.content.includes(word)))
{
randomText((out) => {msg.channel.send(out);});
}
});
我曾尝试使用一个使用布尔值的 while 循环,但是该程序要么只 运行 一次,要么再次导致无限循环。
欢迎任何反馈。
所以可能导致您的代码 运行 那样的事情是您的机器人也在响应它发送给自己的消息。要解决这个问题,您应该在代码的开头部分之后添加此代码 if (message.author.bot) return;
,这样它就可以用作过滤器。
client.on('message', msg =>
{
//message.author.bot returns a boolean
//true if the user who posted is the bot, else it returns false
if (message.author.bot) return;
if(wordCombos.some(word => msg.content.includes(word)))
{
randomText((out) => {msg.channel.send(out);});
}
});
为了完成 PerplexingParadox 的回复,我认为您应该像这样在您的情况下使用 includes() :
if (wordCombos.includes(msg.content))
{
randomText((out) => {msg.channel.send(out);});
}
我想也是一样的。 :)