Record an entire conversation Discord.js - javascript

I want to record a entire conversation from Discord.JS v12. But, I'm don't really good in audio manipulation and other things like that.
I've this code :
const c = message.member.voice?.channel;
if(!c) {
// The user is not in voice channel
return message.channel.send("");
}
switch(args?.[0]?.toLowerCase()){
case 'on':
if(this.vocals.find(r => r.c === c.id && r.u === message.author.id)){
// The user have already an record launched
return message.channel.send("Vous avez déjà un enregistrement de démarré.");
}
const flux = await c.join();
const receiver = flux.receiver;
const audioChunk = this.createNewChunk((message.member.nickname || message.author.username).replace(/[^A-Za-z0-9]/g, ''));
this.vocals.push({
c: c.id,
u: message.author.id,
s: Date.now(),
r: audioChunk
});
flux.on('speaking', (user, speaking) => {
if (speaking) {
const audioStream = receiver.createStream(user, { mode: 'pcm' });
audioStream.on('data', (chunk) => audioChunk.write(chunk));
}
});
return message.channel.send("L'enregistrement a bien été lancé avec succès !")
break;
case 'off':
let f = this.vocals.find(r => r.c === c.id);
const channel = this.bot.channels.cache.get(f.c);
const members = channel.members.array();
f = this.vocals.find(r => r.c === c.id &&
(members.find(r => r.user.id === message.author.id) &&
r.u === message.author.id));
if(!f){
// The user doesnt have any record
return message.channel.send("Vous n'avez aucun enregistrement de démarré.");
}
console.log(f);
f.r.close();
return message.channel.send("L'enregistrement s'est bien terminé avec succès !", )
break;
default:
// const embed = ...
return message.channel.send(
this.help.usage.replace(/{prefix}/g, this.bot.config.prefix)
)
break;
}
And the createNewChunk function :
createNewChunk(name) {
return new wav.FileWriter(`./records/record-${name}.wav`);
}
But, when the users stop speaking in the channel, the record is stopped. Do you know how I can avoid this ?
Thanks you.

Okay, so It's really simple to do.
You have to create a audio chunck with Buffer. Then, detect when nobody is speaking. And you can push every 20ms your Buffer into the Stream.
const { Buffer } = require('buffer');
const emptyBuffer = Buffer.alloc(3840, 0); // You create a Buffer with a length of 3840, and a value to 0 (no sound).
Then, you have to put all your users into an array :
const users = [];
flux.on('speaking', (user, speaking) => {
if (speaking) {
users.push(user.id);
const audioStream = receiver.createStream(user, { mode: 'pcm' });
audioStream.on('end', () => {
users.splice(users.findIndex(r => r == user.id), 1); // Remove the users of users speaking array.
});
}
});
And THEN, you can add your buffer with no sound :
var emptyInterval = setInterval(() => {
if(users.length < 1){
audioChunk.write(emptyBuffer);
}
}, 20)
For stop the stream, stop clear the interval of emptyInterval and stop your event flux.on('speaking').
Works for nodejs v16 and more. I dont know if for nodejs v14 or lower it work.

Related

Discord anti nuke bot whitelist check error

