discord.js RichEmbed issue - discord.js

I want the bot to download data from the MySQL database and add appropriate fields to the embed, and after entering the command, it sends an empty embed. There are no errors in output.
My code:
const { RichEmbed } = require("discord.js");
module.exports = {
name: "support",
category: "Bot",
description: "wyświetla ekipe bota",
usage: `support`,
run: async (client, message, connection) => {
var embed = new RichEmbed()
connection.query(`SELECT id FROM support WHERE ranga = '1'`, (err, rows) => {
if(err) throw err;
if (rows.length < 1) return;
for (const element of rows) {
osoba = client.users.find(user => user.id == `${element.id}`);
embed.addField("Główny Developer", `${osoba.tag}`)
}
})
connection.query(`SELECT id FROM support WHERE ranga = '2'`, (err, rows) => {
if(err) throw err;
if (rows.length < 1) return;
for (const element of rows) {
osoba = client.users.find(user => user.id == `${element.id}`);
embed.addField("Developer", `${osoba.tag}`)
}
})
connection.query(`SELECT id FROM support WHERE ranga = '3'`, (err, rows) => {
if(err) throw err;
if (rows.length < 1) return;
for (const element of rows) {
osoba = client.users.find(user => user.id == `${element.id}`);
embed.addField("Support", `${osoba.tag}`)
}
})
connection.query(`SELECT id FROM support WHERE ranga = '4'`, (err, rows) => {
if(err) throw err;
if (rows.length < 1) return;
for (const element of rows) {
osoba = client.users.find(user => user.id == `${element.id}`);
embed.addField("Grafik", `${osoba.tag}`)
}
})
message.channel.send(embed);
}}

I believe if you are using v12, the rich embed is now MessageEmbed.
EDIT I never really explained it clearly, sorry. Change RichEmbed to MessageEmbed

Related

How to fix this.uuid is not a function discord.js

Hello actually I wanted to make minecraft playerinfo command but I wanted it and I got it on github it was a bit old but I tried to convert it to discord.js v14 code. But I got this error.
TypeError: this.getUuid is not a function
Can you help me please heres the original code: https://github.com/Jystro/Minecraft-info-bot/blob/master/commands/player.js
const mojang = require('mojang-api');
const https = require('https');
const {
EmbedBuilder
} = require('discord.js');
module.exports = {
name: 'playerinfo',
description: 'Diplays player\'s name, uuid, skin, cape and name history',
run: async (client, message, args) => {
//check that a value is sent
if(!args.length) {
message.reply('please specify the player\'s uuid');
return;
}
let uuid = args[0]
//get uuid
this.getUuid(args[0], (err, uuid) => {
if(err) {
message.channel.send('An error occurred. This might be because the player does not exist');
return;
}
//check that uuid exists
mojang.profile(uuid, (err, resp) => {
if(err) {
message.reply('that player\'s uuid does not exist');
return;
}
//get name history
mojang.nameHistory(uuid, (err, resp1) => {
if(err) {
message.reply('there was an error trying to retrieve the data');
console.log(err);
return;
}
let nameHistory = [];
resp1.forEach(element => {
nameHistory.push(element.name);
});
nameHistory = nameHistory.join(', ');
//create embed message
const embedMessage = new EmbedBuilder()
.setColor('Random')
.setTitle(resp.name)
.setDescription(resp.name + "'s profile")
.setThumbnail('https://crafatar.com/avatars/' + resp.id + '.png?overlay')
.addFields(
{
name: 'Name',
value: resp.name
},
{
name: 'UUID',
value: resp.id
},
{
name: 'Skin',
value: 'https://crafatar.com/skins/' + resp.id + '.png'
})
.setImage('https://crafatar.com/renders/body/' + resp.id + '.png?overlay')
//check if cape exists
let cape = 'https://crafatar.com/capes/' + resp.id + '.png';
const req = https.request(cape, res => {
if(res.statusCode == 200) {
embedMessage.fields.push({ name: 'Cape', value: cape });
}
embedMessage.fields.push({ name: 'Name history', value: nameHistory });
//send embed
message.channel.send({ embed: embedMessage });
});
req.on('error', err => {
console.log(err);
message.reply('there was an error while retrieving the cape');
})
req.end();
});
});
})
},
//function to get uuid from uuid/name
getUuid(value, cb) {
let error = false;
let regex = /^[a-f0-9]{32}$/i //regex for uuids
if(!value.match(regex)) {
mojang.nameToUuid(value, (err, resp) => {
if(err || !resp.length) {
error = true;
cb(error, null);
return;
}
cb(error, resp[0].id);
});
}
else { cb(error, value); }
}
}
The issue is your usage of the this keyword and arrow functions.
The main takeaway is this:
Arrow functions don't redeclare this, while anonymous functions do.
This means that when you call the run() method somewhere else in the code, the this keyword in the run method will refer to whatever this is in the current context of where it was executed, which isn't what you want.
To redeclare this to your object, you should rewrite your arrow function as an anonymous function.
module.exports = {
run: async function(client, message, args) {
// you can now safely use `this` in this method
}
}

Making only admins execute commands

