(node .) command: "throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function', listener);" - javascript

I've been trying to make my bot go live on Discord, but I got this error and don't know how to fix it:
Also, here is the "package.json" file:
{
"name": "botName",
"version": "1.0.0",
"main": "raidBot.js",
"scripts": {
"text": "echo \"Error: no test specified\" && exit 1"
},
"author": "uwu || dm 2 partner#7245 & lottie#8696",
"license": "ISC",
"dependencies": {
"discord.js": "^11.4.2"
},
"description": ""
}
"botName.js" file:
const discord = require('discord.js');
var client = new discord.Client();
const token = "instertedTokenHere";
client.on ("ready", () => {
console.log("the bot is ready...");
client.user.setGame ("prefix is $");
});
const prefix = "$";
client.on ("message"), (message) => {
if (message.author.bot) return;
if (message.content.startsWith (prefix + "bot")) {
message.reply ('Running...');
}
};
NOTE: This is what I did that resulted in the error:
cd D:\bot004
npm install
npm install --save discord.js
node .
Everything seems fine though. I have the node_modules folder and package.json, package-lock.json, and botName.js files.

// Your code
const discord = require('discord.js');
var client = new discord.Client();
const token = "instertedTokenHere";
client.on ("ready", () => {
console.log("the bot is ready...");
client.user.setGame ("prefix is $");
});
const prefix = "$";
client.on ("message"), (message) => {
if (message.author.bot) return;
if (message.content.startsWith (prefix + "bot")) {
message.reply ('Running...');
}
};
This looks a little suspect. You are not passing in the callback function to the .on() method below. That's where your error is coming from.
client.on ("message"), (message) => {
if (message.author.bot) return;
if (message.content.startsWith (prefix + "bot")) {
message.reply ('Running...');
}
};
Try refactoring to this:
client.on ("message", (message) => {
if (message.author.bot) return;
if (message.content.startsWith (prefix + "bot")) {
message.reply ('Running...');
}
});
I am able to reproduce the error when I run your code as is. The error subsides when I fix the code.

Place your client variable under the token. I had the same error when I made my discord bot.

Related

discord.js .setToken(...) is not a function

