简体   繁体   中英

discord.js problem with creating text channel

Today I created a bot that works with the "!new" command, but then I faced the problem. The "!new" command creates a channel called "support-1", but when you re-enter "!new" it creates a channel with the same name again. Now I have a question: How do I create a command to create "support" channels that end up being numbered in ascending order? ( "support-1", "support-2" etc. ) My code:

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

The problem is that i don't know to make ir so it creates channels in order from 0 to ∞!

If you want to really properly do it, you could fetch all the channels from a guild. Filter out the ones that aren't text channels. From that set, filter out the channels which don't have the name support-(number) . From the set which you have left, find the one with the highest number and create a new channel with that number + 1.

Here's some example code. Test it to make sure it works.

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');
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM