unban command with discord.js v12 - javascript

I am trying to make an unban command but I get an error const member; ERROR: Missing initializer in const declaration
client.on('message', async message => {
if (message.content.toLowerCase().startsWith(prefix + "unban"))
if (!message.member.hasPermission("BAN_MEMBERS")) {
return message.channel.send(`You cant use this command since you're missing "BAN_MEMBERS" perm`)
}
if (!args[0]) return (await message.channel.send('pls enter a users id to unban.')).then(msg => msg.delete({timeout: 5000}))
const member;
try {
member = await client.users.fetch(args[0])
} catch (e) {
console.log(e)
return message.channel.send(('an error accured'));
}
const reason = args[1] ? args.slice(1).join(' ') : 'no reason';
const newEmbed = new Discord.MessageEmbed()
.setFooter(`${message.author.tag} | ${message.author.id}`, message.author.displayAvatarURL({dynamic: true}))
message.guild.fetchBans().then( bans => {
const user = bans.find(ban => ban.user.id === member.id);
if (user) {
newEmbed.setTitle(`Successfully Unbanned ${user.user.tag}`)
.setColor('#FFFF00')
.addField({name: 'User ID', value: user.user.id, inline: true})
.addField({name: 'User Tag', value: user.user.tag, inline: true})
.addField({name: 'Banned Reason', value: user.reason})
message.channel.send(newEmbed)
}})})

const means that the variable will be immutable (constant). Thus, declaring a const-type variable and not immediately assigning it a value is pointless, and not allowed in Javascript.
To make a mutable variable, instead of const, you should use let.
So, in your code, line 7 should look like this:
let member;

Related

Getting GuildMember Object with user ID Discord.js v13

I'm fairly new to discord.js and Javascript in general. Here I created a simple userinfo command which fetches data of the user and embeds it neatly as you can see below. You can also see that the command requires the author/mod to mention the user to get the result embed but I want to get the same result by member's discord userID.
I tried message.mentions.users.first() || message.guild.member.length(args[0]) but this creates a lot of problems. So basically how do I get to use the same command/code by discord ID.
const moment = require('moment');
const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js')
module.exports = {
description: 'whois',
run: async (client, message, args) => {
const user = message.mentions.users.first()
const embed = new MessageEmbed()
.setTitle(`**PASSION ISLAND MODERATIONS**`)
.setColor('#ffc0cb')
.setThumbnail(user.displayAvatarURL({ dynamic: true }))
.addField('Username', user.username)
.addField('User Id', user.id)
.addField('Account Type', `${user.bot ? 'Bot' : 'Human'}`)
.addField(`Roles`, `${message.member.roles.cache.size}`)
.addField(`Joined At`, `${moment.utc(message.member.joinedAt).format('ddd, MMM Do, YYYY, h:mm a')}`)
.addField(`created At`, `${moment.utc(message.member.createdAt).format('ddd, MMM Do, YYYY, h:mm a')}`)
.setTimestamp()
.setFooter(`Requested by ${message.author.username}`)
message.channel.send({ embeds: [embed] })
},
}
You can try using
let user;
if(message.mentions.members.first()) {
user = message.mentions.members.first()
} else {
let x = await message.guild.members.cache.get(`${args[0]}`)
user = x.user;
}
This would work well with IDs since you can pass a snowflake within the .get() function.
This is the code I'm using, can find by user's id, user's name or user's tag.
let user = message.mentions.users.first()||null;
if (!user && args.length > 0) {
let input = args.join(' ')
let temp = message.guild.members.cache.get(input) || message.guild.members.cache.find(mem => mem.user.username === input) || mmessage.guild.members.cache.find(mem => mem.user.discriminator === input) || null
if (temp) user = temp.user;
}
If you want to be 100% sure you will find the user if he exists in the server can do:
message.mentions.users.first() || message.guild.members.fetch(args[0])
You can try using
message.mentions.members.first().then((m) => {
if (!m) {
// code
}
})
// or do this
const member = await message.mentions.members.first();
if (!member) {
// Code
}
or change the members to an users
as other people have shown you can do that by finding the id in the server like so
message.guild.members.cache.get(args[0]);
// This will return null if it doesnt exist so you can do this
const member = await message.guild.members.cache.get(args[0]);
if (!member) {
// code
}
You can combine both of them to check it and be sure that the member exists like this
const member = await message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!member) {
// Code
}
hopefully this helped
NOTE : I see that you are using multiple .addField() you can use .addFields() to optimize your code
like this
const embed = new MessageEmbed()
.addFields(
{ name: 'name', value: 'the description', inline: true || false },
{ name: 'name', value: 'the description', inline: true || false },
)

