首页 > 解决方案 > 如何编写一个每 30 分钟运行一次的 Javascript 函数

问题描述

对于我的 discord.js 机器人,我试图让它有一个不断变化的状态消息,但我无法让计时器工作,所以现在这是我的基本状态代码,(此代码使机器人状态显示为“正在观看:你”)

client.on('ready', () =>{
    console.log(`Logged in`);
    client.user.setPresence({
        status: "online",  
        game: {
            name: "You",  
            type: "WATCHING" 
        }
    });
 });

标签: javascriptdiscorddiscord.js

解决方案


let statuses = [
    {game: {name: `1`}, type: "WATCHING"},
    {game: {name: `2`}, type: "PLAYING"}
    {game: {name: `3`}, type: "STREAMING"}
];
let i = 0;

setInterval(() => {
     // Get the status
     let status = statuses[i];
     // If it's undefined, it means we reached the end of the array
     if(!status){
         // Restart at the first status
         status = statuses[0];
         i = 0;
     }
     client.user.setPresence(status);
     i++;
}, 5000);

机器人每 5 秒改变一次状态


推荐阅读