confused on forEach loop - discord.js

I am really confused on why this piece of code does not work how I intend it to work. Here is my code:
bot.on("message", async msg => {
if (msg.content.startsWith(`${prefix}apply`)) {
let ban = BannedArray.forEach(banned => {
if(msg.author.id === banned) {
msg.delete()
msg.channel.send("You are banned.")
}
})
if (msg.channel.id === "771665046514040833") {
var user = msg.content.split(" ").slice(1).join(" ")
const loading = new Discord.MessageEmbed()
.setTitle("Fetching your user ID...")
msg2 = await msg.channel.send(loading)
rapi.getUserIdFromUsername(user).then(async found => {
if (found === false) {
msg2.edit("test")
} else {
const found2 = new Discord.MessageEmbed()
.setTitle("User ID Found")
.setThumbnail(found.getAvatarBustImage)
.setDescription("We have found a User ID Linked to your account. It is: " + found.id + ". Is this you? \n [Click here to go to the profile](https://www.roblox.com/users/" + found.id + "/profile) \n \n ***PLEASE NOTE THAT IF YOU REACT WITH ✅ THAT YOUR ID WILL BE STORED FOR READING PURPOSES.***")
msg2.edit(found2)
msg.delete()
msg2.react('✅').then(r => {
msg2.react('❎');
});
msg2.awaitReactions((reaction, user) => user.id == msg.author.id && (reaction.emoji.name == '❎' || reaction.emoji.name == '✅'),
{ max: 1, time: 30000 }).then(async collected => {
if (collected.first().emoji.name == '❎') {
msg.reply("The ID has not been stored.")
}
if (collected.first().emoji.name == '✅') {
IDarray.push(`${found.id} || ${found.name}`)
console.log(found.id + " || " + found.name)
bot.channels.cache.get("771406620570943548").send("New ID pushed to table. Use `idarray` to see the full list. \n Roblox ID of user: " + found.id + " \n Roblox Name: " + found.name)
const check = new Discord.MessageEmbed()
.setTitle("Success")
.setDescription("Your ID has now been saved. Please open your DMs for this application so I can DM you. \n Question 1: \n Have you had experience with this job before?")
msg3 = await msg2.edit(check)
msg2.reactions.removeAll()
const filter = (m) => m.author.id === msg.author.id
msg3.channel.awaitMessages(filter, { max: 1, time: false })
.then(async collected => {
const msg = collected.first()
var Reply1 = msg.content.split(' ').slice(0).join(' ');
if (msg.content === `${Reply1}`) {
msg.delete()
const ques2 = new Discord.MessageEmbed()
.setTitle("Question 2")
.setDescription("Why should we choose you over other applicants?")
msg4 = await msg3.edit(ques2)
const filter2 = (m) => m.author.id === msg.author.id
msg4.channel.awaitMessages(filter2, { max: 1, time: false })
.then(async collected => {
const msg = collected.first()
var Reply2 = msg.content.split(' ').slice(0).join(' ');
if (msg.content === `${Reply2}`) {
msg.delete()
const ques3 = new Discord.MessageEmbed()
.setTitle("Question 3")
.setDescription("What are the basic things that a DJ needs to do?")
msg5 = await msg4.edit(ques3)
const filter3 = (m) => m.author.id === msg.author.id
msg5.channel.awaitMessages(filter3, { max: 1, time: false })
.then(async collected => {
const msg = collected.first()
var Reply3 = msg.content.split(' ').slice(0).join(' ');
if (msg.content === `${Reply3}`) {
msg.delete()
const ques4 = new Discord.MessageEmbed()
.setTitle("Question 4")
.setDescription("How active are you from 1-10?")
msg6 = await msg5.edit(ques4)
const filter4 = (m) => m.author.id === msg.author.id
msg6.channel.awaitMessages(filter4, { max: 1, time: false })
.then(async collected => {
const msg = collected.first()
var Reply4 = msg.content.split(' ').slice(0).join(' ');
if (msg.content === `${Reply4}`) {
msg.delete()
const ques5 = new Discord.MessageEmbed()
.setTitle("Question 5")
.setDescription("Why should we deem to trust you?")
msg7 = await msg6.edit(ques5)
const filter5 = (m) => m.author.id === msg.author.id
msg7.channel.awaitMessages(filter5, { max: 1, time: false })
.then(async collected => {
const msg = collected.first()
var Reply5 = msg.content.split(' ').slice(0).join(' ');
if (msg.content === `${Reply5}`) {
msg.delete()
const ques6 = new Discord.MessageEmbed()
.setTitle("Finished!")
.setDescription("You have completed the application and it is being held for review. To either send or delete the application, please go to your DMs.")
msg8 = await msg6.edit(ques6)
msg9 = await msg.author.send("Here are all your answers, " + found.name + ". \n \n **Question 1,** Have you had experience with this job before? \n" + Reply1 + " \n \n **Question 2,** Why should we choose you over other applicants? \n" + Reply2 + " \n \n **Question 3,** What are the basic things that a DJ needs to do? \n" + Reply3 + " \n \n **Question 4,** How active are you from 1-10? \n" + Reply4 + " \n \n **Question 5,** Why should we deem to trust you? \n" + Reply5 + " \n \n **Please choose to either send or delete the application below.**")
msg9.react('✅').then(r => {
msg9.react('❎');
});
msg9.awaitReactions((reaction, user) => user.id == msg.author.id && (reaction.emoji.name == '❎' || reaction.emoji.name == '✅'),
{ max: 1, time: false }).then(async collected => {
if (collected.first().emoji.name == '❎') {
msg9.reactions.removeAll()
msg9.edit("The application has not been sent.")
}
if (collected.first().emoji.name == '✅') {
const app = new Discord.MessageEmbed()
.setTitle("New application from `" + msg.author.username + "`")
.setDescription("Answers from: " + found.name + ". \n \n **Question 1,** Have you had experience with this job before? \n" + Reply1 + " \n \n **Question 2,** Why should we choose you over other applicants? \n" + Reply2 + " \n \n **Question 3,** What are the basic things that a DJ needs to do? \n" + Reply3 + " \n \n **Question 4,** How active are you from 1-10? \n" + Reply4 + " \n \n **Question 5,** Why should we deem to trust you? \n" + Reply5)
bot.channels.cache.get("771671063909761044").send(app)
msg9.edit("Your application has been sent! Keep an eye on the jobs channel to see if you passed!")
msg9.reactions.removeAll()
}
})
}
})
}
})
}
})
}
})
}
})
}
}).catch(() => {
msg.reply('No reaction after 30 seconds, operation canceled');
msg2.reactions.removeAll()
});
}
})
} else {
msg.delete()
msg.author.send("You can only use the command `--apply` in the application channel (<#771665046514040833>)")
}
}
})
In this script it checks to see if someone is banned but if they are, the command goes ahead. I do get an error saying this: DiscordAPIError: Unknown Message. I am really confused since I have used this method in other bots I have made. Could someone help me please?

