DiscordJS开发Discord机器人:指定频道发消息命令异常求助
修复Discord.js公告命令的问题
你的代码存在几个关键问题导致命令无法正常运行,以下是修正方案及说明:
核心问题点
- 获取频道时错误使用
interaction.options.get(),需改用getChannel()才能拿到实际的频道实例 - 错误提示未设置为仅发起者可见,易造成不必要的公开干扰
- 频道提及的写法可以更简洁可靠
修正后的完整代码
const { Interaction, SlashCommandBuilder, ChannelType, PermissionFlagsBits } = require("discord.js"); module.exports = { data: new SlashCommandBuilder() .setName('announce') .setDescription('向指定频道发送公告') .setDefaultMemberPermissions(PermissionFlagsBits.MentionEveryone) .addChannelOption(option => option .setName('channel') .setDescription('发送公告的目标频道') .addChannelTypes(ChannelType.GuildText) .setRequired(true) ) .addStringOption(option => option .setName('message') .setDescription('公告内容') .setMinLength(1).setMaxLength(1950) .setRequired(true) ) .addBooleanOption(option => option .setName('mention_everyone') .setDescription('是否@全体成员') ) .setDMPermission(false), /** * @param {Interaction} interaction */ async execute(interaction) { // 改用getChannel获取真实频道对象 const channel = interaction.options.getChannel('channel'); const message = interaction.options.getString('message'); const mentionEveryone = interaction.options.getBoolean('mention_everyone') ?? false; try { await channel.send(mentionEveryone ? `@everyone \n\n${message}` : message); // 用channel.toString()直接生成频道提及,无需手动拼接ID await interaction.reply({ content: `公告已成功发送至 ${channel.toString()}`, ephemeral: true // 仅命令发起者可见该提示 }); } catch (error) { console.error(error); // 处理重复回复报错的情况 const replyOpts = { content: '发送公告失败,请检查机器人是否拥有目标频道的发送消息权限', ephemeral: true }; if (interaction.replied) { await interaction.followUp(replyOpts); } else { await interaction.reply(replyOpts); } } } };
额外注意事项
- 确保机器人在目标频道拥有发送消息权限,若需@全体成员,还需开启提及全体成员权限
- 私有频道需将机器人加入对应权限组,否则无法发送消息
- 已设置消息长度限制(1-1950字符),避免触发Discord的内容长度限制报错
内容的提问来源于stack exchange,提问作者prime
相关产品推荐
相关产品推荐

