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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:05:33