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

Discord.js v14:如何获取交互中用户选择的频道实现echo命令

Discord.js v14 Echo命令指定频道发送问题修复

你的问题出在**interaction.channel.send(input)**这一行——interaction.channel永远指向发起命令的频道,和用户选择的频道无关。要实现发送到指定频道,需要先获取用户选择的频道对象,再调用它的send方法。

修改后的完整代码:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { Client, GatewayIntentBits } = require('discord.js')

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

module.exports = {
    data: new SlashCommandBuilder()
        .setName('echo')
        .setDescription('Replies with your input!')
        .addStringOption(option =>
            option.setName('input')
                .setDescription('The input to echo back')
                .setRequired(true)
        )
        .addChannelOption(option => 
            option.setName('channel')
                .setDescription('Which channel do you want to send to')
                .setRequired(true)
        ),
                
    async execute(interaction) {
        const input = interaction.options.getString("input");
        // 获取用户选择的目标频道
        const targetChannel = interaction.options.getChannel('channel');
        
        // 额外判断:确保是可发送消息的文本频道(避免用户选语音/分类频道报错)
        if (!targetChannel.isTextBased()) {
            return interaction.reply({ content: '请选择一个文本频道!', ephemeral: true });
        }

        try {
            await targetChannel.send(input);
            await interaction.reply({ content: "Sent!", ephemeral: true });
        } catch (err) {
            // 处理机器人无权限发送消息的情况
            await interaction.reply({ content: '我没有在该频道发送消息的权限!', ephemeral: true });
        }
    } 
};

关键修改点:

  • 新增const targetChannel = interaction.options.getChannel('channel')获取用户选择的频道
  • 将interaction.channel.send(input)替换为targetChannel.send(input)
  • 增加了频道类型判断和错误捕获,避免因用户选错频道或机器人无权限导致的崩溃

内容的提问来源于stack exchange,提问作者average discord bot maker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 04:55:57