Discord.js v14 如何实现机器人每10秒自动切换状态
在Discord.js v14中实现机器人状态轮播功能
核心思路
准备一个包含多种状态的数组,每个状态对应显示文本和活动类型,用setInterval每10秒切换一次机器人的在线状态。
修改后的完整代码
const Event = require('../../structures/EventClass'); const { ActivityType } = require('discord.js'); module.exports = class ReadyEvent extends Event { constructor(client) { super(client, { name: 'ready', once: true, }); } async run() { const client = this.client; // 自定义轮播状态列表,可按需修改内容和类型 const statusList = [ { text: '👑 TEST BOT WORKS', type: ActivityType.Playing }, { text: `📊 ${client.guilds.cache.size} 个服务器`, type: ActivityType.Watching }, { text: `👥 ${client.users.cache.size} 位用户`, type: ActivityType.Listening }, { text: '💡 输入 /help 查看指令', type: ActivityType.Competing } ]; let currentIndex = 0; // 每10秒执行一次状态切换 setInterval(() => { const currentStatus = statusList[currentIndex]; client.user.setActivity(currentStatus.text, { type: currentStatus.type }); // 循环切换索引,到末尾后回到开头 currentIndex = (currentIndex + 1) % statusList.length; }, 10000); // 10000毫秒 = 10秒 console.log("✅ [READY!] Starting Discord Bot...") console.log(`✅ [ONLINE!] Discord Bot is now online with ${client.users.cache.size} users and ${client.guilds.cache.size} servers.`); } };
关键说明
- 状态配置:
statusList中的每个对象对应一种状态,ActivityType的类型和旧版本逻辑一致,v14仅需显式导入该枚举即可。 - 轮播逻辑:通过取余运算
(currentIndex + 1) % statusList.length实现状态的循环切换,避免索引越界。 - 动态内容:示例中加入了服务器、用户数量的动态显示,你可以替换成任意自定义文案或动态数据。
额外提示
- 若需避免内存泄漏,可将定时器实例挂载到
client上,在机器人退出时调用clearInterval(client.statusInterval)清理:// 在run函数中保存定时器实例 client.statusInterval = setInterval(() => { // 切换逻辑 }, 10000); - 状态切换间隔建议不小于5秒,避免频繁API请求。
内容的提问来源于stack exchange,提问作者Whtery1087
相关产品推荐
相关产品推荐

