Why since my switch to discord js 13, the messageCreate Event bug? - javascript

I explain my problem: I use a js file external to my commands for my Events and I have the impression that there are some things that do not work correctly in my messageCreate.js which however worked before with Discord .JS in version 12.
For example, when I want to return as soon as the bot sends a message it doesn't work via the messageCreate.js, I have to put it in all of my commands etc.
In my commands I noticed that the arguments do not work whereas before I had no problems. I was able to verify this by putting a
if(args == undefined) return console.log("test")
and the message "test" was displayed in the console as soon as I tried.
I put my code below, hoping you can help me. :)
the part of my index.js that deals with events:
fs.readdir("./Events/", (err, files) => {
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] ${chalk.cyan('Chargement des évènements ...')}`)
if (err) return Debug.logs(err)
files.forEach(async (file) => {
if (file.endsWith(".js")) {
const event = require(`./Events/${file}`)
let eventName = file.split(".")[0]
try {
bot.on(eventName, event.bind(null, bot))
delete require.cache[require.resolve(`./events/${file}`)]
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] ${chalk.green('Event Chargé :')} ${chalk.cyan(file)}`)
} catch (error) {
Debug.logs(error)
}
} else {
return
}
})
})
my messageCreate.js :
const env = process.env
const chalk = require('chalk')
const moment = require('moment')
const Debug = require('../utils/Debug')
const config = require("../config.json")
module.exports = async (bot, message) => {
if(message.channel.type === "DM"){
if(message.author.bot) return;
message.reply("Les commandes en **messages privés** sont actuellement **désactivées** !")
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] [${chalk.yellow(message.author.tag)}] a envoyé ${chalk.green(message.content)} en DM`)
}else{
if (!message.author.bot) {
if (message.content.startsWith(config.prefix)) {
const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
const cmd = bot.commands.get(command)
if (cmd) {
await cmd.run(bot, message, args)
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] [${chalk.yellow(message.author.tag)}] a utilisé ${chalk.green(command)} ${chalk.cyan(args.join(" "))}`)
} else {
return
}
} else {
return
}
} else {
return
}
}
}
and one exemple of command who not work with messageCreate.js :
const Discord = require("discord.js");
module.exports.run = async (bot, message, config, args) => {
message.delete();
if(args == undefined) return console.log("wtf that not work ?")
}
module.exports.help = {
name:"test",
desc:"test commands !",
usage:"test",
group:"autre",
examples:"$test"
}
module.exports.settings = {
permissions:"false",
disabled:"false",
owner:"false"
}
as soon as I run the command with argument or without any argument, in both cases the console receives the message "wtf that not work?"
I hope you can help me! thanks in advance :)
Sorry if my english is bad but i'm french, not english !

In messageCreate.js, you call your command with the following:
// 3 arguments
await cmd.run(bot, message, args);
However, your command's run function is defined with 4 parameters:
async (bot, message, config, args) => {
// config = 'args', and args = undefined
}
To fix the issue, either:
Pass in a value for config, such as null:
await cmd.run(bot, message, null, args);
Make your function only have 3 parameters:
async (bot, message, args) => {
// ...
}

Related

How to catch an err in node.js?

How can I catch an error in node.js?
Here's my code:
const { Client, Message, MessageEmbed } = require("discord.js")
const translate = require('#iamtraction/google-translate')
module.exports = {
name: "ترجم",
description: `يترجم اللغه فقط أستعمل !translate "الكلمه/الجمله يلي بدك تترجمها"`,
aliases: ['translate'],
run: async (client, message, args) => {
const query = args.join(" ")
const lang = args[0]
if(!query) return message.reply('Please specify a text to translate');
const translated = await translate(query, { to: lang });
message.reply(translated.text);
},
};
It works when I type in chat:
!translate ar hello
But when I type:
!translate "not a real lang" hello
It shutdowns with the error:
Error: The language 'not a real lang' is not supported
I tried .catch, I tried if and else, I tried try
async functions return a value only if no error occurred. If something goes wrong an error is thrown that has to be caught.
You call the async function that errs with the await keyword, so you have to surround that with a try { } catch (e) {} block like this:
try {
const translated = await translate(query, { to: lang });
message.reply(translated.text);
} catch (e) {
message.reply('Translation failed: ' + e.message);
}
Since you take care of another possible error one line above, you could wrap the whole thing into a try-catch block and take care of all kinds of errors in a unified way:
const { Client, Message, MessageEmbed } = require("discord.js")
const translate = require('#iamtraction/google-translate')
module.exports = {
name: "ترجم",
description: `يترجم اللغه فقط أستعمل !translate "الكلمه/الجمله يلي بدك تترجمها"`,
aliases: ['translate'],
run: async (client, message, args) => {
try {
const query = args.join(" ")
const lang = args[0]
if(!query) throw new Error('Please specify a text to translate');
const translated = await translate(query, { to: lang });
message.reply(translated.text);
} catch (e) {
if (message) {
message.reply('Translation failed: ' + e.message);
}
}
},
};
This way you will get a meaningful reply in any case (as long as you have a valid message). For example, maybe args is not an array.
To catch errors in node.js you usually do this:
try {
// your code here
} catch (error){
console.error(error);
//your error response code here
}