i get error
let executor = await this.members.fetch(executorID);
^^^^^
SyntaxError: await is only valid in async function
when using the code below (use is to check if user breaks any of set filters and if so remove roles or ban user whatever they set option to)
ive tried my best to lable what parts of code does please not english isnt my first language
ive only recieved this error since trying to add a check whitelist feature - everything else works without the whitelist check code
without the code for whitelist the code works and performs as intended and the whitelist code succesfully logs ids for that guild
if(whitelisted && whitelisted.length) {
whitelisted.forEach(x => {
if (executorID === x.user) return;
const { Structures } = require('discord.js');
let whitelisted = db.get(`whitelist_${message.guild.id}`)
const { limits, defaultPrefix } = require('../config.js');
Structures.extend('Guild', Guild => {
class GuildExt extends Guild {
constructor(...args) {
super(...args);
}
get prefix() {
return this.get('prefix', defaultPrefix);
}
get(key, fallback) {
return this.client.db.get(`${this.id}_${key}`) || fallback;
}
set(key, data) {
return this.client.db.set(`${this.id}_${key}`, data);
}
delete(key) {
return this.client.db.delete(`${this.id}_${key}`);
}
resolveChannel(channelID) {
const channel = this.channels.cache.get(channelID);
return channel;
}
get limits() {
var obj = {};
for (var k in limits) {
obj[k] = {
minute: this.get(
`limits.${k}.minute`,
limits[k].per_minute
),
hour: this.get(`limits.${k}.hour`, limits[k].per_hour)
};
}
return obj;
}
getActions(limit = 10, filter = () => true) {
var obj = {};
var l = limits;
for (var k in limits) {
obj[k] = {
name: this.client.Utils.toProperCase(k),
actions: this.client.Utils.convertEntries(
[
...this.get(
this.client.Utils.convertLimitNameToActionType(
k
),
[]
),
...this.get(
`archive.${this.client.Utils.convertLimitNameToActionType(
k
)}`,
[]
)
]
.filter(filter)
.slice(0, limit)
)
};
}
return obj;
}
find_entry(action, filter) {
let guild = this;
return new Promise(resolve => {
(async function search(iter) {
//console.log(`ACTION = ${action} | ITER = ${iter}`);
if (!guild.me) return resolve(null);
if (guild.me.hasPermission('VIEW_AUDIT_LOG')) {
let logs = await guild.fetchAuditLogs({
limit: 10,
type: action
});
let entries = logs.entries;
let entry = null;
entries = entries.filter(filter);
for (var e of entries)
if (!entry || e[0] > entry.id) entry = e[1];
if (entry) return resolve(entry);
}
if (++iter === 5) return resolve(null);
else return setTimeout(search, 200, iter);
})(0);
});
}
push_entry(entry, displayName) {
const action = ['MEMBER_KICK', 'MEMBER_BAN_ADD'].includes(
entry.action
)
? 'MEMBER_REMOVE'
: entry.action;
const oneHourAgo = Date.now() - 1000 * 60 * 60;
// Fetch Entries for a sepcific action (Last Hour)
let entries = this.get(action, []);
// Filter entries older than one hour to a new variable
let olderThanOneHour = entries.filter(
i => !(i.timestamp > oneHourAgo)
);
// Prepend entries older than one hour to the archive
if (olderThanOneHour.length > 0)
this.set(`archive.${action}`, [
...olderThanOneHour,
...this.get(`archive.${action}`, [])
]);
// Filter entries older than one hour from old variable
entries = entries.filter(i => i.timestamp > oneHourAgo);
// Prepend new entry if not already found
if (
!entries.find(
i =>
i.target.id === entry.target.id &&
i.executor.id === entry.executor.id
)
)
entries.unshift({
timestamp: entry.createdTimestamp,
action: entry.action,
target: {
id: entry.target.id,
displayName,
targetType: entry.targetType
},
executor: {
id: entry.executor.id,
displayName: entry.executor.tag
}
});
// Update entries newer than one hour
return this.set(action, entries);
}
async check_limits(entries, executorID, configAction) {
// Ignore if executor is the owner or is whitelisted
if (executorID === this.ownerID) return;
if(whitelisted && whitelisted.length) {
whitelisted.forEach(x => {
if (executorID === x.user) retrun;
// Filter actions relating to executor
const oneMinuteAgo = Date.now() - 1000 * 60;
let executorActionsHour = entries.filter(
i => i.executor.id === executorID
);
let executorActionsMinute = executorActionsHour.filter(
i => i.timestamp > oneMinuteAgo
);
console.log(
`${configAction}/${executorID}: LAST_HOUR: ${executorActionsHour.length} LAST_MINUTE: ${executorActionsMinute.length} `
);
let limits = this.limits;
let limitReached = null;
if (executorActionsHour.length >= limits[configAction].hour)
limitReached = 'Hour';
if (executorActionsMinute.length >= limits[configAction].minute)
limitReached = 'Minute';
// Check if the amount of actions is greater than or equal to the limit
if (limitReached) {
// Remove all of the executor's roles
let executor = await this.members.fetch(executorID);
executor.roles.remove(executor.roles.cache);
// Handle managed roles
let managed = executor.roles.cache
.filter(r => r.managed)
.array();
for (var i = 0; i < managed.length; i++)
managed[i].setPermissions(0, 'Guardian Action');
// Notify owner, executor, and logging channel
const embed = this.client.util
.embed()
.setTitle(`Limit Reached - ${limitReached}`)
.setDescription(
this.client.Utils.convertEntries(
limitReached === 'Hour'
? executorActionsHour
: executorActionsMinute
)
)
.setColor(0x7289da);
await this.owner.send(
embed.setFooter(
"This message was sent to you because you're the Guild owner."
)
);
await executor.send(
embed.setFooter(
'This message was sent to you because you were the executor.'
)
);
const loggingChannel = this.resolveChannel(
this.get(`loggingChannelID`)
);
if (loggingChannel)
await loggingChannel.send(embed.setFooter(''));
}
})
}
}
}
return GuildExt;
});
i am new to JS and any help would be appreciated
please dont hate if i do have bad syntax !!
i am new - sorry if i dont get things the first time
You forgot to make your forEach function async, just change it to:
/* ... */
whitelisted.forEach(async (x) => {
/* ... */
let executor = await this.members.fetch(executorID);
/* ... */
}
/* ... */
Not part of your question but you misspelled return here
if (executorID === x.user) retrun;
Your line
let executor = await this.members.fetch(executorID);
is inside a non-async anonymous function in:
if (whitelisted && whitelisted.length) {
whitelisted.forEach(x => { // <- This line
if (executorID === x.user) return;
// ...
Try changing it with:
if (whitelisted && whitelisted.length) {
whitelisted.forEach(async (x) => { // <- Use async here
if (executorID === x.user) return;
// ...
Also, avoid using forEach to make asynchronous calls.

discord.js collector.on('end') not posting the collected things in the channel he supposed to

My Problem is that everything works fine but the collector doesnt send the hole thing in the channel i decided to. I give you here the full code so you can understand the system. But the Problem is only the collector.on(end) function.
The Error here is: https://imgur.com/7Zoff1D
I really tried everything but i dont know how to fix it. :)
if (reaction.emoji.name === "✅"){
const dmChannel = await reaction.message.guild.members.cache.get(user.id)
let embed = new Discord.MessageEmbed()
.setTitle('4D Artworks Bestellung')
.setDescription('Wähle bitte aus was du haben willst indem du unten reagierst. \n\n 1️⃣ » Einzeln auswählen \n 2️⃣ » Paket \n 3️⃣ » Blowjob')
.setColor('GREEN')
let msgEmbed = await dmChannel.send(embed)
msgEmbed.react('1️⃣')
msgEmbed.react('2️⃣')
msgEmbed.react('3️⃣')
}
}
if (reaction.emoji.name === '1️⃣') {
let embed = new Discord.MessageEmbed()
const questions = [`Sneertu1`, `Sneertu2`, `Sneertu3`];
const dmChannel = await user.send('**Willkommen, beantworte alle Fragen um eine Bestellung aufzugeben.**')
const collector = dmChannel.channel.createMessageCollector((msg) => msg.author.id == user.id);
let i = 0;
const res = [];
dmChannel.channel.send(questions[0])
collector.on('collect', async(msg) => {
if(questions.length == i) return collector.stop('MAX');
const answer = msg.content;
res.push({ question: questions[i], answer });
i++;
if(questions.length == i) return collector.stop('MAX');
else {
dmChannel.channel.send(questions[i]);
}
});
collector.on('end', async(collected, reason) => {
if(reason == 'MAX') {
if(reaction.guild.id === "809490902389227520"){
let channelId = '813887506256494692'
const data = client.channels.cache.get(channelId);
await data.send(`${reaction.message.guild.members.cache.get(user.id)} hat eine Bestellung abgegeben!\n\n${res.map(d => `**${d.question}** \n ${d.answer}`).join("\n\n")}`)
}
}
})
}

Discord js reaction not detected [duplicate]

This question already has answers here:
message event listener not working properly
(2 answers)
Closed 1 year ago.
There's something I don't understand with discordjs. I want to make a bot which lists people when they react on a message.
It partially works, when the guy who enter the commands (or who has enter a command before) reacts to the bot's message, the message edits immediately. But when it's someone who has never entered command, it didn't update.
const Discord = require('discord.js');
const client = new Discord.Client();
var auth = require('./auth.json');
const regexTime = new RegExp('^(0[0-9]|1[0-9]|2[0-3]|[0-9])([:|h])([0-5][0-9])?$');
var messageBot = "";
var time;
var timer;
var commandeValide=false;
var date = new Date;
var heureMs;
client.on('ready', () => {
console.log(client.guilds.fetch())
});
client.on('message', msg => {
if (msg.content.substring(0,1) === '!') {
var args = msg.content.substring(1).split(' ');
var cmd = args[0];
switch(cmd){
case 'amongus':
dateGame = args[1];
time = args[2];
messageBot = '#everyone Est-ce que des personne veulent faire un Among us à '+ time + ' le '+ dateGame;
if ( dateGame != undefined && time != undefined ){
var heure = time.split('h')[0] * 3600000;
var minute = time.split('h')[1] * 60000;
var temps = heure + minute;
heureMs = date.getHours() * 3600000 + date.getMinutes() * 60000;
if(regexTime.test(time) && isDate(dateGame)){
if(temps>heureMs){
commandeValide=true;
msg.channel.send(messageBot).then(sendMessage => {
sendMessage.react('✅')
});
timer = temps - heureMs;
}
}else{
msg.reply("Veuillez rentrer une heure ou une date valide!");
commandeValide=false;
}
}else{
msg.reply("Veuillez rentrer une heure et/ou une date s'il vous plaît! (exemple: !amongus 19/04 20h)");
commandeValide=false;
}
}
}
if(commandeValide){
const filter = (reaction, user) => {
console.log(client.users.cache);
//return ['✅'].includes(reaction.emoji.name);
return reaction.emoji.name === '✅' && user.id !== msg.author.id;
};
const collector = msg.createReactionCollector(filter, { dispose: true, time: timer }); //dispose: true permet d'utiliser remove
collector.on('collect', (reaction, user) => {
reaction.users.fetch().then((user) => {
updateMessage(user.array(),msg);
});
});
collector.on('remove', (reaction, user) => {
reaction.users.fetch().then((user) => {
updateMessage(user.array(),msg);
});
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} items`);
});
}
});
function updateMessage(tab, msg){
var listparticipant = "";
tab.forEach(user => {
if(user.id !== auth.server_id){
listparticipant += "- " + user.username + "\n";
}
})
msg.edit(messageBot + "\n" + listparticipant);
console.log(listparticipant);
}
client.login(auth.token);
Discord changed how much they emit events, make sure to put he proper intents on your bot and try again!
const client = new Discord.Client({
ws : {
intents: [
'GUILD_MEMBERS',
'GUILD_MESSAGES',
'GUILD_MESSAGE_REACTIONS' //<--- the intent you need to detect reactions on messages in a guild
]
}
});

Discord.js Bot giveaway command : embedSent.reactions.get is not a function

I am trying to make a Discord.js giveaway command that send an embed, save it to the variable embedSent then collect the reactions after the TimeOut with the reactions.get() method, but I keep getting the error TypeError: embedSent.reactions.get is not a function Here is the part of my code :
var embed = new Discord.MessageEmbed();
embed.setColor(0x3333ff);
embed.setTitle("Nouveau Giveaway !");
embed.setDescription("**" + item + "**");
embed.addField(`Durée : `, ms(ms(time), {
long: true
}), true);
embed.setFooter("Réagissez à ce message avec 🎉 pour participer !");
var embedSent = await message.channel.send(embed);
embedSent.react("🎉");
setTimeout(function () {
var peopleReacted = embedSent.reactions.get("🎉").users.filter(user => user.id !== client.user.id).array()
}, time);
Ok, after almost 2 months, I finally figured it out. The full, working command (DiscordJS v12) :
if (command == "giveaway") {
// !giveaway {time s/m/d} {item}
const messageArray = message.content.split(" ");
if (!message.member.hasPermission(["ADMINISTRATOR"])) return message.channel.send("You don't have enough permissions to start a giveaway !")
var item = "";
var time;
var winnerCount;
for (var i = 1; i < args.length; i++) {
item += (args[i] + " ");
}
time = args[0];
if (!time) {
return message.channel.send(`Invalid duration provided`);
}
if (!item) {
item = "No title"
}
var embed = new Discord.MessageEmbed();
embed.setColor(0x3333ff);
embed.setTitle("New Giveaway !");
embed.setDescription("**" + item + "**");
embed.addField(`Duration : `, ms(ms(time), {
long: true
}), true);
embed.setFooter("React to this message with 🎉 to participate !");
var embedSent = await message.channel.send(embed);
embedSent.react("🎉");
setTimeout(async () => {
try{
const peopleReactedBot = await embedSent.reactions.cache.get("🎉").users.fetch();
var peopleReacted = peopleReactedBot.array().filter(u => u.id !== client.user.id);
}catch(e){
return message.channel.send(`An unknown error happened during the draw of the giveaway **${item}** : `+"`"+e+"`")
}
var winner;
if (peopleReacted.length <= 0) {
return message.channel.send(`Not enough participants to execute the draw of the giveaway **${item}** :(`);
} else {
var index = Math.floor(Math.random() * peopleReacted.length);
winner = peopleReacted[index];
}
if (!winner) {
message.channel.send(`An unknown error happened during the draw of the giveaway **${item}**`);
} else {
console.log(`Giveaway ${item} won by ${winner.toString()}`)
message.channel.send(`🎉 **${winner.toString()}** has won the giveaway **${item}** ! Congratulations ! 🎉`);
}
}, ms(time));
}
Hope it helped some !
I guess this giveaway command works for me - Discord.js V13
don't forget to have npm i ms installed if you haven't already
const { Client, Intents, CommandInteraction, ReactionUserManager } = require('discord.js');
const INTENTS = new Intents(32767); // 32767 == full intents, calculated from intent calculator
const client = new Client({
intents: INTENTS
});
const Discord = require('discord.js');
const ms = require('ms') // make sure package ms is downloaded in console, to do this, simply type: npm i ms in your terminal
// https://www.npmjs.com/package/ms
client.once("ready" , () => {
console.log("I am online!")
});
client.on('messageCreate', async message => {
const prefix = "!" // this can be any prefix you want
let args = message.content.substring(prefix.length).split(" ")
// COMMAND FORMAT: !startgiveaway {duration} {winners} {#channel} {prize}
// E.g. !startgiveaway 24h 3w #giveaways Free Discord Nitro
if ((message.content.startsWith(`${prefix}startgiveaway`))) { // this condition can be changed to any command you'd like, e.g. `${prefix}gstart`
if (message.member.roles.cache.some(role => (role.name === 'Giveaway') )) { // user must have a role named Giveaway to start giveaway
let duration = args[1];
let winnerCount = args[2];
if (!duration)
return message.channel.send('Please provide a duration for the giveaway!\nThe abbreviations for units of time are: `d (days), h (hours), m (minutes), s (seconds)`');
if (
!args[1].endsWith("d") &&
!args[1].endsWith("h") &&
!args[1].endsWith("m") &&
!args[1].endsWith("s")
)
return message.channel.send('Please provide a duration for the giveaway!\nThe abbreviations for units of time are: `d (days), h (hours), m (minutes), s (seconds)`');
if (!winnerCount) return message.channel.send('Please provide the number of winners for the giveaway! E.g. `1w`')
if (isNaN(args[2].toString().slice(0, -1)) || !args[2].endsWith("w")) // if args[2]/winnerCount is not a number (even after removing end 'w') or args[2] does not end with 'w', condition returns:
return message.channel.send('Please provide the number of winners for the giveaway! E.g. `3w`');
if ((args[2].toString().slice(0, -1)) <= 0)
return message.channel.send('The number of winners cannot be less than 1!');
let giveawayChannel = message.mentions.channels.first();
if (!giveawayChannel || !args[3]) return message.channel.send("Please provide a valid channel to start the giveaway!")
let prize = args.slice(4).join(" ");
if (!prize) return message.channel.send('Please provide a prize to start the giveaway!');
let startGiveawayEmbed = new Discord.MessageEmbed()
.setTitle("🎉 GIVEAWAY 🎉")
.setDescription(`${prize}\n\nReact with 🎉 to participate in the giveaway!\nWinners: **${winnerCount.toString().slice(0, -1)}**\nTime Remaining: **${duration}**\nHosted By: **${message.author}**`)
.setColor('#FFFFFF')
.setTimestamp(Date.now() + ms(args[1])) // Displays time at which the giveaway will end
.setFooter("Giveaway ends");
let embedGiveawayHandle = await giveawayChannel.send({embeds: [startGiveawayEmbed]})
embedGiveawayHandle.react("🎉").catch(console.error);
setTimeout(() => {
if (embedGiveawayHandle.reactions.cache.get("🎉").count <= 1) {
return giveawayChannel.send("Nobody joined the giveaway :(")
}
if (embedGiveawayHandle.reactions.cache.get("🎉").count <= winnerCount.toString().slice(0, -1)) { // this if-statement can be removed
return giveawayChannel.send("There's not enough people in the giveaway to satisfy the number of winners!")
}
let winner = embedGiveawayHandle.reactions.cache.get("🎉").users.cache.filter((users) => !users.bot).random(winnerCount.toString().slice(0, -1));
const endedEmbedGiveaway = new Discord.MessageEmbed()
.setTitle("🎉 GIVEAWAY 🎉")
.setDescription(`${prize}\n\nWinner(s): ${winner}\nHosted By: **${message.author}**\nWinners: **${winnerCount.toString().slice(0, -1)}**\nParticipants: **${embedGiveawayHandle.reactions.cache.get("🎉").count - 1}**\nDuration: **${duration}**`)
.setColor('#FFFFFF')
.setTimestamp(Date.now() + ms(args[1])) // Displays time at which the giveaway ended
.setFooter("Giveaway ended");
embedGiveawayHandle.edit({embeds:[endedEmbedGiveaway]}); // edits original giveaway message to show that the giveaway ended successfully
const congratsEmbedGiveaway = new Discord.MessageEmbed()
.setDescription(`🥳 Congratulations ${winner}! You just won **${prize}**!`)
.setColor('#FFFFFF')
giveawayChannel.send({embeds: [congratsEmbedGiveaway]}).catch(console.error);
}, ms(args[1]));
} // end "Giveaway" role condition
}
})
client.login('INSERT YOUR BOT TOKEN HERE');

Loop for display help command

Actually, i try to create a bot with discord.js and i try to do a help command.
i don't understand why my loop do this (i know it's not a good way for this)
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++;
}
}
"Modérations" is supposed to display one command, "level & rank" too, "Outils" 4 command and "Sondage" too
enter image description here
I think you solutuion its not right way. If you will have more then 10 groups bot will spam commands list. The 1 way to do it its display all categories list if args.length===0, if args !==0 you try to find all commands in this category. To discord embed you can add only 18 fields, so if you have more then 18 command in categroy you will get api error. So you need spliced commands to pages.
This code will display all categories if args.length === 0, or command groups not fined.
If group fined bot send embed message with command in group (max 10), and react message if pages more then 1, so user can change page with reaction.
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
}

Categories