创建文本通道的discord.js问题

时间:2019-02-20 19:20:05

标签: javascript discord.js

今天,我创建了一个可以使用“!new”命令的机器人,但后来遇到了问题。 “!new”命令创建一个名为“ support-1”的通道,但是当您重新输入“!new”时,它将再次创建一个具有相同名称的通道。现在,我有一个问题:如何创建命令以创建最终以升序编号的“支持”频道? (“ support-1”,“ support-2”等。)我的代码:

message.guild.createChannel(`ticket-${message.author.id}`, "text")

问题是我不知道要使ir,所以它会按从0到∞的顺序创建通道!

1 个答案:

答案 0 :(得分:0)

如果您想真正正确地执行此操作,则可以从公会获取所有频道。过滤掉不是文本通道的那些。从该组中过滤掉名称不为support-(number)的频道。从剩下的一组中找到编号最高的那个,并创建一个编号为1的新频道。

这是一些示例代码。对其进行测试以确保其正常工作。

bot.on("message", async message => {
  if (message.author.bot) return;

  if (message.content.startsWith('!new')) {
    // Fetch all the channels in the guild.
    let allChannels = message.guild.channels;

    // Filter out all the non-text channels.
    let textChannels = allChannels.filter((channel) => {
      return channel.type === "text";    
    });

    // Filter out all the text channels whose name isn't 'support-(number)'.
    let supportChannels = textChannels.filter((textChannel) => {
      // Checks whether a channel name has format 'support-(number)'. Look into Regex for more info.
      return textChannel.name.match(/^(support-)\d+$/g);
    });

    // Check if there are any support channels.
    if (supportChannels.length) {
      // Get the numbers from the channel name.
      let numbers = supportChannels.map((supportChannel) => {
        return parseInt(supportChannel.name.split('-')[1]);
      });

      // Get the highest number from the array.
      let highestNumber = Math.max(...numbers);

      // Create a new support channel with the highest number + 1.
      message.guild.createChannel(`support-${highestNumber+1}`, 'text');
    } else {
      // There are no support channels, thus create the first one.
      message.guild.createChannel('support-1', 'text');
    }
  }
});