如何检测Discord机器人say命令中用户是否指定了频道?
Let's break down the problem with your current say command code right now: you're always slicing args from index 2 for the message content, regardless of whether the user actually specified a target channel. That means when no channel is provided, you end up cutting off the first word of the intended message.
The Root Problem
Your original code sets channel to either the mentioned channel, a channel matching args[1], or the current channel—but you never check if that channel was actually found from the user's input before setting msg. So even when the user doesn't specify a channel, msg is still using args.slice(2), which skips the first word incorrectly.
The Solution
Here's how to adjust your code to properly detect if a channel was specified, and set the message content accordingly:
if(command === `${prefix}say`) { if(!message.member.roles.has(`337402636015894528`)) return; let channel = message.mentions.channels.first() || message.guild.channels.find("name", args[1]); let msg; // Check if we found a channel from user input if(!channel) { // No channel specified, use current channel and slice args from index 1 channel = message.channel; msg = args.slice(1).join(" "); } else { // Channel was specified, slice args from index 2 (skip the channel mention/name) msg = args.slice(2).join(" "); } message.delete(); channel.send(msg); }
How This Works
- First, attempt to find the target channel: We check for a mentioned channel first, then try to match
args[1]to a channel name. If neither works,channelwill beundefined. - Check if channel exists: If
channelisundefined, that means the user didn't specify a valid channel. We fall back to the current channel, and setmsgtoargs.slice(1)(since there's no channel argument to skip). - Channel was specified: If we did find a channel from the user's input, we skip that argument (either the mention or the name in
args[1]) by slicing from index 2, then join the rest into the message content.
This way, the command behaves exactly as you want:
- When the user types
!say #general Hello everyone, it sends "Hello everyone" to #general. - When the user types
!say Hello everyone, it sends "Hello everyone" to the current channel.
内容的提问来源于stack exchange,提问作者Exominem

