L oop для отображения справочной команды - PullRequest
1 голос
/ 20 января 2020

На самом деле, я пытаюсь создать бота с диссонансом. js и пытаюсь выполнить команду помощи.

Я не понимаю, почему мой l oop делает это (я знаю, что это не так) хороший способ для этого)

let i = 0;
const embed = new RichEmbed();

if (args.length < 1) {
  embed.setColor('#5B4DCA');
  while (i < list_groups.length) {
    let x = 0;
    embed.setTitle(`${list_groups[i]}`)
    while (x < groups.length) {
      if (groups[x] === list_groups[i]) {
        embed.addField('test1', 'test2')
      }
      x++;
    }
    message.channel.send(embed)
    i++;
  }
}

«Модерации» должны отображать одну команду, «уровень и ранг», команда «Outils» 4 и «Sondage» тоже

введите описание изображения здесь

1 Ответ

0 голосов
/ 20 января 2020

Я думаю, что вы решили, что это не правильный путь. Если у вас будет более 10 групп, бот выдаст список спам-команд. 1 способ сделать это - отобразить список всех категорий, если args.length===0, если args! == 0, вы пытаетесь найти все команды в этой категории. Чтобы исключить вставку, вы можете добавить только 18 полей, поэтому, если у вас более 18 команд в категории, вы получите ошибку API. Таким образом, вам нужно объединить команды на страницах.

Этот код будет отображать все категории, если args.length === 0 или группы команд не оштрафованы. Если группа оштрафована, бот отправляет встраиваемое сообщение с командой в группу (макс. 10) и реагирует на сообщение, если страниц больше 1, поэтому пользователь может изменить страницу с реакцией.

   const {Discord,RichEmbed} = require('discord.js');
    const {prefix,token,classic_roles} = require('../config.json');
    const logs = require('../logs/logs');

    module.exports.run = async (bot, message, args) => {
        if(args.length === 0) {
            //Show user all allowed groups commands 
            let commandCategories = bot.commands.map(command => `!help ${command.help.groups}`).filter(onlyUnique).join('\n') //find all categories and get onlyUnique
            let helpMessage = `**The list of command groups:**\n\n ${commandCategories}`
            let Embed = new Discord.RichEmbed()
                .setAuthor(message.author.tag, message.author.displayAvatarUrl)
                .setDescription(helpMessage)
                .setColor('#e0c40b')
            message.channel.send(Embed)
        } else {
            //try find required group 
            let commandsInCategory = bot.commands.filter(command => command.help.groups === args.join(' ').toLowerCase())
            if(commandsInCategory.size === 0) {
                // if no group find, then display user list of groups 
                let commandCategories = bot.commands.map(command => `!help ${command.help.groups}`).filter(onlyUnique).join('\n')
                let helpMessage = `**For get command list use**\n\n ${commandCategories}`
                        let Embed = new Discord.RichEmbed()
                .setAuthor(message.author.tag, message.author.displayAvatarUrl)
                .setDescription(helpMessage)
                .setColor('#e0c40b')
            message.channel.send(Embed)
                return
            }
            let counter = 0
            let allCommands = []
            commandsInCategory.map(command => {
                allCommands.push({
                    name: command.help.name,
                    description: command.help.description
                })
            })

            allCommands = generateHelpArray(allCommands)
            //for better display, we will display only 10 in page
            let Embed = new Discord.RichEmbed()
                Embed.setAuthor(message.author.tag, message.author.displayAvatarUrl)
                Embed.setDescription(`The list command of group : **${args.join(' ')}**`)
                allCommands[counter].map(command => {
                    Embed.addField(`**${command.name}**`,`${command.description}`,false)
                })
                Embed.setColor('#E8DB0E')
                Embed.setFooter(`Page ${counter+1} of ${allCommands.length}`)
                message.channel.send(Embed).then(msg => {
                    if(allCommands.length < 2) return
                    // To change page we will use react emoji 
                    msg.react(`◀️`).then(() => msg.react('▶️'))
                    const filter = (reaction, user) => {
                        return [`◀️`, '▶️'].includes(reaction.emoji.name) && user.id === message.author.id;
                    };
                    const collector = msg.createReactionCollector(filter, { max:50, time: 60000 });
                    collector.on('collect', (reaction, reactionCollector) => {
                        if (reaction.emoji.name === `◀️`) {
                            //Change counter, remove user reaction and call change embed function 
                            reaction.remove(message.author.id)
                            counter-=1
                            if(counter < 0) counter = 0
                            editEmbed(message, msg, counter, args.join(' '), allCommands)
                        } else if (reaction.emoji.name === `▶️`) {
                            //Change counter, remove user reaction and call change embed function 
                            reaction.remove(message.author.id)
                            counter+=1
                            if(counter >= allCommands.length) counter = allCommands.length -1
                            editEmbed(message, msg, counter, args.join(' '), allCommands)
                        }
                   });
                   collector.on('end', (reaction, reactionCollector) => {
                    msg.clearReactions()
                   })
                })

        }
    }

    module.exports.help = {
        name: "help",
        description: "Vous permet d'obtenir toutes les commandes accessibles pour vos rôles.",
        access: "Public",
        groups: "Outils"
    }




    const onlyUnique = (value, index, self) => { 
        return self.indexOf(value) === index;
    }


    const editEmbed = (message, msg, counter, category, allCommands) => {
        let Embed  = new Discord.RichEmbed()
            Embed.setAuthor(message.author.tag, message.author.displayAvatarURL)
            Embed.setDescription(`The list command of group : **${category}**`)
            Embed.setColor('#E8DB0E')
            allCommands[counter].map(command => {
                Embed.addField(`**${command.name}**`,`${command.description}`,false)
            })
            Embed.setFooter(`Page ${counter+1} of ${allCommands.length}`)
            msg.edit(Embed)
    }

    const generateHelpArray = (arr) => {
        let newArray = [];
        for (let i = 0; i < arr.length; i+=10) {
        newArray.push(arr.slice(i,i+10))
        }
        return newArray
    }
...