The problem is that I couldn't figure out a way to make this command only accessible by admins. I've tried using if statements, however, I failed. message. I am not sure if member. roles. cache. has( ' 732524984777572363 ' ) would allow members with the role ID 732524984777572363 to execute it since there's already an if statement.
const Discord = require('discord.js');
const fs = require('fs');
const cooldown = new Set();
module.exports.run = async (client, msg, args, config) => {
if(cooldown.has(msg.author.id)) {
msg.reply(`You need to wait ${config.COOLDOWN} minutes to use this command again!`)
.then((m) => {
msg.delete();
setTimeout(() => {
m.delete();
}, 5000);
});
} else {
fs.readFile('./accounts/crunchy.txt', 'utf8', function(err, data) {
if (err) throw err;
data = data + '';
var lines = data.split('\n');
let account = lines[Math.floor(Math.random() * 1)];
fs.writeFile('./accounts/crunchy.txt', lines.slice(1).join('\n'), function(err) {
if(err) throw err;
});
let embed = new Discord.RichEmbed()
.addField('Rate Us Here | قيمنا هنا ', `<#915***********80>`)
.addField('CrunchyRoll Account',`\n**${account}**`)
.setThumbnail('**************************')
.setColor("#363940")
.setFooter('Bot made by ******')
.setTimestamp();
msg.author.send(embed);
msg.reply('I\'ve sent you the account! Please check your DM!')
.then(m => {
setTimeout(() => {
m.delete();
}, 900000);
});
cooldown.add(msg.author.id);
setTimeout(() => {
cooldown.delete(msg.author.id);
}, config.COOLDOWN * 60 * 1000);
});
}
};
module.exports.help = {
name: `CrunchyRoll`,
description: `Sends you a CrunchyRoll account!`
};```
Simply adding a role check and a server check will prevent any issues!
The first line would be:
if(!msg.guild) return;
This line makes sure the user is running the command in a server(guild), this prevents a member role from being undefined or null.
The second line would be:
if(!msg.author.roles.cache.has('ROLE_ID_HERE')) return;
This prevents a user from running a command if they do not have a specific role.
The final code would be:
if(!msg.guild) return;
if(!msg.author.roles.cache.has('ROLE_ID_HERE')) return;
You will need to add this to the top of your code in order for it to work as you'd like.
const Discord = require('discord.js');
const fs = require('fs');
const cooldown = new Set();
module.exports.run = async (client, msg, args, config) => {
if(!msg.guild) return;
if(!msg.member.roles.cache.has('ROLE_ID_HERE')) return;
if(cooldown.has(msg.author.id)) {
msg.reply(`You need to wait ${config.COOLDOWN} minutes to use this command again!`)
.then((m) => {
msg.delete();
setTimeout(() => {
m.delete();
}, 5000);
});
} else {
fs.readFile('./accounts/crunchy.txt', 'utf8', function(err, data) {
if (err) throw err;
data = data + '';
var lines = data.split('\n');
let account = lines[Math.floor(Math.random() * 1)];
fs.writeFile('./accounts/crunchy.txt', lines.slice(1).join('\n'), function(err) {
if(err) throw err;
});
let embed = new Discord.RichEmbed()
.addField('Rate Us Here | قيمنا هنا ', `<#915***********80>`)
.addField('CrunchyRoll Account',`\n**${account}**`)
.setThumbnail('**************************')
.setColor("#363940")
.setFooter('Bot made by ******')
.setTimestamp();
msg.author.send(embed);
msg.reply('I\'ve sent you the account! Please check your DM!')
.then(m => {
setTimeout(() => {
m.delete();
}, 900000);
});
cooldown.add(msg.author.id);
setTimeout(() => {
cooldown.delete(msg.author.id);
}, config.COOLDOWN * 60 * 1000);
});
}
};
module.exports.help = {
name: `CrunchyRoll`,
description: `Sends you a CrunchyRoll account!`
};

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 | Cannot read property 'displayName' of undefined

I am making a discord bot for a friend and everything worked until i tried to make an unban command. when i tried to unban someone it did not work. then i looked at the error. it displayed:
TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Unhandled promise rejection: TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
this is my code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
console.log(message.content);
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first();
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length >= 1) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
message.channel.send(embedMsg);
}
if (args.length < 2) {
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
newargs = "";
for (var i = 1; i < args.length; i++) {
newargs += (args[i] + " ");
}
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
}
does anyone know what i am doing wrong?
It says in the discord.js's official docs that the unban method returns a member object https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=unban
The reason why it says 'undefined' is because the member object you are trying to access is not in the server/guild. So, therefore you need add a reference to the member object that the method returns:
message.guild.unban('some user ID').then((member) => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}
Unbun method return a user promise, so user dont have property displayName, you need use .username
And you can use user.id for unban, so right way will be let member = message.mentions.members.first() || args[0]
This check doing wrong, because its not stop code execute
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
Amm and whats this part code doing? Why its duplicate?
if (args.length < 2) {
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
The edited code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first() || args[0]
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
let newargs = args.splice(1,args.length).join(' ')
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
}
}

Message when collection ends

I'm trying to make a trivia command for my bot and I want to make it so that it sends a message after the amount of time for the collection it says "Times up".
This is what I have written so far:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("Correct!");
} else {
message.channel.send("wrong!");
}
});
collector.on('end', message => {
message.channel.send("times up!")
});
}
}
};
When I do this it says send of undefined for the end event.
I've also tried this below, but it does nothing:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("correct!");
} else {
message.channel.send("wrong!");
}
});
collector.stop('end', message => {
message.channel.send("times up!");
});
}
}
};
The last thing I tried was this, but I got .stop of undefined:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("correct!");
} else {
message.channel.send("wrong!");
}
}).stop(["times up"]);
}
}
};
Also, how could I make the collection stop after the "Correct!" spot?
Try using:
collector.on('end', (collected, reason) => {
message.channel.send("times up!")
});
Like in the docs: https://discord.js.org/#/docs/main/stable/class/MessageCollector?scrollTo=e-end

Resources