Javascript 如何使我的机器人每10秒更改一次状态?
这是我的代码,有人说我应该使用Javascript 如何使我的机器人每10秒更改一次状态?,javascript,discord,discord.js,bots,Javascript,Discord,Discord.js,Bots,这是我的代码,有人说我应该使用Math.floor,但我不知道应该把它放在哪里 bot.user.setActivity({ name: 'Arth agora em JavaScript~', type: 'PLAYING' }) }); 您将需要一系列不同的活动,您可以插入任意数量的活动 setInterval每10秒执行一次arrow函数中的代码(指定为10000毫秒)。arrow函数中的代码将从数组中随机选择一个活动 const activities = [ { name: '
Math.floor
,但我不知道应该把它放在哪里
bot.user.setActivity({ name: 'Arth agora em JavaScript~', type: 'PLAYING' })
});
您将需要一系列不同的活动,您可以插入任意数量的活动
setInterval
每10秒执行一次arrow函数中的代码(指定为10000毫秒)。arrow函数中的代码将从数组中随机选择一个活动
const activities = [
{ name: 'Arth agora em JavaScript~', type: 'PLAYING' },
{ name: 'Another activity', type: 'PLAYING' }
];
setInterval(() => bot.user.setActivity(activities[Math.floor(Math.random() * activities.length)]), 10000);
使用setInterval()
:
您可以使用递归setTimeout(优于setInterval),它将在您想要的任何时间执行,并且不会导致任何类型的内存泄漏
function Foo(){
// your code here
setTimeout(Foo, 5000); // you can define your function and the amount of time here
}
Foo();
我不太确定您的请求,但如果您希望您的机器人的状态每x秒更改一次,您可以在代码中应用您的概念,并使用Math.random()生成具有此类型函数的随机数:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
Math.floor()仅将数字舍入到最接近的整数
因此,最后,您可以将这两种代码结合起来,获得以下结果:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function updateStatus(){
bot.user.setActivity({ name: 'Random Status : ' + getRandomInt(1, 200), type: 'PLAYING' })
});
setTimeout(updateStatus, 5000); // you can define your function and the amount of time here
}
updateStatus();
但是,我建议您构建一个更复杂的结构,比如客户端-服务器,以便每次都刷新数据包,但我甚至不知道您的全部代码。您可以更改bot活动/状态
const activities_list = [
"RANDOM",
"help",
"Random Status"
];
setInterval(() => bot.user.setActivity(activities[Math.floor(Math.random() * activities_list.length)]), 10000);
您的代码段语法无效。要设置一个重复出现的事件,您可能应该使用setInterval:每十秒更改一次状态将打破不和谐添加到@Octogonal T,让您的机器人每Y秒执行任何X操作被视为API垃圾邮件
const activities_list = [
"RANDOM",
"help",
"Random Status"
];
setInterval(() => bot.user.setActivity(activities[Math.floor(Math.random() * activities_list.length)]), 10000);