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

如何为不同角色在单个Slash Command中实现差异化功能?

实现多角色差异化命令逻辑(Discord.js)

为了让不同角色成员使用同一命令时触发差异化奖励逻辑,我们可以将角色与对应奖励范围的映射关系抽离为配置对象,后续新增角色等级时只需修改配置,无需改动核心执行逻辑。以下是优化后的代码:

module.exports = {
    cooldown: 1,
    data: new SlashCommandBuilder().setName("test").setDescription("测试多角色奖励命令"),
    async execute(interaction) {
        // 基础常量配置
        const guildId = "1115972333480452146";
        const userId = interaction.user.id;
        const itemId = "1116763689014398798";

        // 角色-奖励映射配置:按优先级从高到低排列,键为角色ID,值为对应奖励区间
        const roleRewardConfig = [
            { roleId: "1115972503597228112", min: 15000, max: 20000 }, // 一级角色(最高优先级)
            { roleId: "替换为二级角色ID", min: 10000, max: 15000 },    // 二级角色
            { roleId: "替换为三级角色ID", min: 5000, max: 10000 }      // 三级角色
        ];

        // 查找用户拥有的首个匹配角色(遵循配置的优先级顺序)
        const matchedRole = roleRewardConfig.find(config => interaction.member.roles.cache.has(config.roleId));

        if (!matchedRole) {
            // 无匹配角色时的提示
            const noPermissionEmbed = new EmbedBuilder()
                .setColor(0x0099ff)
                .setDescription("您没有使用该命令的权限等级。");
            await interaction.reply({ embeds: [noPermissionEmbed] });
            return;
        }

        // 生成对应角色的随机奖励金额
        const reward = Math.floor(Math.random() * (matchedRole.max - matchedRole.min) + matchedRole.min);
        
        // 发送奖励结果提示
        const rewardEmbed = new EmbedBuilder()
            .setColor(0x0099ff)
            .setDescription(`您获得了 ${reward} 奖励!`);
        await interaction.reply({ embeds: [rewardEmbed] });

        // 将奖励物品添加至用户背包
        const inventoryItem = await unb.addInventoryItem(guildId, userId, itemId, reward);
        console.log(inventoryItem);
    },
};

核心逻辑说明

  • 配置化管理:通过roleRewardConfig数组统一维护角色与奖励的对应关系,新增或调整角色等级时仅需修改此配置,无需改动执行逻辑。
  • 优先级匹配:使用find方法按配置顺序查找用户角色,确保高优先级角色的奖励规则优先生效。
  • 逻辑复用:所有角色的奖励生成、消息回复、背包操作逻辑复用,避免重复代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:02:27