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

如何用Discord.js的SlashCommandBuilder向指定频道发送公开消息

问题

我现有如下基于SlashCommandBuilder的Discord.js斜杠命令代码:

const { SlashCommandBuilder } = require('discord.js');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        await interaction.reply('Pong!');
    },
};

请问如何修改该命令,使其执行时不回复交互,而是向指定频道ID发送所有人可见的普通文本消息“Pong!”,且仍以斜杠命令形式实现?

修改方案

需要满足Discord对斜杠命令的响应要求,同时实现向指定频道发消息的逻辑,修改后的代码如下:

const { SlashCommandBuilder } = require('discord.js');

// 替换成你的目标频道ID
const TARGET_CHANNEL_ID = '123456789012345678';

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Sends Pong! to a specified channel'),
    async execute(interaction) {
        // 发送仅执行者可见的临时响应,避免Discord判定命令超时
        await interaction.deferReply({ ephemeral: true });

        try {
            // 获取目标频道
            const targetChannel = await interaction.client.channels.fetch(TARGET_CHANNEL_ID);
            
            // 校验频道是否可发送文本消息
            if (targetChannel && targetChannel.isTextBased()) {
                await targetChannel.send('Pong!');
                // 可选:给执行者发送成功提示,也可以用interaction.deleteReply()直接删除临时响应
                await interaction.editReply('已向指定频道发送Pong!');
            } else {
                await interaction.editReply('指定频道不存在或无法发送消息');
            }
        } catch (error) {
            console.error('发送消息失败:', error);
            await interaction.editReply('发送消息时出现错误');
        }
    },
};
关键说明
  • 交互响应要求:Discord规定斜杠命令必须在3秒内给出反馈,用deferReply({ ephemeral: true })生成仅执行者可见的临时响应,避免命令被标记超时。
  • 频道权限与校验:确保机器人拥有目标频道的发送消息权限,同时用isTextBased()校验频道类型,避免向不可发送文本的频道操作报错。
  • 灵活的提示选项:可以选择给执行者发送操作提示,也可以直接删除临时响应,完全隐藏交互反馈。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:10:38