Command interaction not responding

this code is not executing the desired function which is to be able to initiate a message to repeat on a set interval. When debugging there are no errors and the bot comes online fine but the command can't be used and it says nothing to suggest what the problem is.
I need a professionals help to identify the reason this code is not working and why the bot acts as if it does not even exist.
This is the shortest amount of code to replicate the results I have left out the config.json because it has my token but I know for sure that that file is configured properly anyway
Test.ts file in commands folder
const Discord = require("discord.js");
const source = require('../index');
module.exports.run = (Client, message, args) => {
if (!args [0]) return message.reply(`Please specify if you are turning the command on or off!`);
if (args[1]) return message.reply(`Please specify if you are turning the command on or off! [Too many Arguments!]`);
switch (args[0])
{
default:
{
message.reply('Invalid argument specified.')
break;
}
case "on":
{
if (!source.timedCheck){
source.timedCheck =setInterval(() =>{
// Function for set interval
console.log("Interval cycle run!" + (val++) + "times!");
valcheck();
}, 25 * 10000);
message.reply('command started!');
} else {
return message.reply(`command already running!`)
}
break;
}
case "off":
{
if (source.timedCheck){
message.reply(`user has turned off command!`);
clearInterval(source.timedCheck);
source.timedCheck = undefined;
} else {
return message.reply(`command already offline!`)
}
break;
}
}
let valcheck = () => {
if (source.val > 5){
clearInterval(source.timedCheck);
source.timedCheck = undefined;
message.channel.send(`command finished as scheduled!`);
}
};
};
module.exports.help = {
name: "test",
usage: "test <on/off>"
};
Index.js file
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
// Export variables for commands
module.exports.timedCheck = undefined;
module.exports.val = 0;
// Login to Discord with your client's token
client.login(token);
You didn't tell the bot to execute this command. In your Index file you have to require the command file, catch the "message" or the "interactionCreate" events and then execute your command.
This code is incomplete and I can only guide you in a direction as you miss many things in your code.
You should read a tutorial: https://discordjs.guide/creating-your-bot/creating-commands.html#command-deployment-script
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./src/commands');
// require every command and add to commands collection
for (const file of commandFiles) {
const command = require(`./src/commands/${file}`);
client.commands.set(command.name, command);
}
client.on('message', async message => {
// extract your args from the message, something like:
const args = message.content.slice(prefix.length).split(/ +/);
try {
command.execute(message, args, client); // provide more vars if you need them
} catch (error) {
// handle errors here
}

discord bot not processing the command

I was adding some new commands to my discord v12 bot. But it's not responding to the code I typed. Any help is appreciated.
This section is inside index.js
client.admins = new discord.Collection();
const admins = fs.readdirSync('./custom/admin').filter(file => file.endsWith('.js'));
for (const file of admins) {
const admin = require(`./custom/admin/${file}`);
client.admins.set(admin.name.toLowerCase(), admin);
};
This is the code to process the above lines
if (message.author.bot || message.channel.type === 'dm') return;
const prefix = client.config.discord.prefix;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const admin = args.shift().toLowerCase();
const adm = client.admins.get(admin) || client.admins.find(adm => adm.aliases && adm.aliases.includes(admin));
if (adm) adm.execute(client, message, args);
And the function which I am trying the bot to do is named delete.js
module.exports = {
name: 'snap' ,
aliases: [],
category: 'admin',
utilisation: '{prefix}snap [number]',
execute(message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")
if (message.member.hasPermission('ADMINISTRATOR') ){
const {MessageAttachment} = require('discord.js');
const snaping = new MessageAttachment('./snap.gif')
message.channel.send(snaping)
setTimeout(snapCommand , 9000 ,args, message)
}
else
{
message.channel.send("-_- you are not an admin,Then why are you trying to use admin commands");
}
function snapCommand(args, message){
var del= args ;
del = parseInt(del , 10)
message.channel.bulkDelete(del+2);
}
}
}
when I launch the bot it shows no error msg, So that's a good sign I think, but when I use !snap 5
'!' which is my prefix. The bot does nothing. No error in the console also. Does anyone have any idea to solve this?
Never mind, I fixed it by adding client to the delete.js code
execute(client, message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")

JavaScript Command Handler Not Running Additional Commands?

I have a command handler for my discord bot. It loads the command modules fine, (and console logs indicate as much), but I'm having trouble getting it to execute commands beyond the first command module. Here's the code:
const Discord = require("discord.js");
const client = new Discord.Client();
client.commands = new Discord.Collection();
const prefix = "f$";
const fs = require("fs");
try {
const files = fs.readdirSync("./commands/");
let jsFiles = files.filter(filename => filename.split(".").pop() === "js");
for (const filename of jsFiles) {
let command = require(`./commands/${filename}`);
if (!command) return console.error(`Command file '${filename}' doesn't export an object.`);
client.commands.set(command.name, command);
console.log(`Loaded command: ${command.name}`);
}
} catch (err) {
console.error(`Error loading command: '${err}'`);
}
console.log("Finished loading\n");
client.on("ready", () => {
console.log("Client ready!");
});
client.on("message", async message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/g);
//console.log(args);
let cmdName = args.shift().toLowerCase();
for (const command of client.commands.values()) {
console.log(command.name);
console.log(cmdName);
console.log(command === cmdName);
if (command.name !== cmdName /*&& !command.aliases.includes(cmdName)*/) return;
try {
await command.executor(message, args, client);
} catch (err) {
console.error(`Error executing command ${command.name}: '$```{err.message}'`);
}
}
});
client.login(TOKEN).catch(err => console.log(`Failed to log in: ${err}`));
and in each command module you have this bit:
module.exports = {
name: "command",
description: "description of command",
aliases: [],
executor: async function (message, args, client) {
(I have not done aliases for this yet, so alias lines are either empty or remmed out.)
You've incorrectly referenced your variable in the template literal which meant lots of your code was ignored, this likely is the entirety of the problem, it should look like this:
console.error(`Error executing command ${command.name}: ${err.message}`);
For guidance regarding template literals use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals. If you wanted to use the ``` but have them ignored use this code:
console.error(`Error executing command ${command.name}: \`\`\` ${err.message} \`\`\` `);
In addition on your execute function you don't have closing braces so that should be:
module.exports = {
name: "command",
description: "description of command",
aliases: [],
executor: async function (message, args, client) {
// code to be executed
}

Trying to do close and open command quick.db

const db = require("quick.db");
module.exports.run = async (client, message, args) => {
let botfetch = db.fetch(`ddoskoruma_${message.guild.id}`);
let kapaç = args[0];
if (kapaç === "aç") {
db.set(`ddoskoruma_${message.guild.id}`)
console.log("Open")
} else if (botfetch) {
console.log("Already open.")
}
if (kapaç === "kapat") {
db.delete(`ddoskoruma_${message.guild.id}`)
console.log("Closed.")
} else if (!botfetch) {
console.log("Already close.")
}
}
module.exports.conf = {
name: "ddoskoruma"
};
I am trying to do close and open commands with quick.db. I want to do if command already closed, reply "It's already closed/opened." but I'm trying this code for it but I'm getting this error:
(Sorry for my bad english)
(node:26756) UnhandledPromiseRejectionWarning: TypeError: Input cannot be undefined # ID: ddoskoruma_640958795643617284
You need to provide a key and a value when you use db.set(). For example:
db.set(`ddoskoruma_${message.guild.id}`, 1);
Just edit this line and it will work.

Categories

Resources