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
相关产品推荐
相关产品推荐

