Discord.js V13 使用斜杠命令触发用户角色分配功能报错求助
Discord机器人斜杠命令分配角色功能修复方案
错误原因
你遇到的"message not found, did you mean Message"报错,是因为当前使用的discord.js v14及以上版本调整了模块导出规则,你使用的旧版导入写法已经不兼容,同时你的代码仅实现了斜杠命令的注册和回复逻辑,没有补充分配角色的核心功能代码。
修复要点
- 移除未使用的
Message、Role导入,修正权限枚举的导入方式 - 补充
GuildMembers权限意图,否则无法读取和修改成员角色 - 补充
giverole命令的角色分配逻辑,添加异常捕获避免权限不足导致崩溃 - 提前在Discord开发者门户的机器人设置页开启
Server Members Intent开关,邀请机器人时勾选Manage Roles权限,且确保你要分配的角色在服务器角色列表中的位置低于机器人自身的角色
修复后完整代码
import DiscordJS, { GatewayIntentBits } from 'discord.js' import dotenv from 'dotenv' dotenv.config() const client = new DiscordJS.Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMembers ], }) client.on('ready', () => { console.log('BOT ONLINE') //bot test server const guildId = '868857440089804870' const guild = client.guilds.cache.get(guildId) let commands if (guild) { commands = guild.commands } else { commands = client.application?.commands } commands?.create({ name: 'ping', description: 'says pong' }) commands?.create({ name: "serverip", description: 'Gives user the server IP' }) commands?.create({ name: "giverole", description: 'Gives user the role' }) }) client.on('interactionCreate', async (interaction) => { if(!interaction.isCommand()) { return } const { commandName, user, guild } = interaction //This is the role id that i want to give const roleId = '884231659552116776' //these are the users that i want to give the role to const allowedUsers = ['725867136232456302', '311981346161426433'] if (commandName === 'ping') { interaction.reply({ content: 'pong', ephemeral: true, }) } else if (commandName === 'serverip') { interaction.reply({ content: 'thisisserverip.lol', ephemeral: true, }) } else if (commandName === 'giverole') { // 校验用户是否在允许列表中 if (!allowedUsers.includes(user.id)) { return interaction.reply({ content: '你没有权限领取该角色', ephemeral: true }) } try { const member = await guild.members.fetch(user.id) await member.roles.add(roleId) interaction.reply({ content: 'Role given', ephemeral: true, }) } catch (err) { console.error('角色分配失败:', err) interaction.reply({ content: '角色分配失败,请确认机器人权限配置正确', ephemeral: true }) } } }) client.login(process.env.test)
内容的提问来源于stack exchange,提问作者Connor Brown
相关产品推荐
相关产品推荐

