【问题标题】:How to set a variable to a voice channel specified by a user - Discord.js如何将变量设置为用户指定的语音通道 - 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);
        }
    }
});

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案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],
      );
      // ...
    

    【讨论】:

    • 确实很简单。非常感谢您的帮助!
    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2019-06-30
    • 2019-09-23
    • 2022-10-14
    • 2022-01-16
    • 2021-05-04
    相关资源
    最近更新 更多