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

如何检测Discord机器人say命令中用户是否指定了频道?

Fixing the "say" Command Channel Detection Issue in Discord.js

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

  1. 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, channel will be undefined.
  2. Check if channel exists: If channel is undefined, that means the user didn't specify a valid channel. We fall back to the current channel, and set msg to args.slice(1) (since there's no channel argument to skip).
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:05:24