Im using discord js to make a multi-purpose discord bot for my server, but its giving me this error:
ValidationError: Expected a string primitive
It was working fine yesterday but i forgot to save something and i dont know what.
const fs = require('node:fs');
const path = require('node:path');
const {
Client,
GatewayIntentBits,
Partials,
Collection,
} = require("discord.js");
const { Player } = require('discord-player');
const { Routes } = require('discord-api-types/v10');
const { token, prefix, guildId, clientId } = require('./config.json');
const { REST } = require('#discordjs/rest');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildVoiceStates
],
partials: [
Partials.Channel,
Partials.Message,
Partials.User,
Partials.GuildMember,
],
});
client.player = new Player(client, {
ytdlOptions: {
quality: "highestaudio",
highWaterMark: 1 << 25
}
});
module.exports = client;
// command handler
//slash commands
const slashCommands = [];
client.slashCommands = new Collection();
const commandsPath = path.join(__dirname, "commands"); // E:\yt\discord bot\js\intro\commands
const slash_commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('S.js'));
for(const file of slash_commandFiles)
{
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.slashCommands.set(command.data.name, command);
slashCommands.push(command.toJSON());
}
console.log(slashCommands);
//message commands
client.messageCommands = new Collection();
const message_commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('M.js'));
for (const file of message_commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.messageCommands.set(command.Name, command);
}
//event handler
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
// messageCommand handler
client.on('messageCreate', (message) => {
const args = message.content.slice(prefix.length).split(' ');
const command = args[0];
if (client.messageCommands.get(command)) {
let Command = client.messageCommands.get(command);
Command.execute(message);
}
});
client.on('ready', () => {
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId),
{ body: slashCommands })
.then(() => console.log('Successfully updated commands for guild ' + guildId))
.catch(console.error);
console.log('bot is online!');
client.user.setStatus('idle');
});
client.login(token);
im sure there's nothing wrong with any of the command files because it was working fine yesterday.
there's 100% an error in this line slashCommands.push(command.toJSON()); but I cant seem to fix it. The command.toJSON() console logs just fine but gives an error while trying to push into the list
Ran into the same issue, turns out options (i.e. addUserOption) require a description. Point is it's really confusing as this error shows up when doing command.data.toJSON(). If you are dynamically loading the command files as described in the guide and running into this issue, then try manually doing a require to trigger the validation beforehand.
Try using command.data.toJSON() as command is a nested object with a data and an execute key.
I've fixed it, there was a url in the json which seemed to be causing some issue, I removed the file with the url and its working now
Related
DiscordAPIError[50035]: Invalid Form Body
0[CONTENT_TYPE_INVALID]: Expected "Content-Type" header to be one of {'application/json'}.
Im getting this while starting my bot.
const fs = require("fs");
const colors = require('colors');
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v10");
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync("./src/commands");
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
commands.set(command.data.name, command);
commandArray.push(command.data.toJSON());
}
}
const clientId = "0";
const guildId = "0";
const rest = new REST({ version: "10" }).setToken(process.env.TOKEN);
try {
console.log("Started refreshing application (/) commands.".yellow);
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: client.commandArray,
});
console.log("Successfully reloaded application (/) commands.".green);
} catch (error) {
console.error(`${error}`.red);
}
};
};
This is the code of handleCommands.js, and error above is getting by this script, anyway to fix?
(client id and guild id is blurred.)
Im beginner in the js so i dont really know much abt it.
I were trying to do slash command loader, but actually it gave me some kind of errors.
This question already has answers here:
message event listener not working properly
(2 answers)
Closed 1 year ago.
I have been trying to make a command handler with prefix, but I'm getting a problem, the bot won't respond and there is no error either
// Index
---// Collections
client.functions = new Collection();
client.commands = new Collection();
client.interactions = new Collection();
---// Handlers
const handlers = fs
.readdirSync("./config/handlers/")
.filter((file) => file.endsWith(".js"));
const commandFolders = fs.readdirSync("./config/commands/");
const interactionFolders = fs.readdirSync("./config/interactions");
const eventFiles = fs
.readdirSync("./config/events/")
.filter((file) => file.endsWith(".js"));
(async () => {
for (file of handlers) {
require(`./config/handlers/${file}`)(client);
}
client.handleCommands(commandFolders);
client.handleInteractions(interactionFolders);
client.handleEvents(eventFiles);
client.login(token);
})();
// The event handler
module.exports = (client) => {
client.handleEvents = async (eventFiles) => {
for (const file of eventFiles) {
const event = require(`../events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
console.log(`[EVENT HANDLER] - ${file} has been loaded.`);
}
};
};
// command handler
const fs = require("fs");
module.exports = (client) => {
client.handleCommands = async (commandFolders) => {
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./config/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
client.commands.set(command.name, command);
console.log(`[COMMANDS HANDLER] - ${file} has been loaded`);
}
}
};
};
// and in the last my messageCreate.js
const prefix = ".";
module.exports = {
name: "messageCreate",
async execute(message, client) {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!message.user.id === "798928603201929306") return;
console.log(
`${message.user.tag} used ${command} in #${message.channel} triggered an command.`
);
if (
!message.content.startsWith(prefix) ||
message.author.bot ||
message.channel.type === "DM"
)
return;
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args, client);
} catch (error) {
console.error(error);
message.reply("there was an error trying to execute that command!");
}
},
};
// ping command
module.exports = {
name: "ping",
async execute(message, args, client) {
message.channel.send(`Pong ${client.ws.ping}`)
}
} // I haven't tried this yet because I'm getting an error in the messageCreate.js
notes:
1. sorry for the long code block
2. hope I inputted everything for getting enough help/info
3. my discord.js version is v13
4. if you need more info about my files, let me know in the comments
It is likely that you created your client with the wrong intents. If you need to listen to messages in servers, make sure you use the GUILD_MESSAGES intent.
const bot = new Discord.Client({intents:[Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES]})
Following along with discordjs.guide/creating-your-bot
I've made an event handler that's working correctly and returning the expected terminal logs.
However, none of the commands that were previously working are working. I've had this happen before and I had to restart the bot and the commands started functioning correctly again.
The bit I can't figure out is the interaction are being logged in my terminal successful yet they're showing up as failed interactions in the discord.
My command handler;
const fs = require('fs');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Successfully registered application commands.');
} catch (error) {
console.error(error);
}
})();
my event handler;
const fs = require('fs');
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(token);
Ping command:
const { SlashCommandBuilder } = require('#discordjs/builders'); module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply('Pong!');
},
};
interactionCreate event listener:
module.exports = { name: 'interactionCreate', execute(interaction) { console.log(${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.); }, }; This is triggering correctly at least, I'm getting an output in my log that's expected.
And my interactionCreate although this lives in with my command handling folder/code. I'll post the folder structure below as well.
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
//If the command doesn't exist, it will return undefined, so exit early with return.
if (!command) return;
//If it does exist, call the command's .execute() method, and pass in the interaction variable as its argument.
try {
await command.execute(interaction);
//In case something goes wrong, log the error and report back to the member to let them know.
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
I am trying to code in / commands into my discord bot. But I keep on getting this error:
Cannot read property 'commands' of undefined
Below I have attached my main.js file, as well as the part that just keeps giving me the error:
Part that gives me the error
const getApp = (guildID) => {
const app = client.api.applications(client.user.id)
if (guildID) {
app.guilds(guildID)
}
}
client.once('ready', async() => {
client.user.setActivity('FALLBACK BOT, USE THE MAIN CHECKPOINT BOT INSTEAD. THIS IS FOR DEVELOPMENT PURPOSES')
const commands = await getApp(guildID).commands.get()
console.log(commands)
await getApp(guildID).commands.post({
data: {
name: 'ping',
description: 'Shows your current ping.',
},
})
});
Here is the full script
// Just grabbing some librarys
const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ]});
const mongoose = require('mongoose');
// Defining the guildID
const guildID = (process.env.guildID);
// Filtering the command folder so it only includes .js files
const { join } = require('path');
const fs = require('fs');
require('./dashboard/server');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
const getApp = (guildID) => {
const app = client.api.applications(client.user.id)
if (guildID) {
app.guilds(guildID)
}
}
client.once('ready', async() => {
client.user.setActivity('FALLBACK BOT, USE THE MAIN CHECKPOINT BOT INSTEAD. THIS IS FOR DEVELOPMENT PURPOSES')
const commands = await getApp(guildID).commands.get()
console.log(commands)
await getApp(guildID).commands.post({
data: {
name: 'ping',
description: 'Shows your current ping.',
},
})
});
['command_handler', 'event_handler'].forEach(handler =>{
require(`./handlers/${handler}`)(client, Discord);
})
mongoose.connect(process.env.MONGODB_SRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
}).then(()=> {
console.log('Connected to Database')
}).catch((err) =>{
console.log(err);
})
// Logging into the bot (THIS INCLUDES THE TOKEN SO DONT INCLUDE IT WHEN SENDING MESSAGES)
client.login(process.env.DISCORD_TOKEN);
Note: I am quite new to JS so. keep that in mind
Your getApp() function doesn't return anything so you are trying to read commands property from undefined value.
You have to return you app.guilds(guildId) so you can read property from it.
const getApp = (guildID) => {
const app = client.api.applications(client.user.id)
if (guildID) {
app.guilds(guildID)
}
return app;
}
client.once('ready', async() => {
client.user.setActivity('FALLBACK BOT, USE THE MAIN CHECKPOINT BOT INSTEAD. THIS IS FOR DEVELOPMENT PURPOSES')
const app = getApp(guildID);
if (app === null) {
console.error('error');
return;
}
const commands = await app.commands.get()
console.log(commands)
await app.commands.post({
data: {
name: 'ping',
description: 'Shows your current ping.',
},
})
});
So I have help.js file where I require all other commands so that I can have access to their usage,
This is my help.js codes:
//Here is how I require all other commands...
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
//If i removed this from here...
const commandFolders = fs.readdirSync('./commands/');
client.commands = new Discord.Collection();
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}/`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../${folder}/${file}`);
client.commands.set(command.name, command);
}
}
//To here... the syntax is now defined on ban.js...
module.exports = {
name: 'help',
syntax: {
syntax: { //I will use this if for example a command has invalid syntax
color: 0xeb4034,
title: 'Oops!',
description: 'Looks like your syntax is invalid, see\n`?help {command}` for more description.'
},
}
execute: async function(message, args) {
//Here I call the ban usage
switch (args[0]) {
case 'ban':
let { usage } = client.commands.get('ban');
return message.channel.send({ embed: usage }); //This worked
}
More codes...
}
But suddenly if I call the syntax in help.js from other file... it is undefined, but if I hover it, it's showing the value of the syntax,
Heres my ban.js codes:
const Discord = require('discord.js');
const { syntax } = require('../Global/help');
module.exports = {
name: 'ban',
usage: {
color: 0x1e90ff,
title: 'Ban',
description: '`Usage:` {prefix}ban user time {optional reason}\n`Example:` ?ban <#message.author.tag> 1h/1m/1s Bad dude'
},
execute: async function(message, args) {
//If I hover on the syntax, it is showing the value, but the result is undefined...
console.log(syntax); //Shows undefined
if (args.length < 1) return message.channel.send({ embed: syntax }); //Made an error
}
}
This is how my files and folders are setup
How do I fix this?
Edit: I found the solution, its not running the code above the module.exports of ban.js so I made a function that returns the syntax
You didn't constructed your client properly
const client = new Discord.Client({
intents: ["GUILDS","GUILD_MEMBERS","GUILD_MESSAGES"]
});