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

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.

Related

im making a discord bot for the first time in discord js and my test command wont work

This is "my code" and the command doesn't work. tried following a YouTube tutorial. this is my first time trying to do something like this. all my code experience comes from simple python code. so if you have any vids that explains this pls send
const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField, Permissions, Message } = require(`discord.js`);
const prefix = '>';
const client = new Client({
intents: [
32767
]
});
client.on("ready", () => {
console.log("botong is online!")
client.user.setPresence({
status: 'online',
activity: {
name: 'status',
type: 'ActivityType.Playing'
}
});
});
client.on("messageCreate", (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
//message array
const messageArray = message.content.split(" ");
const argument = messageArray.slice(1);
const cmd = messageArray[0];
//commands
//test commands
if (commands === 'test') {
message.channel.send("Bot is working!")
}
})
client.login("MY TOKEN");
tried to run this and nothing happened, it should send a message in my discord server saying "Bot is Working"
so if you have any vids that explains this pls send
Here's an article from Codeacademy which explains how to create a simple Discord bot. https://www.codecademy.com/article/christine_yang/build-a-discord-bot-with-node-js
Reason why your test message doesn't appear: the message never gets sent because you haven't defined commands so it can obviously never be 'test'.
if (commands === 'test') {
message.channel.send("Bot is working!")
}
Edit: Here's a code sample from the article which sends message to the channel each time someone sends "Hello" there.
client.on('messageCreate', msg => {
// You can view the msg object here with console.log(msg)
if (msg.content === 'Hello') {
msg.reply(`Hello ${msg.author.username}`);
}
});

cannot read property of 'channels' of undefined discord.js

const reason = args.slice(0).join(" ");
if (!reason) return message.channel.send('Reason for ticket?');
const user = message.guild.member(message.author);
const ticket = db.fetch(`Ticket_user_${user.id}`)
if(ticket) message.channel.send("You already made a ticket senpai! Close your old ticket.");
const channel = message.guild.channels.cache.find
(channel => channel.name === 'ticket')
if (!channel)
guild.channels.create('ticket', {
type: 'text',
permissionOverwrites: [
{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
},
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
})
.then(console.log)
.catch(err => {
message.channel.send("An error occurred while running the command. Please report this error to the support server:"+ err)
return;
})
db.add(`Ticket_user_${user.id}`)
const time = "3"
setTimeout(() => {
const embed = new Discord.MessageEmbed()
.setTitle(`Ticket#0001`)
.setDescription(`Reason: ${reason}`)
.addField("Welcome to my ticket senpai!! We are waiting for staff")
.setColor("PURPLE")
message.channel.send(embed)
}, ms(time))
}
}
I'm making a ticket system for my bot and ik you people smart because top.gg won't help
Thank you for the help this will help my bot and my code and make me smart plus I'm removing the dot becccause of downvote ig
Here in this code
if (!channel){
guild.channels.create('ticket', { //...... rest of the code
You didn't define guild. Try replacing guild with message.guild
Like this:
if (!channel){
message.guild.channels.create('ticket', { //.... rest of the code
Also, please remove the unnecessary part (dots) from the question

Cannot destructure property "commands" of message.bot as it is undefined (discord.js)

So, I was switching to module.exports for my bot and for the help command I got the error: "Cannot destructure property "commands" of message.bot as it is undefined"
I never experienced the error before so I don't know how to fix it.
Also I copied the advanced command handler code from the official discord.js guide and it still does not work.
const Discord = require('discord.js')
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands'],
usage: '!help | !help <command name>',
cooldown: 1,
async execute(message, args, bot) {
const data = []
const { commands } = message.bot;
if(!args[1]){
let embed = new Discord.MessageEmbed()
.setTitle('Commands')
.addField('Fun 🎲', Wide)
.addField('Games 🎮', funay)
.addField('Information 📙', inf)
.addField(`Images 🖼`, imagess)
.addField('Moderation 👩‍⚖️', mod)
.addField('Giveaway🎉', gib)
.addField('Other', other)
.setColor('RANDOM')
.setThumbnail(message.author.displayAvatarURL())
message.channel.send(embed)
} else {
const name = args[1].toLowerCase()
const cmd = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!cmd) {
return message.reply('that\'s not a valid command!');
}
const embedd = new Discord.MessageEmbed()
.setTitle(`Name: ${cmd.name}`)
.addField('Aliases', `${cmd.aliases.join(", ")}`)
.addField('Description', `${cmd.description}`)
.addField('Usage', data.push `${cmd.usage}`)
.setFooter(`Cooldown: ${cmd.cooldown || 3} second(s)`)
.setColor("RANDOM")
message.channel.send(embedd);
}
},
}
Try to change message.bot to message.client

unban command with discord.js v12

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;

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