Related

TypeError: Cannot read property 'toLowerCase' of undefined discord.js

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

DISCORD JS Vote + Coins [top.gg]

I am wanting to integrate the "vote" command of my bot, with the api of top.gg, I want something similar to the command below. this command is the "work" command of my bot, so that you have a base, I would like to modify it so that, when voting for my bot, it delivers "6k of coins" to the user who voted. do you have an explanation of how I can do it? I will leave my code for the work command below, so you can have an idea.
async run({ message, args, prefix, author }, t) {
if (!args[0]) {
User.findOne({ idU: message.author.id }, async (err, user) => {
let xp = Math.floor(Math.random() * 90) + 1;
let work = user.work.cooldown;
let cooldown = 1.44e7;
let money = Math.ceil(user.work.level * 2 * user.work.coins + 400);
let nextlevel = user.work.nextLevel * user.work.level;
if (work !== null && cooldown - (Date.now() - work) > 0) {
return message.quote(
`<:daily:842204620977864734> Você deve esperar **${moment
.duration(cooldown - (Date.now() - work))
.format("h [hora(s)], m [minuto(s)] e s [segundos]")
.replace("minsuto(s)", "minuto(s)")}** até poder trabalhar novamente`
);
} else {
if (user.work.exp + xp > nextlevel) {
message.quote(
`Parabéns, sua empresa acaba de subir para o level **${
user.work.level + 1
}**.`
);
await User.findOneAndUpdate(
{ idU: message.author.id },
{
$set: {
"work.cooldown": Date.now(),
"work.exp": 0,
coins: user.coins + money,
"work.level": user.work.level + 1,
},
}
);
} else {
message.quote(
`<:work:846536054399303700><:coins_k:846487970612903976> Você trabalhou com sucesso e obteve **${money.toLocaleString()} coins** e **${xp} de XP**.`
);
await User.findOneAndUpdate(
{ idU: message.author.id },
{
$set: {
"work.cooldown": Date.now(),
"work.exp":
user.work.exp + xp > nextlevel ? 0 : user.work.exp + xp,
coins: user.coins + money,
},
}
);
}
}
});
return;
}
You can check if the user has voted to your bot usinghttps://top.gg/api/bots/:bot_id/check?userId=userid endpoint
const fetch = require("node-fetch"); // import node-fetch module
const botId = client.user.id; // get the client (bot) id
const uId = message.author.id; // get the author id
const url = `https://top.gg/api/bots/${botId}/check?userId=${uId}`; // api endpoint
fetch(url, { method: "GET", headers: { Authorization: "your top.gg bot token" }})
.then((res) => res.text())
.then((json) => {
var isVoted = JSON.parse(json).voted;
if (isVoted === 0) {
return message.channel.send("you haven't voted yet");
}
message.channel.send("thank you for voting");
});
Note that this code is not perfect.
You can get your top.gg bot token from https://top.gg/bot/your-bot-id/webhooks
Source: https://docs.top.gg/api/bot/#individual-user-vote
By updating the post, I managed to get the desired result, I will leave the code below to others who have the same question!
const botId = client.user.id; //
const uId = message.author.id; // get the author id
const url = `https://top.gg/api/bots/${botId}/check?userId=${uId}`; // api endpoint
fetch(url, {
method: "GET", headers: { Authorization: "top.gg token" },
})
.then((res) => res.text())
.then((json) => {
let isVoted = JSON.parse(json).voted;
User.findOne({ idU: message.author.id }, async (err, user) => {
//================= Imports =================//
let cooldown = 4.68e7;
let coins = Math.floor(Math.random() * 5000);
let vote = user.vote;
let atual = user.coins;
let time = cooldown - (Date.now() - vote);
if (isVoted !== null && cooldown - (Date.now() - vote) > 0) {
return message.channel.send(`**Você já votou em mim hoje!**\n\nVolte em **${moment
.duration(time)
.format(
"h [Horas] m [Minutos] e s [Segundos]"
)}**`);
}
message.channel.send(`**Vote em mim em:** https://top.gg/bot/762320527637217312/vote **e receba até 5K de coins de forma aleatória!**`);
await User.findOneAndUpdate(
{ idU: message.author.id },
{ $set: { coins: coins + atual, vote: Date.now() } }
);
});
});

Discord.Js bot doesn't wait for a response

I made a announce command for my Discord.js v12 bot.
What happens when I run my command:
Here is my code:
// title
message.channel.send("What would be the title ?");
const titlecollector = new Discord.MessageCollector(
message.channel,
(m) => m.author.id === message.author.id,
{ time: 60000 }
);
// description
message.channel.send("What would be the description ?");
const descCollector = new Discord.MessageCollector(
message.channel,
(m) => m.author.id === message.author.id,
{ time: 180000 }
);
// ping
message.channel.send("Would I ping everyone, here or none ?");
const pingCollector = new Discord.MessageCollector(
message.channel,
(m) => m.author.id === message.author.id,
{ time: 60000 }
);
// channel
message.channel.send("Which channel should I send it to ?");
const channelCollector = new Discord.MessageCollector(
message.channel,
(m) => m.author.id === message.author.id,
{ time: 60000 }
);
// color
message.channel.send("What color should I use ?");
const colourCollector = new Discord.MessageCollector(
message.channel,
(m) => m.author.id === message.author.id,
{ time: 180000 }
);
// THE ANNONCEMENT
const announcementEmbed = new Discord.MessageEmbed()
.setTitle(collector)
.setDescription(descriptionCollector)
.setFooter(`Sent by ${message.member.user.tag}`);
const channel = Client.channels.cache.find(
(channel) => channel.name === channelCollector
);
if (pingCollector == "everyone") {
channel.send("#everyone");
} else if (pingCollector == "here") {
channel.send("#here");
}
channel.send(announcementEmbed);
I want it to wait for a response and then store that. What is wrong with my code?
You need to await the messages, instead of using a message collector.
//title
message.channel.send("Enter a title").then(() => {
const filter = m => m.author.id == message.author.id //this ensures that it's waiting messages from the person who sent the message
message.channel.awaitMessages(filter, {time: 60000, max: 1, errors: ['time']) //the time variable is the amount of milliseconds it should wait for, change this accordingly
.then(async messages => {
let title = messages.first().content
//description
message.channel.send("Enter a description!").then(() => {
message.channel.awaitMessages(filter, {time: 60000, max: 1, errors: ['time'])
.then(async messages2 => {
let description = messages2.first().content
}).catch(() => {
message.channel.send("You didn't enter anything!")
})
})
}).catch(() => {
message.channel.send("You didn't enter anything!")
})
})
And so on...

How can I change this script to kick user by user id?

I have this script for kicking users. How can I change that script so I can kick user by user id?
Script:
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";
client.on('message', function(message) {
if (!message.content.startsWith(prefix)) { return }
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "kick") {
let member = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (member) { // add this
member.kick(reason);
client.channels.cache.get('737341022782357566').send("User <#" + member.id +
"> with id " + member.id + " has been kicked by <#" + message.author.id +
"> with reason " + reason)
} else {
message.reply("invalid parameters for $kick")
}
message.delete();
}
})
client.login('token');
You'll have to get the member by ID:
const Member = message.guild.members.cache.get('MemberId')
if (!Member) return console.log(`Invalid member.`);
And then kick them:
Member.kick("Reason").catch(error => {
console.log(`Couldn't kick ${Member.user.tag}.`);
})

How to get a bot to read reactions of a specific message it sent?

I am trying to make an automatic system in which the bot has a timer and if it doesn't get enough reactions to the bot's message, it says one thing, but if the votes match, the other message is sent, I've got most of it working but I get an error with the "rpMessage.awaitReactions" line.
I've tried making the initial message a Const, a variable, a "let" and just message.awaitReactions
if(cmd === `${prefix}rp`) {
const rpMessage = message.channel.send("<#&608365714775998485> A Roleplay is being started by " + message.author + " React with :white_check_mark: to join / vote" + '\n' + "Just a few rules to remember:" + '\n \n' + "• Dont FRP as this will get you removed from the RP" + '\n' + "• Drive cars in your civ rank (You can find speeds if you click your name)" + '\n' + "• Listen to staff" + '\n' + "• Don't cop bait").then(rpvote => {
rpvote.react('👍').then(() => rpvote.react('👎'));})
const filter = (reaction, user) => {
return ['👍', '👎'].includes(reaction.emoji.name) && user.id === message.author.id;
};
rpMessage.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] }) // This part isn't working
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') {
message.reply('you reacted with a thumbs up.');
}
else {
message.reply('you reacted with a thumbs down.');
}
})
.catch(collected => {
console.log(`After a minute, only ${collected.size} out of 4 reacted.`);
message.reply('>rpfail.');
});
}
It's supposed to get the reactions from the message, but it never is able to read the property of awaitReacions
I am assuming the problem to be reusing code from stackoverflow question Discord.js message after receiving emoji reaction without updating the variables.
rpMessage.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] }) // This part isn't working
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') {
rpMessage.reply('you reacted with a thumbs up.');
}
else {
rpMessage.reply('you reacted with a thumbs down.');
}
})
.catch(collected => {
console.log(`After a minute, only ${collected.size} out of 4 reacted.`);
rpMessage.reply('>rpfail.');
});
}
The variable name is rPMessage for you and you have used message

Resources