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

Discord.js v12中TypeScript提示role.setPermissions为有效函数但运行时报错TypeError: role.setPermissions is not a function

解决Discord.js v12中role.setPermissions is not a function错误

你遇到这个报错的核心原因很明确:Discord.js v12里根本没有Role.setPermissions()这个方法——这个方法是v13及更高版本才新增的API。在v12中,修改角色权限需要使用Role.edit()方法来实现。

具体修复步骤

1. 替换权限修改的核心代码

把你循环里的这行错误代码:

await role.setPermissions(role.permissions.remove(args[0]))

改成v12对应的正确写法:

await role.edit({
  permissions: role.permissions.remove(args[0])
})

2. 优化角色集合的获取(可选但推荐)

你当前的角色获取代码let roles = (await msg.guild.roles.fetch()).cache;有点冗余,因为msg.guild.roles.fetch()在v12中不带参数时,会直接返回包含服务器所有角色的Collection(已经是缓存同步后的结果),可以简化成:

let roles = await msg.guild.roles.fetch();

3. 额外的小优化建议

  • 遍历角色集合不需要用for await...of,因为Collection的遍历是同步操作,改成普通for...of即可:
    for (const [, role] of roles) {
      // 你的角色处理逻辑
    }
    
  • 给getRoleByMention函数加个格式校验,避免用户输入非标准角色提及导致的报错:
    function getRoleByMention(mention, guild) {
      if (!mention?.startsWith('<@&') || !mention?.endsWith('>')) return null;
      const id = mention.slice(3, -1);
      return guild.roles.cache.get(id);
    }
    
  • 可以给最终的消息添加空值判断,避免没有符合条件角色时显示空字符串:
    msg.channel.send(`Replaced roles: ${replaced || "None"}`);
    

关于命令参数的说明

你执行的命令m.removeRolePerm MANAGE_MESSAGES @Dyno @Dyno把高位和低位角色设为同一个,这本身不会导致权限修改的错误,只是会过滤出位置等于该角色的角色(如果存在的话),所以这个参数设置没问题。

完整修改后的execute函数示例

async execute(client, msg, args, cooldowns, guildForPre, prefix) {
  if(msg.member.permissions.has("MANAGE_ROLES")) {
    let roles = await msg.guild.roles.fetch();
    let highPos = getRoleByMention(args[1], msg.guild)?.position || msg.guild.roles.highest.position;
    let lowPos = getRoleByMention(args[2], msg.guild)?.position || msg.guild.roles.everyone.position;
    
    roles = roles.filter(r => r.permissions.has(args[0]))
                 .filter(r => r.position <= highPos && r.position >= lowPos);
    
    let replaced = '';
    for (const [, role] of roles) {
      if(role.position >= msg.guild.me.roles.highest.position || role.position >= msg.member.roles.highest.position) continue;
      
      await role.edit({ permissions: role.permissions.remove(args[0]) });
      replaced = replaced ? `${replaced}, ${role.name}` : role.name;
    }
    
    msg.channel.send(`Replaced roles: ${replaced || "None"}`);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:13:15