I am new in discord.js v14.0.3 and trying to start a simple command but I got an error.
I checked my BOT_TOKEN, BOT_CLIENT_ID, GUILD_ID is valid and I think the problem is not related with those token, how can I fix it?
Error Message
> node register.js
/register.js:11
(async () => {
^
TypeError: (intermediate value).setToken(...) is not a function
at Object.<anonymous> ....
My code
require("dotenv").config()
const { REST } = require('#discordjs/rest')
const { Routes } = require('discord.js')
const commands = [
{
name: 'ping',
description: 'Replies with Pong!',
},
];
const rest = new REST({ version: '10' }).setToken(process.env.BOT_TOKEN)
(async () => {
try {
console.log('Started refreshing application (/) commands.')
await rest.put(Routes.applicationGuildCommands(process.env.BOT_CLIENT_ID, process.env.DC_GUILD_ID), { body: commands });
console.log('Successfully reloaded application (/) commands.')
} catch (error) {
console.error(error)
}
})()
package.json
{
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js",
"build": "node register.js"
},
"dependencies": {
"discord.js": "^14.0.3",
"dotenv": "^16.0.1",
"ytdl-core": "^4.11.0"
}
}
Two things:
Looks like your package.json is missing #discordjs/rest. Install it with npm install #discordjs/rest or whatever your package manager is. Since you have no error on the require it may be is installed as phantom dependency.
You simply missing a semicolon in the line const rest = new REST({ version: '10' }).setToken(process.env.BOT_TOKEN) therfore the whole block with ...setToken...(async () is considered to be one(!) expression.

TypeError: command.execute is not a function when catching an error. Also, cooldown doesn't work. On Discord.js

I've been working on a Discord bot for a while and have implemented a cooldown command for a while too. It never works, and today i decided that i will try to fix it.
At first, it kept sending me an error message saying TypeError: command.execute is not a function and an error message on the channel, so i just removed catch (err) so it wont send that annoying message. But of course, doing that is perhaps the equivalent of removing a scratched limb.
Now that more people uses my bot, i was trying to rework on the cooldown feature, which is located on ../events/guild/message.js and it goes like this:
require('dotenv').config();
const Discord = require('discord.js');
const cooldowns = new Map();
module.exports = async (Discord, client, message) => {
if (message.author.bot) return;
const prefix = message.content.includes("nabe ") ? "nabe " : "n!"
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const cmd = client.commands.get(command) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(message.channel.type === "dm")return message.channel.send("you can't use commands on dm")
if(cmd){
cmd.execute(client, message, args, Discord);
}else return
if(!cooldowns.has(command.name)){
cooldowns.set(command.name, new Discord.Collection());
}
const current_time = Date.now();
const time_stamps = cooldowns.get(command.name);
const cooldown_amount = (command.cooldown) * 1000;
if(time_stamps.has(message.author.id)){
const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
if(current_time < expiration_time){
const time_left = (expiration_time - current_time) / 1000;
return message.reply(`wait **${time_left.toFixed(1)}** more seconds to do ${command.name} again.`).then(msg => { msg.delete({ timeout: 7000 }) });
}
}
time_stamps.set(message.author.id, current_time);
setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);
try{
command.execute(message, args, cmd, client, Discord);
} catch (err){
message.reply("There was an error trying to execute this command.");
console.log(err);
}
}
How it was implemented on each command files:
module.exports = {
info: {
name: "command name",
description: "command description",
cooldown: 30,
},
async execute(client, message, args, Discord) {
/*code here*/
}
By the way, i got most of this code from CodeLyon on youtube, and here's the sourcebin.
Everytime i executed a command it will return the TypeError: command.execute is not a function error and an error message on the channel. I am aware that some people said that command.execute does not exist, but it works on the tutorial video, and i don't know any alternatives. And it probably won't even fix the cooldown anyway.
I will definitely really appreciate it if anybody can find a solution.
NodeJS 16.13.0, NPM 8.1.0, DiscordJS 12.5.3, Heroku server.
I am aware that some people said that command.execute does not exist
And they would be right. As you can see in your defined command:
module.exports = {
info: {
name: "command name",
description: "command description",
cooldown: 30,
},
You did not appear to specify an execute function in the command body. If you want to run the command, you need to do that:
module.exports = {
info: {
name: "command name",
description: "command description",
cooldown: 30,
execute: (client, message, args, Discord) => {
// command logic goes here
}
},
P.S I believe the sourcebin tutorial that you linked also included an execute function:

How to fix TypeError: Cannot read property 'execute' of undefined in discord.js

I am new to command handler I am trying to execute commands for different js file
but I get this error
TypeError: Cannot read property 'execute' of undefined
this is my main.js
// Import the discord.js module
const Discord = require('discord.js');
const fs = require('fs');
// Create an instance of a Discord client
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const prefix = "$"
/**
* The ready event is vital, it means that only _after_ this will your bot start reacting to information
* received from Discord
*/
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'pingg'){
client.commands.get('pingg').execute(message, args);
}
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login('censored');
fs.readdir("./commands/", (err, files) => {
if(err) console.error(error)
let jsfiles = files.filter(f => f.split(".").pop() === "js")
if (jsfiles.length <= 0) {
return console.log("No commands to log in FOLDER NAME")
}
console.log(`Loading ${jsfiles.length} commands from FOLDER NAME...`)
jsfiles.forEach((f,i) => {
let props = require(`./commands/${f}`)
console.log(`${i + 1}: ${f} loaded!`)
client.commands.set(f, props)
})
})
my ping.js
module.exports = {
name : 'pingg',
description : 'Test',
execute(message, args){
message.channel.send('pongg')
}
}
The commands are registered in client.commands collection in the bot application lifecycle after the client is ready.
This is because client.login is invoked before it.
You can use commandFiles to load the commands from their modules. This was already performed sychronously so you have some guarantee on the order.
Also do that before the client.login statement.
Another issue is that the command module is named ping.js and as such your current implementation registers ping command to client.command collection.
However, you are resolving pingg command from the collection which returns an undefined
commandFiles.forEach(file => {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
});
client.login('censored');
//...

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
}

Discord.JS | Music Bot "Error: Video Unavailable"

I'll list the command logic itself and all installed dependencies below. Basically, whenever I run the command in Discord with any youtube link I've given it so far, the bot joins and everything runs correctly but then shortly after, the bot errors out in VSC with the error "Video Unavailable". I've looked through all kinds of forums and watched a lot of videos and I can't find any solution at all.
Play Command Logic:
if (musicArgs.startsWith('play')) {
let musicPlayPrefix = 'play';
let musicPlayArgs = musicArgs.slice(musicPlayPrefix.length).trim();
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play(await ytdl(musicPlayArgs), { type: 'opus'})
dispatcher.on('error', console.error);
dispatcher.on('start', () => {
message.channel.send(`**Now Playing:** *${musicPlayArgs}`);
});
dispatcher.on('finish', () => {
message.channel.send(`**Music Finished!**`);
});
}
else {
message.channel.send(`You're not in a voice channel! Retry the command inside of one.`);
}
}
Dependencies in Package.json:
"dependencies": {
"#discordjs/opus": "github:discordjs/opus",
"discord.js": "^12.3.1",
"ffmpeg-static": "^4.2.7",
"hypixel-api-reborn": "^2.2.4",
"libsodium-wrappers": "^0.7.8",
"ytdl-core-discord": "git+https://github.com/amishshah/ytdl-core-discord.git"
}

Categories

Resources