如何将变量设置为用户指定的语音通道 - Discord.js

Posted

技术标签:

【中文标题】如何将变量设置为用户指定的语音通道 - Discord.js【英文标题】:How to set a variable to a voice channel specified by a user - Discord.js 【发布时间】:2021-10-06 21:10:41 【问题描述】:

总的来说,我对 discord.js 和 javascript 还是很陌生,所以如果这真的很简单,我深表歉意!

我正在开发一个 Discord 机器人,并试图让它为用户指定的语音通道设置一个变量。目前,ChosenChannel 仍然是 null。如果我直接在代码中(第 8 行)将 args 替换为频道名称,它会起作用,但用户无法更改它。

提前感谢您的帮助!

client.on ('message', message => 
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if (command == 'setchannel') 
        //set ChosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
        ChosenChannel = message.guild.channels.cache.find(channel => channel.name === args);
        //alert user if ChosenChannel is not an actual channel
        if (ChosenChannel == null) 
            message.channel.send('Unable to find channel');
        //alert user if ChosenChannel is not a voice channel
         else if (ChosenChannel.type !== 'voice') 
            message.channel.send('That does not seem to be a voice channel');
        //otherwise, confirm that the command worked, and print the name of the channel
         else    
            message.channel.send('The chosen channel is: ');
            message.channel.send(ChosenChannel.name);
        
    
);

【问题讨论】:

【参考方案1】:

args 是一个数组,通道名称是一个字符串。因此,您需要将 args 转换为字符串,方法是 join 用空格字符返回。

if (command == 'setchannel') 
  //set chosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
  const channelName = args.join(' ')
  const chosenChannel = message.guild.channels.cache.find(
    (channel) => channel.name === channelName,
  );
  //alert user if chosenChannel is not an actual channel
  if (!chosenChannel) 
    message.channel.send('Unable to find channel');
    //alert user if chosenChannel is not a voice channel
   else if (chosenChannel.type !== 'voice') 
    message.channel.send('That does not seem to be a voice channel');
    //otherwise, confirm that the command worked, and print the name of the channel
   else 
    message.channel.send('The chosen channel is: ');
    message.channel.send(chosenChannel.name);
  

其实频道名是不能有空格的,所以它总是args的第一个元素,所以你也可以这样使用:

if (command == 'setchannel') 
  //set chosenChannel to a channel within the current server that matches the name typed by the user (not currently working!)
  const chosenChannel = message.guild.channels.cache.find(
    (channel) => channel.name === args[0],
  );
  // ...

【讨论】:

确实很简单。非常感谢您的帮助!

以上是关于如何将变量设置为用户指定的语音通道 - Discord.js的主要内容,如果未能解决你的问题,请参考以下文章

如何访问discord.py中的哪个语音通道用户写入命令?

如何确定用户是不是加入/切换/离开了语音频道?

如何在 discord.py 机器人加入语音通道之间添加暂停?

将 guildUserProperties.Mute 设置为 false 时,Bot 不会取消静音用户

用户使用JDA进入公会时如何更新语音通道

(Discord.py) 如何锁定和解锁语音通道