Can I use an if statement inside a try-catch method?

I'm using the guild.fetchVanityData() method to get a guild's vanity data in my Discord bot using the Discord.js library.
My invite.js command throws an error saying This guild does not have the VANITY_URL feature enabled.
I know that the guild does not have it enabled, and am sending a custom message to the user telling them that. Hence, I do not want it to throw an error. I'm using an if check in my message.js event file to swallow the error if the command executed is the invite command (The command throwing the error), using a return method. This does not seem to work as it still throws an error.
The only file in my entire bot in which I am using a try-catch is at the end of message.js.
My code is below, please help me out.
Message.js event file
module.exports = {
name: 'message',
execute(message, client) {
const prefixes = ['!1','833376214609690674', "<#!833376214609690674>","<#833376214609690674>"]
const prefix = prefixes.find(p => message.content.startsWith(p));
if (!prefix || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (message.content === "<#833376214609690674>" || message.content === "<#!833376214609690674>" || message.content === "833376214609690674" || message.content === "!1") {
const mCommand = client.commands.get('help')
mCommand.execute(message, args)
}
if (!client.commands.has(commandName)) return message.channel.send("Please provide a valid command.")
const command = client.commands.get(commandName);
try {
command.execute(message, args, client);
}
catch (error) {
if(command.name === "invite") {
return
}
else {
console.log(error)
}
}
},
};
Invite.js command file
const Discord = require('discord.js')
module.exports = {
name: 'invite',
category: "utility",
description: 'Get the bot invite or server invite info.',
execute: async (message, args) => {
if (args[0] === 'bot') {
const embed = new Discord.MessageEmbed()
.setTitle('Bot Invite')
.setDescription("Returns the bot's invite link.")
.addFields({
name: 'Invite',
value: "[Click here](https://discord.com/api/oauth2/authorize?client_id=833376214609690674&permissions=4294442710&scope=bot%20applications.commands) to invite the bot to your server."
})
message.channel.send(embed)
}
else if (args[0] === 'server') {
message.guild.fetchVanityData()
if (!message.guild.vanityURLCode) {
const embed = new Discord.MessageEmbed()
.setTitle('Server Invite')
.setDescription("Returns the server's Vanity URL if it has one.")
.addFields({
name: 'Vanity URL',
value: 'This server does not have a Vanity URL.',
inline: true
},
{
name: 'Uses',
value: 'Not Applicable',
inline: true
})
.setTimestamp()
return message.channel.send(embed)
}
const embed = new Discord.MessageEmbed()
.setTitle('Server Invite')
.setDescription("Returns the server's Vanity URL if it has one.")
.addFields({
name: 'Vanity URL',
value: `https://discord.gg/${message.guild.vanityURLCode}`,
inline: true
},
{
name: 'Uses',
value: `${message.guild.vanityURLUses}`,
inline: true
})
message.channel.send(embed)
}
}
}
I think this is all the code that is required, but if you wish to see my other commands, files, etc., you can go to this repl: https://replit.com/#smsvra6/MultiBot
According to discord.js documentation, <Guild>.fetchVanityData returns a Promise. Therefore, you can use <Promise>.then and <Promise>.catch syntax.
i.e.:
message.guild.fetchVanityData()
.then(data => {
// success, the server has a vanity url ;
})
.catch(error => {
// error, the server does not have a vanity url.
});
There is no need for an if statement.

Temporary mute command returning error 'Cannot read property 'slice' of undefined'

I am trying to create a temporary mute command, that will unmute the muted user in the given time.
Here's my code:
const Discord = require("discord.js");
const ms = require("ms");
module.exports = {
name: 'mute',
description: 'mute a specific user',
usage: '[tagged user] [mute time]',
async execute(message, embed, args) {
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if (!tomute) return message.reply("Couldn't find user.");
const reason = args.slice(1).join(' ');
if (tomute.hasPermission("MANAGE_MESSAGES")) return message.reply("Can't mute them!");
const muterole = message.guild.roles.cache.find(muterole => muterole.name === "muted");
if (!muterole) {
try {
muterole = await message.guild.roles.create({
name: "muted",
color: "#000000",
permissions: []
})
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.overwritePermissions(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
} catch (e) {
console.log(e.stack);
}
}
const mutetime = args.slice(2).join(' ');
//here is the start of the error
await (tomute.roles.add(muterole.id));
message.reply(`<#${tomute.id}> has been muted for ${ms(ms(mutetime))} `);
setTimeout(function() {
tomute.roles.remove(muterole.id);
message.channel.send(`<#${tomute.id}> has been unmuted!`);
}, ms(mutetime));
}
}
Currently getting the following error: Cannot read property 'slice' of undefined
Do you have any idea on how to fix the command?
edit
this after a year and this is for future people who come here
the issue was here
async execute(message, embed, args) {
i never passed embed from my main file so args was undefined
embed part was where the args should have been, I was stupid at that time and was new to coding, but as I now have some experience, I decided to edit this to show what wrong
It means that somewhere in your code, you have a value which is undefined and you try to use the string/array function slice on it but undefined does not have this function : so it is a error.

discord.js - give role by reacting - return value problem

So I wanted a command intomy bot, which iis able to give server roles if you react on the message. By google/youtube I done this. My problem is, that if I react on the message my algorith won't step into my switch also if I react to the costum emoji it won't even detect it that I reacted for it. Probably somewhere the return value is different but I was unable to find it yet. Sy could check on it?
const { MessageEmbed } = require('discord.js');
const { config: { prefix } } = require('../app');
exports.run = async (client, message, args) => {
await message.delete().catch(O_o=>{});
const a = message.guild.roles.cache.get('697214498565652540'); //CSGO
const b = message.guild.roles.cache.get('697124716636405800'); //R6
const c = message.guild.roles.cache.get('697385382265749585'); //PUBG
const d = message.guild.roles.cache.get('697214438402687009'); //TFT
const filter = (reaction, user) => ['🇦' , '🇧' , '🇨' , '<:tft:697426435161194586>' ].includes(reaction.emoji.name) && user.id === message.author.id;
const embed = new MessageEmbed()
.setTitle('Available Roles')
.setDescription(`
🇦 ${a.toString()}
🇧 ${b.toString()}
🇨 ${c.toString()}
<:tft:697426435161194586> ${d.toString()}
`)
.setColor(0xdd9323)
.setFooter(`ID: ${message.author.id}`);
message.channel.send(embed).then(async msg => {
await msg.react('🇦');
await msg.react('🇧');
await msg.react('🇨');
await msg.react('697426435161194586');
msg.awaitReactions(filter, {
max: 1,
time: 15000,
errors: ['time']
}).then(collected => {
const reaction = collected.cache.first();
switch (reaction.emoji.name) {
case '🇦':
message.member.addRole(a).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${a.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case '🇧':
message.member.addRole(b).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${b.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case '🇨':
message.member.addRole(c).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${c.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case '<:tft:697426435161194586>':
message.member.addRole(d).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${d.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
}
}).catch(collected => {
return message.channel.send(`I couldn't add you to this role!`);
});
});
};
exports.help = {
name: 'roles'
};
As of discord.js v12, the new way to add a role is message.member.roles.add(role), not message.member.addRole. Refer to the documentation for more information.
You need to use roles.add() instead of addRole()
Mate, You cannot use the id of emoji in codes(except when you are sending a message). so, the custom emoji has to be replaced by a real emoji that shows a box in your editor and works perfectly in discord. If you can find it, then this might be complete as discord API cannot find the emoji <:tft:697426435161194586>. you can get an emoji by using it in discord and opening discord in a browser and through inspect element, get the emoji.
Else, you will have to use different emoji.

Discord bot - Purge command not working discord.js-commando

I have created a discord bot recently using node js which when I do !purge, responds with Unknown command, do !help to view a list of command but after saying it, it is purging the messages. That is, it works well but posting that error message. I don't know what's the problem please help me
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix = '!';
bot.on('message', message => {
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.slice(1);
if (msg.startsWith(prefix + 'PURGE')) {
async function purge() {
message.delete();
if (isNaN(args[0])) {
message.channel.send('Please input a number of messages to be deleted \n Syntax: ' + prefix + 'purge <amount>');
return;
}
const fetched = await message.channel.fetchMessages({limit: args[0]});
console.log(fetched.size + ' messages found, deleting...');
// Deleting the messages
message.channel.bulkDelete(fetched)
.catch(error => message.channel.send(`Error: ${error}`));
}
purge();
}
});
bot.login('MY BOT TOKEN HERE');
Right now you're using the discord.js-commando library. Any reason you decided to use that library? It looks like you're just using standard discord.js functions like bot.on, message.channel.send, message.channel.fetchMessages, message.channel.bulkDelete...
You should be good just useing the standard discord.js library, starting your code with this:
const Discord = require('discord.js');
const bot = new Discord.Client();
You can find this code on the main "Welcome" page of Discord.js
Edit:
I'm still not sure why you're using discord.js-commando, but that doesn't matter. Here's an example command I came up with using the discord.js-commando library:
const commando = require('discord.js-commando');
class PurgeCommand extends commando.Command {
constructor(client) {
super(client, {
name: 'purge',
group: 'random', // like your !roll command
memberName: 'purge',
description: 'Purge some messages from a Text Channel.',
examples: ['purge 5'],
args: [
{
key: 'numToPurge',
label: 'number',
prompt: 'Please input a number ( > 0) of messages to be deleted.',
type: 'integer'
}
]
});
}
run(msg, { numToPurge }) {
let channel = msg.channel;
// fail if number of messages to purge is invalid
if (numToPurge <= 0) {
return msg.reply('Purge number must be greater than 0');
}
// channel type must be text for .bulkDelete to be available
else if (channel.type === 'text') {
return channel.fetchMessages({limit: numToPurge})
.then(msgs => channel.bulkDelete(msgs))
.then(msgs => msg.reply(`Purge deleted ${msgs.size} message(s)`))
.catch(console.error);
}
else {
return msg.reply('Purge command only available in Text Channels');
}
}
};
module.exports = PurgeCommand
I'd also recommend using a new type instead of integer so you can validate the user's response and make sure they enter a number greater than 0.
If you need help setting up an initial discord.js-commando script, I'd take a look at this repo provided by the Discord team: https://github.com/discordjs/Commando/tree/master/test
You might wanna use this. This purge command is intended for discord.js v11.5.1 and I haven't tested to see if it works on v12, but I think this might work for you. I should say that THIS DELETES ALL THE CONTENT INSIDE THE CHANNEL (Nested command)
exports.run = (bot, message, args) => {
let filter = m => message.author.id === message.author.id;
message.channel.send("Are you sure you wanna delete all messages? (y/n)").then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content.toUpperCase() == "YES" || message.content.toUpperCase() == "Y") {
message.channel.bulkDelete(100);
} else if (message.content.toUpperCase() == "NO" || message.content.toUpperCase() == "N") {
message.channel.send("Terminated").then(() => {message.delete(2000)});
} else {
message.delete();
}
})
.catch(collected => {
message.channel.send("Timeout").then(() => {message.delete(2000)});
});
}).catch(error => {
message.channel.send(error);
});
};

Categories

Resources