As you can see I'm trying to do a list in form of an embed, where users can sign themselves in, via discord buttons. I already created the buttons and I thought with this code I could do what I wanted, but there are some problems. For example the first press on the buttons always results in a failed interaction. Or when someone else presses a button after I pressed one, he changes my name in the Array. And after some clicks the bot also crashes with the error "DiscordAPIError: Unknown interaction" at this function: "await i.update({ embeds: [newEmbed], components: [row] });". As I'm new to Programming and stuck for several days now, someone really needs to help me. This is the part of the code, that doesn't work how it should:
client.on('interactionCreate', async interaction => {
var users = [];
var buttonclicker = interaction.member.nickname
var greenbtnclicker = '🟢 ${buttonclicker}'
var yellowbtnclicker = '🟡 ${buttonclicker}'
const collector = interaction.channel.createMessageComponentCollector({ time: 2147483647 });
if(!interaction.isButton()) return;
collector.on('collect', async (i) => {
if (i.customId === 'green') {
if(users.indexOf(greenbtnclicker) == -1) {
if(users.indexOf(yellowbtnclicker) > -1) {
var int = users.indexOf(yellowbtnclicker)
users.splice(int, 1)
}
users.push(greenbtnclicker)
users.sort();
const newEmbed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription('Active Players: ${users.length}')
.setFooter('Footer')
for(var j=0;j < users.length; j++) {
newEmbed.addField('--------------------------------', users[j])
}
await i.update({ embeds: [newEmbed], components: [row] });
} else {
console.log('Already green')
}
} else if (i.customId === 'red') {
if(users.indexOf(yellowbtnclicker) != -1) {
var int = users.indexOf(yellowbtnclicker)
users.splice(int, 1)
const newEmbed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription('Active Players: ${users.length}')
.setFooter('Footer')
for(var j=0;j < users.length; j++) {
newEmbed.addField('--------------------------------', users[j])
}
await i.update({ embeds: [newEmbed], components: [row] });
} else if(users.indexOf(greenbtnclicker) != -1) {
var int = users.indexOf(greenbtnclicker)
users.splice(int, 1)
const newEmbed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription('Active Players: ${users.length}')
.setFooter('Footer')
for(var j=0;j < users.length; j++) {
newEmbed.addField('--------------------------------', users[j])
}
await i.update({ embeds: [newEmbed], components: [row] });
} else {
console.log('Already out')
}
} else if (i.customId === 'yellow') {
console.log(users)
if(users.indexOf(yellowbtnclicker) == -1) {
if(users.indexOf(greenbtnclicker) != -1) {
var int = users.indexOf(greenbtnclicker)
users.splice(int, 1)
}
users.push(yellowbtnclicker)
users.sort();
const newEmbed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription('Active Players: ${users.length}')
.setFooter('Footer')
for(var j=0;j < users.length; j++) {
newEmbed.addField('--------------------------------', users[j])
}
await i.update({ embeds: [newEmbed], components: [row] });
} else {
console.log('Already yellow')
}
}
});
});
I also have this before the essential code:
const { MessageActionRow, MessageButton, MessageEmbed} = require("discord.js");
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId("green")
.setStyle("SUCCESS")
.setLabel("green")
.setEmoji("🟢"),
new MessageButton()
.setCustomId("red")
.setStyle("DANGER")
.setLabel("red")
.setEmoji("🔴"),
new MessageButton()
.setCustomId("yellow")
.setStyle("SECONDARY")
.setLabel("yellow")
.setEmoji("🟡"),
);
client.once("messageCreate", async (msg) => {
if(msg.content.toLowerCase() == "!createrecord" && msg.guild && !msg.member.user.bot){
msg.delete()
var embed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription("No active players")
.setFooter("Footer")
msg.channel.send({ embeds: [embed], components: [row] })
}
})
It looks like you didn’t define row, try to define row
Try adding the following code
const {
MessageActionRow,
MessageButton
} = require('discord.js');
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId("buttonsid")
.setLabel('test!')
.setStyle('PRIMARY'),
);
Related
const Invites = new Collection();
const guildInvites = new Map()
client.on('inviteCreate', async invite => {
const invites = await invite.guild.invites.fetch();
const codeUses = new Map();
invites.each(inv => codeUses.set(inv.code, inv.uses, inv.inviter));
guildInvites.set(invite.guild.id, codeUses);
})
client.once('ready', () => {
client.guilds.cache.forEach(guild => {
guild.invites.fetch()
.then(invites => {
const codeUses = new Map();
invites.each(inv => codeUses.set(inv.code, inv.uses, inv.inviter));
guildInvites.set(guild.id, codeUses);
})
.catch(err => {
console.log("OnReady Error:", err)
})
})
})
client.on('guildMemberAdd', async member => {
const cachedInvites = guildInvites.get(member.guild.id)
const newInvites = await member.guild.invites.fetch();
try {
const usedInvite = newInvites.find(inv => cachedInvites.get(inv.code) < inv.uses < inv.inviter);
const embed0 = new MessageEmbed()
.setTitle("Invite Logs")
.setColor("GREEN")
.setDescription(`Ο/Η ${member} (${member.user.username}) μπήκε στον server από την πρόσκληση (${usedInvite.code || "δεν υπάρχει πλέον"}) του ${usedInvite.inviter} (${usedInvite.inviter.username}) **αλλά είναι Fake**`)
var fake22 = (Date.now() - member.user.createdAt < 1000*60*60*config.invite_faketime*1) //return client.channels.cache.get(config.invite_logs).send({embeds: [embed0] }),db.add(`total_${usedInvite.inviter.id}`, 1),db.add(`fake_${usedInvite.inviter.id}`, 1)
const embed = new MessageEmbed()
.setTitle("Invite Logs")
.setColor("GREEN")
.setDescription(`Ο/Η ${member} (${member.user.username}) μπήκε στον server από την πρόσκληση (${usedInvite.code || "δεν υπάρχει πλέον"}) του ${usedInvite.inviter} (${usedInvite.inviter.username})`)
client.channels.cache.get(config.invite_logs).send({embeds: [embed] })
if (usedInvite.inviter) {
db.set(`invites_${member.guild.id}.${member.id}.inviter`, usedInvite.inviter.id);
if (fake22) {
total = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.total`, 1);
_fake = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.fake`, 1);
}
else {
total = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.total`, 1);
regular = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.regular`, 1);
}}
//console.log(`The code ${usedInvite.code} was just used by ${member.user.username}. ${usedInvite.inviter.username}`)
} catch(err) {
}
newInvites.each(inv => cachedInvites.set(inv.code, inv.uses));
guildInvites.set(member.guild.id, cachedInvites);
});
**
we have user 1
user 2
user 3
i am user 1
i invite user 2 and i see in logs that user 1 invites user 2
but after i make invite link from user 2 and i invite user 3
but i see in logs tha user 1 invites user 3
**
can someone help me to cashed the right invite ?
I'm creating a message with buttons as reaction roles but do the reaction role handling in another file so it stays loaded after a reset but it either says "interaction.deferUpdate() is not a function, or in discord it says "this interaction failed" but it gave/removed the role
my code for creating the message:
const { ApplicationCommandType, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
name: 'role',
description: "reactionroles",
cooldown: 3000,
userPerms: ['Administrator'],
botPerms: ['Administrator'],
run: async (client, message, args) => {
const getButtons = (toggle = false, choice) => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('member')
.setCustomId('member')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
new ButtonBuilder()
.setLabel('member2')
.setCustomId('member2')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
);
return row;
}
const embed = new EmbedBuilder()
.setTitle('Wähle eine rolle')
.setDescription('Wähle die rolle, die du gern haben möchtest')
.setColor('Aqua')
message.channel.send({ embeds: [embed], components: [getButtons()] })
.then((m) => {
const collector = m.createMessageComponentCollector();
collector.on('collect', async (i) => {
if (!i.isButton()) return;
await i.deferUpdate();
});
});
}
};
code for the reaction role:
const fs = require('fs');
const chalk = require('chalk')
var AsciiTable = require('ascii-table')
var table = new AsciiTable()
const discord = require("discord.js");
table.setHeading('Events', 'Stats').setBorder('|', '=', "0", "0")
module.exports = (client) => {
client.ws.on("INTERACTION_CREATE", async (i) => {
let guild = client.guilds.cache.get('934096845762879508');
let member = await guild.members.fetch(i.member.user.id)
let role = guild.roles.cache.find(role => role.name === i.data.custom_id);
if (!member.roles.cache.has(role.id)) {
member.roles.add(role);
} else {
member.roles.remove(role);
}
return i.deferUpdate()
})
};
The client.ws events give raw data (not discord.js objects), so the .deferUpdate() method doesn't exist there. You should be using client.on("interactionCreate")
client.on("interactionCreate", async (i) => {
// ...
return i.deferUpdate()
})
I am getting the interaction has already been acknowledged error. Basically when the command is called the first time, the button and the modal work just fine. The second time, the button appears but then shows the modal and throws the "DiscordAPIError: Interaction has already been acknowledged." error. I am in a real slump.
} else if (order == "edit") {
let shelfNameSpaces = "";
for (let i = 1; i < args.length; i++) {
shelfNameSpaces += args[i] + " ";
}
let shelfName = shelfNameSpaces.trim();
let shelfObj = await Shelves.findOne({name: shelfName})
if (shelfObj) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setThumbnail(profileImage)
.setTitle(`${shelfObj["name"]}`)
.setDescription("Displaying shelf info")
.addField("Owner", `<#${shelfObj["owner"]}>`)
if (shelfObj["info"].length <= 0) {
embed.addField("Info", "No information added")
} else {
embed.addField("Info", shelfObj["info"])
}
let m = await message.channel.send({ embeds: [embed] })
const row = new MessageActionRow();
row.addComponents(
new MessageButton()
.setCustomId(`edit-shelf`)
.setLabel('Edit Shelf')
.setStyle("PRIMARY")
)
var buttons = await message.channel.send({ components: [row] })
setTimeout(() => {
if (buttons.deletable)
buttons.delete()
}, 60000);
// client.on("interactionCreate", async (interaction) => {
// module.exports = {
// name: 'interactionCreate',
// async execute (interaction) {
// }
// }
var editInfo, modal, editRow;
client.on("interactionCreate", async (interaction) => {
if (!interaction.isButton() || interaction.isModalSubmit()) return;
if (interaction.customId == "edit-shelf") {
// interaction.reply("Editing")
if (buttons.deletable)
buttons.delete()
modal = new Modal()
.setCustomId(`editModal`)
.setTitle('Edit Info')
editInfo = new TextInputComponent()
.setCustomId(`editInput`)
.setLabel("Input your edit")
.setValue(shelfObj["info"])
.setStyle("PARAGRAPH")
editRow = new MessageActionRow().addComponents(editInfo)
modal.addComponents(editRow)
await interaction.showModal(modal)
modalCheck++;
}
})
client.on("interactionCreate", async (inter) => {
if (!inter.isModalSubmit()) return;
inter.deferUpdate()
const editval = inter.fields.getTextInputValue('editInput')
// console.log(editval);
shelfObj["info"] = editval
const updatedShelf = new Shelves(shelfObj);
await updatedShelf.save()
const embed2 = new MessageEmbed()
.setColor("#0099ff")
.setThumbnail(profileImage)
.setTitle(`${shelfObj["name"]}`)
.setDescription("Displaying shelf info")
.addField("Owner", `<#${shelfObj["owner"]}>`)
if (shelfObj["info"].length <= 0) {
embed2.addField("Info", "No information added")
} else {
embed2.addField("Info", shelfObj["info"])
}
m.edit({ embeds: [embed2] })
// inter.reply("Shelf edited successfully")
// await inter.deleteReply()
// if (buttons.deletable)
// buttons.delete()
})
} else {
const embed = new MessageEmbed()
.setColor("#ff0000")
.setTitle("Shelves")
.setDescription("Unknown Shelf")
.addField("Error", "Shelf not found");
message.channel.send({ embeds: [embed] });
}
I've experienced this error multiple times, and I finally found out how to fix this error.
To start off, you need to install a package called nanoid (npm i nanoid in terminal).
At the top of your file, include const { nanoid } = require("nanoid");. This package is used for creating unique IDs for anything you'd like.
now, make a variable, and make it the following:
let id = `button-${nanoid()}`;
Make your .setCustomId() equal .setCustomId(id).
Lastly, make your if (interaction.customId == "edit-shelf") equal if (interaction.customId == id).
Note: If you have another error, try changing your nanoid package in your package.json to version ^3.3.4, and uninstall and install it again.
I'm developing a discord.js moderation bot, but when I run it I get this error.
Here is the code:
var Discord = require('discord.js')
const fs = require("fs")
const { PREFIX } = require("../../config")
const db = require('quick.db')
const { stripIndents } = require("common-tags");
module.exports = {
config: {
name: "help",
description: "Help Menu",
usage: "1) m/help \n2) m/help [module name]\n3) m/help [command (name or alias)]",
example: "1) m/help\n2) m/help utility\n3) m/help ban",
aliases: ['h']
},
run: async (bot, message, args) => {
let prefix;
if (message.author.bot || message.channel.type === "dm") return;
try {
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched == null) {
prefix = PREFIX
} else {
prefix = fetched
}
} catch (e) {
console.log(e)
};
if(message.content.toLowerCase() === `${prefix}help`){
var log = new Discord.MessageEmbed()
.setTitle("**Help Menu: Main**")
.setColor(`#d9d9d9`)
.addField(`**👑Moderation**`, `[ \`${prefix}help mod\` ]`, true)
.addField(`**⚙️Utility**`, `[ \`${prefix}help utility\` ]`, true)
message.channel.send(log);
}
else if(args[0].toLowerCase() === "mod") {
var commandArray = "1) Ban \n2) Kick\n3) Whois\n4) Unban\n5) Warn\n6) Mute\n7) Purge\n8) Slowmode \n9) Nick \n10) Roleinfo"
var commandA2 = "11) Rolememberinfo\n12) Setmodlog\n13) Disablemodlog\n14) Lock (Lock the channel)\n15) Unlock (Unlock the channel)\n16) Lockdown (Fully Lock the whole server. [FOR EMRGENCIES ONLY]) \n17) Hackban\\forceban <id>"
pageN1 = "**\n💠Commands: **\n`\`\`js\n" + commandArray + "\`\`\`";
pageN2 = "**\n💠Commands: **\n`\`\`js\n" + commandA2 + "\`\`\`";
let pages = [pageN1, pageN2]
let page = 1
var embed = new Discord.MessageEmbed()
.setTitle('**Help Menu: [Moderation]👑**')
.setColor("#d9d9d9") // Set the color
.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
.setDescription(pages[page-1])
message.channel.send({embed}).then(msg => {
msg.react('⬅').then( r => {
msg.react('➡')
// Filters
const backwardsFilter = (reaction, user) => reaction.emoji.name === '⬅' && user.id === message.author.id
const forwardsFilter = (reaction, user) => reaction.emoji.name === '➡' && user.id === message.author.id
const backwards = msg.createReactionCollector(backwardsFilter, {timer: 6000})
const forwards = msg.createReactionCollector(forwardsFilter, {timer: 6000})
backwards.on('collect', (r, u) => {
if (page === 1) return r.users.remove(r.users.cache.filter(u => u === message.author).first())
page--
embed.setDescription(pages[page-1])
embed.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
msg.edit(embed)
r.users.remove(r.users.cache.filter(u => u === message.author).first())
})
forwards.on('collect', (r, u) => {
if (page === pages.length) return r.users.remove(r.users.cache.filter(u => u === message.author).first())
page++
embed.setDescription(pages[page-1])
embed.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
msg.edit(embed)
r.users.remove(r.users.cache.filter(u => u === message.author).first())
})
})
})
}
else if(args[0].toLowerCase() === "util") {
var embed = new Discord.MessageEmbed()
.setTitle('**Help Menu: [Utility]**')
.setColor("#d9d9d9") // Set the color
.setDescription("```js" + `1) Prefix [${prefix}help prefix for more info]\n 2) Help [${prefix}help for more info]` + "```")
} else {
const embed = new Discord.MessageEmbed()
.setColor("#d9d9d9")
.setAuthor(`${message.guild.me.displayName} Help`, message.guild.iconURL())
.setThumbnail(bot.user.displayAvatarURL())
let command = bot.commands.get(bot.aliases.get(args[0].toLowerCase()) || args[0].toLowerCase())
if (!command) return message.channel.send(embed.setTitle("**Invalid Command!**").setDescription(`**Do \`${prefix}help\` For the List Of the Commands!**`))
command = command.config
embed.setDescription(stripIndents`
** Command -** [ \`${command.name.slice(0, 1).toUpperCase() + command.name.slice(1)}\` ]\n
** Description -** [ \`${command.description || "No Description provided."}\` ]\n
** Usage -** [ \`${command.usage ? `\`${command.usage}\`` : "No Usage"}\` ]\n
** Examples -** [ \`${command.example ? `\`${command.example}\`` : "No Examples Found"}\` ]\n
** Aliases -** [ \`${command.aliases ? command.aliases.join(" , ") : "None."}\` ]`)
embed.setFooter(message.guild.name, message.guild.iconURL())
return message.channel.send(embed)
}
}
}
If someone could help with this issue it would be great because I don't know what to do. I already searched on internet but I still don't know what I need to do to solve this error. All this code is for help function, when someone calls -pks help the bot should show embed telling all his functions
Here is my index.js file:
const { Client, Collection } = require('discord.js');
const { PREFIX, TOKEN } = require('./config');
const bot = new Client({ disableMentions: 'everyone' });
const fs = require("fs");
const db = require('quick.db');
bot.commands = new Collection();
bot.aliases = new Collection();
["aliases", "commands"].forEach(x => bot[x] = new Collection());
["console", "command", "event"].forEach(x => require(`./handler/${x}`)(bot));
bot.categories = fs.readdirSync("./commands/");
["command"].forEach(handler => {
require(`./handler/${handler}`)(bot);
});
bot.on('message', async message => {
let prefix;
try {
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched == null) {
prefix = PREFIX
} else {
prefix = fetched
}
} catch {
prefix = PREFIX
};
try {
if (message.mentions.has(bot.user.id) && !message.content.includes("#everyone") && !message.content.includes("#here")) {
message.channel.send(`\nMy prefix for \`${message.guild.name}\` is \`${prefix}\` Type \`${prefix}help\` for help`);
}
} catch {
return;
};
});
bot.login(TOKEN);
So I am making a bot where it can play music and I wanted to have a Music Quiz command (Music getting play and you need to find the name and/or authors). I wrote the code but it get stuck at What is the number of songs you want the quiz to have?. I can't find the issue (Also I get no error).
Here is the code:
const { MessageEmbed } = require('discord.js');
const ytdl = require('ytdl-core');
const { PREFIX } = require('../../config')
const musictriviajson = require('../../JSON/musictrivia.json')
const db = require('quick.db');
module.exports = {
config: {
name: 'musictrivia',
category: 'music',
aliases: ['musicquiz', 'mt'],
description: "Music Trivia for You",
usage: "[amount of songs]",
accessableby: "everyone"
},
run: async (bot, message, args, ops) => {
let prefix;
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched === null) {
prefix = PREFIX
} else {
prefix = fetched
}
const noperm = new MessageEmbed()
.setColor("GREEN")
.setDescription("**❌ You do not have permissions to add money!**")
if (!message.member.hasPermission("CONNECT", "SPEAK")) return message.channel.send(noperm)
const serverQueue = ops.queue.get(message.guild.id)
if (serverQueue) return message.channel.send("Cannot Play Music Trivia While Music is Playing!")
const triviaData = {
isTriviaRunning: false,
wasTriviaEndCalled: false,
triviaQueue: [],
triviaScore: new Map()
};
ops.queue2.set(message.guild.id, triviaData)
var { channel } = message.member.voice;
const channeljoin = new MessageEmbed()
.setColor("GREEN")
.setDescription("**Please Join A VC To Play Music Trivia!**")
if (!channel)
return message.channel.send(channeljoin);
if (serverQueue && serverQueue.playing)
return message.channel.send('**A quiz or a song is already running!**');
triviaData.isTriviaRunning = true;
if (!args[0]) return message.channel.send("**What is the number of songs you want the quiz to have?**")
if (args[0] >= 5 && args[0] <= 15) {
var videoDataArray = musictriviajson.songs;
const randomXVideoLinks = getRandom(videoDataArray, args[0]);
const infoEmbed = new MessageEmbed()
.setColor('GREEN')
.setTitle('Starting Music Quiz')
.setDescription(
`Get ready! There are ${args[0]} songs, you have 30 seconds to guess either the singer/band or the name of the song. Good luck!
You can end the trivia at any point by using the end-trivia command`
);
message.channel.send(infoEmbed);
for (let i = 0; i < randomXVideoLinks.length; i++) {
const song = {
url: randomXVideoLinks[i].url,
singer: randomXVideoLinks[i].singer,
title: randomXVideoLinks[i].title,
voiceChannel: channel
};
triviaData.triviaQueue.push(song);
}
const channelInfo = Array.from(
message.member.voice.channel.members.entries()
);
channelInfo.forEach(user => {
if (user[1].user.bot) return;
triviaData.triviaScore.set(user[1].user.username, 0);
});
} else {
return message.channel.send("**Please enter a number between 5 and 15**")
}
playQuizSong(triviaData.triviaQueue, message);
async function playQuizSong(queue, message) {
const queueConstruct = {
textChannel: message.channel,
voiceChannel: channel,
connection: null,
songs: [],
volume: 2,
playing: true,
loop: false
};
ops.queue3.set(message.guild.id, queueConstruct)
try {
const connection = await queue[0].voiceChannel.join();
queueConstruct.connection = connection
const dispatcher = connection
.play(
ytdl(queue[0].url, {
quality: 'highestaudio',
highWaterMark: 1 << 20
})
)
.on('start', function() {
dispatcher.setVolume(queueConstruct.volume);
let songNameFound = false;
let songSingerFound = false;
const filter = m =>
triviaData.triviaScore.has(m.author.username);
const collector = message.channel.createMessageCollector(filter, {
time: 30000
});
collector.on('collect', m => {
if (!triviaData.triviaScore.has(m.author.username))
return;
if (m.content.startsWith(prefix)) return;
if (m.content.toLowerCase() === queue[0].title.toLowerCase()) {
if (songNameFound) return;
songNameFound = true;
if (songNameFound && songSingerFound) {
triviaData.triviaScore.set(
m.author.username,
triviaData.triviaScore.get(m.author.username) +
1
);
m.react('✅');
return collector.stop();
}
triviaData.triviaScore.set(
m.author.username,
triviaData.triviaScore.get(m.author.username) + 1
);
m.react('✅');
}
else if (
m.content.toLowerCase() === queue[0].singer.toLowerCase()
) {
if (songSingerFound) return;
songSingerFound = true;
if (songNameFound && songSingerFound) {
triviaData.triviaScore.set(
m.author.username,
triviaData.triviaScore.get(m.author.username) +
1
);
m.react('✅');
return collector.stop();
}
triviaData.triviaScore.set(
m.author.username,
triviaData.triviaScore.get(m.author.username) + 1
);
m.react('✅');
} else if (
m.content.toLowerCase() ===
queue[0].singer.toLowerCase() +
' ' +
queue[0].title.toLowerCase() ||
m.content.toLowerCase() ===
queue[0].title.toLowerCase() +
' ' +
queue[0].singer.toLowerCase()
) {
if (
(songSingerFound && !songNameFound) ||
(songNameFound && !songSingerFound)
) {
triviaData.triviaScore.set(
m.author.username,
triviaData.triviaScore.get(m.author.username) +
1
);
m.react('✅');
return collector.stop();
}
triviaData.triviaScore.set(
m.author.username,
triviaData.triviaScore.get(m.author.username) + 2
);
m.react('✅');
return collector.stop();
} else {
return m.react('❌');
}
});
collector.on('end', function() {
if (triviaData.wasTriviaEndCalled) {
triviaData.wasTriviaEndCalled = false;
return;
}
const sortedScoreMap = new Map(
[...triviaData.triviaScore.entries()].sort(
(a, b) => b[1] - a[1]
)
);
const song = `${capitalize_Words(
queue[0].singer
)}: ${capitalize_Words(queue[0].title)}`;
const embed = new MessageEmbed()
.setColor('GREEN')
.setTitle(`**The song was - ${song}**`)
.setDescription(
getLeaderBoard(Array.from(sortedScoreMap.entries()))
);
message.channel.send(embed);
queue.shift();
dispatcher.end();
return;
});
})
.on('finish', function() {
if (queue.length >= 1) {
return playQuizSong(queue, message);
} else {
if (triviaData.wasTriviaEndCalled) {
queueConstruct.playing = false;
triviaData.isTriviaRunning = false;
queueConstruct.connection = null;
message.guild.me.voice.channel.leave();
return;
}
const sortedScoreMap = new Map(
[...triviaData.triviaScore.entries()].sort(
(a, b) => b[1] - a[1]
)
);
const embed = new MessageEmbed()
.setColor('GREEN')
.setTitle(`**Music Quiz Results\n\n**`)
.setDescription(
getLeaderBoard(Array.from(sortedScoreMap.entries()))
);
message.channel.send(embed);
queueConstruct.playing = false;
triviaData.isTriviaRunning = false;
triviaData.triviaScore.clear();
queueConstruct.connection = null;
message.guild.me.voice.channel.leave();
return;
}
});
} catch (e) {
console.error(e);
ops.queue.delete(message.guild.id)
await channel.leave();
return message.channel.send("**Something Went Wrong!**");
}
}
function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError('getRandom: more elements taken than available');
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}
function getLeaderBoard(arr) {
if (!arr) return;
let leaderBoard = '';
leaderBoard = `👑 **${arr[0][0]}:** ${arr[0][1]} points`;
if (arr.length > 1) {
for (let i = 1; i < arr.length; i++) {
leaderBoard =
leaderBoard + `\n\n ${i + 1}: ${arr[i][0]}: ${arr[i][1]} points`;
}
}
return leaderBoard;
}
function capitalize_Words(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
}
};
Thanks in advance!