You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用discord.js v13自动获取服务器Booster角色并存入quick.db?

获取Discord服务器Booster角色并存入quick.db的实现方案

当然可以实现这个需求,下面是具体的代码示例和注意事项,适配Discord.js v14+和quick.db:

步骤1:依赖安装

确保你已经安装了所需依赖:

npm install quick.db discord.js

步骤2:核心代码实现

这段代码会在机器人启动时批量同步所有服务器的Booster角色,同时监听新服务器加入、角色修改事件来自动更新数据库:

const { Client, GatewayIntentBits } = require('discord.js');
const db = require('quick.db');

// 初始化机器人客户端,需要必要的权限意图
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildRoles
  ]
});

// 机器人启动后,批量同步所有服务器的Booster角色
client.on('ready', async () => {
  console.log(`已登录:${client.user.tag}`);
  
  client.guilds.cache.forEach(async (guild) => {
    try {
      // 获取当前服务器的Booster角色
      const boosterRole = guild.roles.premiumSubscriberRole;
      
      // 以服务器ID为标识存入数据库,无Booster角色则存null
      await db.set(`boosterRole_${guild.id}`, boosterRole?.id || null);
      console.log(`同步服务器 ${guild.name}:${boosterRole ? `Booster角色ID ${boosterRole.id}` : '无Booster角色'}`);
    } catch (err) {
      console.error(`同步服务器 ${guild.name} 失败:`, err);
    }
  });
});

// 机器人加入新服务器时,自动同步该服务器的Booster角色
client.on('guildCreate', async (guild) => {
  try {
    const boosterRole = guild.roles.premiumSubscriberRole;
    await db.set(`boosterRole_${guild.id}`, boosterRole?.id || null);
    console.log(`新服务器 ${guild.name} 同步完成:${boosterRole ? `Booster角色ID ${boosterRole.id}` : '无Booster角色'}`);
  } catch (err) {
    console.error(`新服务器 ${guild.name} 同步失败:`, err);
  }
});

// 监听角色修改事件,当Booster角色变更时自动更新数据库
client.on('roleUpdate', async (oldRole, newRole) => {
  const guild = oldRole.guild;
  // 确认修改的是原Booster角色
  if (oldRole.id === guild.roles.premiumSubscriberRole?.id) {
    const newBoosterRole = guild.roles.premiumSubscriberRole;
    await db.set(`boosterRole_${guild.id}`, newBoosterRole?.id || null);
    console.log(`服务器 ${guild.name} Booster角色更新:${newBoosterRole ? `新ID ${newBoosterRole.id}` : '已移除'}`);
  }
});

// 登录机器人
client.login('你的机器人Token');

关键注意事项

  • Discord.js版本兼容:如果使用v13版本,将guild.roles.premiumSubscriberRole替换为guild.premiumRole
  • 权限要求:机器人必须拥有Guilds和GuildRoles的权限意图,否则无法获取服务器角色信息
  • 数据库键设计:用boosterRole_${guild.id}作为键,方便后续通过服务器ID快速查询对应的Booster角色ID
  • 空值处理:对于没有开通服务器提升或未设置Booster角色的服务器,存入null,后续业务逻辑中可以通过判断该值是否存在来处理
  • 错误捕获:每个服务器的处理都加入了try/catch,避免单个服务器处理失败导致整个同步流程中断

内容的提问来源于stack exchange,提问作者Wayz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:20:57