Discord.js Cannot read property 'name' - javascript

can someone help me fix this error? It's causing me some critical damage.
const Discord = require('discord.js');
const config = require('./config.json');
const bot = new Discord.Client();
const cooldowns = new Discord.Collection();
const fs = require('fs');
bot.commands = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if (err) console.log(err);
let jsfile = files.filter((f) => f.split('.').pop() === 'js');
if (jsfile.length <= 0) {
console.log('No Commands fonud!');
return;
}
jsfile.forEach((f, i) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
});
fs.readdir('./events/', (error, f) => {
if (error) console.log(error);
console.log(`${f.length} Loading events...`);
f.forEach((f) => {
const events = require(`./events/${f}`);
const event = f.split('.')[0];
client.on(event, events.bind(null, client));
});
});
});
let statuses = ['By LeRegedit#1281', 'Prefix => !', 'V1.0', 'Coming Soon'];
bot.on('ready', () => {
console.log(bot.user.username + ' is online !');
setInterval(function() {
let status = statuses[Math.floor(Math.random() * statuses.length)];
bot.user.setPresence({ activity: { name: status }, status: 'online' });
}, 10000);
});
bot.on('message', async (message) => {
if (message.author.bot) return;
if (message.channel.type === 'dm') return;
let content = message.content.split(' ');
let command = content[0];
let args = content.slice(1);
let prefix = config.prefix;
let commandfile = bot.commands.get(command.slice(prefix.length));
if (commandfile) commandfile.run(bot, message, args);
if (!message.content.startsWith(prefix)) return;
});
bot.login(config.token);
Type Error: Cannot read property 'name' of undefined

Related

405 Error using slash command handler Discord.js

I got a 405: Method Not Allowed error when I was running the slash command builder.
There's the code:
const { glob } = require("glob");
const { promisify } = require("util");
const { Client } = require("discord.js");
const mongoose = require("mongoose");
const globPromise = promisify(glob);
/**
* #param {Client} client
*/
module.exports = async (client) => {
// Commands
const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
commandFiles.map((value) => {
const file = require(value);
const splitted = value.split("/");
const directory = splitted[splitted.length - 2];
if (file.name) {
const properties = { directory, ...file };
client.commands.set(file.name, properties);
}
});
// Events
const eventFiles = await globPromise(`${process.cwd()}/events/*.js`);
eventFiles.map((value) => require(value));
// Slash Commands
const slashCommands = await globPromise(
`${process.cwd()}/SlashCommands/*/*.js`
);
const arrayOfSlashCommands = [];
slashCommands.map((value) => {
const file = require(value);
if (!file?.name) return;
client.slashCommands.set(file.name, file);
if (["MESSAGE", "USER"].includes(file.type)) delete file.description;
if (file.userPermissions) file.defaultPermission = false;
arrayOfSlashCommands.push(file);
});
client.on("ready", async () => {
// Register for a single guild
const guild = client.guilds.cache.get("1014471738844790844");
await guild.commands.set(arrayOfSlashCommands).then((cmd) => {
const getRoles = (commandName) => {
const permissions = arrayOfSlashCommands.find((x) => x.name === commandName).userPermissions;
if (!permissions) return null;
return guild.roles.cache.filter(x => x.permissions.has(permissions) && !x.managed);
};
const fullPermissions = cmd.reduce((accumulator, x) => {
const roles = getRoles(x.name);
if (!roles) return accumulator;
const permissions = roles.reduce((a, v) => {
return [
...a,
{
id: v.id,
type: 'ROLE',
permission: true,
}
];
}, []);
return [
...accumulator,
{
id: x.id,
permission: permissions,
}
];
}, []);
guild.commands.permissions.set({ fullPermissions });
});
// Register for all the guilds the bot is in
// await client.application.commands.set(arrayOfSlashCommands);
});
// mongoose
const { mongooseConnectionString } = require('../config.json')
if (!mongooseConnectionString) return;
mongoose.connect(mongooseConnectionString).then(() => console.log('Connected to mongodb'));
};
There's the interactionCreate.js file:
const client = require("../index");
client.on("interactionCreate", async (interaction) => {
// Slash Command Handling
if (interaction.isCommand()) {
await interaction.deferReply({ ephemeral: false }).catch(() => { });
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "An error has occurred " });
const args = [];
for (let option of interaction.options.data) {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
if (!interaction.member.permissions.has(cmd.userPermissions || [])) return interaction.followUp({ content: `Error: Mission Permissions.` });
cmd.run(client, interaction, args);
}
// Context Menu Handling
if (interaction.isContextMenu()) {
await interaction.deferReply({ ephemeral: false });
const command = client.slashCommands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
});
And there's the error I got:
C:\Users\pines\OneDrive\桌面\ROBO_Head-v2\node_modules\discord.js\src\rest\RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: 405: Method Not Allowed
at RequestHandler.execute (C:\Users\pines\OneDrive\桌面\ROBO_Head-v2\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\pines\OneDrive\桌面\ROBO_Head-v2\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async ApplicationCommandPermissionsManager.set (C:\Users\pines\OneDrive\桌面\ROBO_Head-v2\node_modules\discord.js\src\managers\ApplicationCommandPermissionsManager.js:186:18) {
method: 'put',
path: '/applications/991997852538634311/guilds/1014471738844790844/commands/permissions',
code: 0,
httpStatus: 405,
requestData: { json: [], files: [] }
}
Discord.js version is 13.11.0, bot has administrator permission on the server.
Please help me solve this.

I want my discord bot to send a random message to a text room given by user [by channel id or channel name]

so what I am trying to do is when a user write a command such as
!setchannel #test or !setchannel 86xxxxxxxxxxxxxxx
then the bot will send the random messages to that channel every certain time.
Note that I did the random messages code but I still stuck on creating the !setchannel command.
I am using discord.js v12.5.3
index.js main file
require('events').EventEmitter.prototype._maxListeners = 30;
const Discord = require('discord.js')
const client = new Discord.Client()
require('discord-buttons')(client);
const ytdl = require('ytdl-core');
const config = require('./config.json')
const mongo = require('./mongo')
const command = require('./command')
const loadCommands = require('./commands/load-commands')
const commandBase = require('./commands/command-base')
const { permission, permissionError } = require('./commands/command-base')
const cron = require('node-cron')
const zkrList = require('./zkr.json')
const logo =
'URL HERE'
const db = require(`quick.db`)
let cid;
const { prefix } = config
client.on('ready', async () => {
await mongo().then((mongoose) => {
try {
console.log('Connected to mongo!')
} finally {
mongoose.connection.close()
}
})
console.log(`${client.user.tag} is online`);
console.log(`${client.guilds.cache.size} Servers`);
console.log(`Server Names:\n[ ${client.guilds.cache.map(g => g.name).join(", \n ")} ]`);
loadCommands(client)
cid = db.get(`${message.guild.id}_channel_`)
cron.schedule('*/10 * * * * *', () => {
const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
const zkrEmbed = new Discord.MessageEmbed()
.setDescription(zkrRandom)
.setAuthor('xx', logo)
.setColor('#447a88')
client.channels.cache.get(cid).send(zkrEmbed);
})
client.on("message", async message => {
if (message.author.bot) {
return
}
try {if (!message.member.hasPermission('ADMINISTRATOR') && message.content.startsWith('!s')) return message.reply('you do not have the required permission') } catch (err) {console.log(err)}
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const cmd = args[0]
if (cmd === "s") {
let c_id = args[1]
if (!c_id) return message.reply("you need to mention the text channel")
c_id = c_id.replace(/[<#>]/g, '')
const channelObject = message.guild.channels.cache.get(c_id);
if (client.channels.cache.get(c_id) === client.channels.cache.get(cid)) return message.reply(`we already sending to the mentioned text channel`);
if (client.channels.cache.get(c_id)) {
await db.set(`${message.guild.id}_channel_`, c_id); //Set in the database
console.log(db.set(`${message.guild.id}_channel_`))
message.reply(`sending to ${message.guild.channels.cache.get(c_id)}`);
cid = db.get(`${message.guild.id}_channel_`)
const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
const zkrEmbed = new Discord.MessageEmbed()
.setDescription(zkrRandom)
.setAuthor('xx', logo)
.setColor('#447a88')
client.channels.cache.get(cid).send(zkrEmbed);
} else {
return message.reply("Error")
}
}
})
})
client.login(config.token)
zkr.json json file
[
"message 1",
"message 2",
"message 3"
]
You'll have to use a database to achieve what you're trying to do
An example using quick.db
const db = require(`quick.db`)
const prefix = "!"
client.on("message", async message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const cmd = args[0]
if (cmd === "setchannel") {
let c_id = args[1]
if (!c_id) return message.reply("You need to mention a channel/provide id")
c_id = c_id.replace(/[<#>]/g, '')
if (client.channels.cache.get(c_id)) {
await db.set(`_channel_`, c_id) //Set in the database
} else {
return message.reply("Not a valid channel")
}
}
})
Changes to make in your code
client.on('ready', async () => {
let c_id = await db.get(`_channel_`)
cron.schedule('*/10 * * * * *', () => {
const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
const zkrEmbed = new Discord.MessageEmbed()
.setTitle('xx')
.setDescription(zkrRandom)
.setFooter("xx")
.setColor('#447a88')
.setAuthor('xx#8752')
client.channels.cache.get(c_id).send(zkrEmbed)
})
})
The above sample of quick.db is just an example
If you're using repl.it, I recommend you to use quickreplit
Edit
require('events').EventEmitter.prototype._maxListeners = 30;
const Discord = require('discord.js')
const client = new Discord.Client()
const ytdl = require('ytdl-core');
const config = require('./config.json')
const mongo = require('./mongo')
const command = require('./command')
const loadCommands = require('./commands/load-commands')
const commandBase = require('./commands/command-base')
const cron = require('node-cron')
const zkrList = require('./zkr.json')
const db = require(`quick.db`)
const prefix = "!"
let cid;
client.on('ready', async () => {
await mongo().then((mongoose) => {
try {
console.log('Connected to mongo!')
} finally {
mongoose.connection.close()
}
})
console.log(`${client.user.tag} is online`);
console.log(`${client.guilds.cache.size} Servers`);
console.log(`Server Names:\n[ ${client.guilds.cache.map(g => g.name).join(", \n ")} ]`);
cid = db.get('_channel_')
loadCommands(client)
//commandBase.listen(client);
})
cron.schedule('*/10 * * * * *', () => {
const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
const zkrEmbed = new Discord.MessageEmbed()
.setTitle('xx')
.setDescription(zkrRandom)
.setFooter("xx")
.setColor('#447a88')
.setAuthor('xx#8752')
client.channels.cache.get(cid).send(zkrEmbed);
})
client.on("message", async message => {
console.log(db.get('_channel_'))
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const cmd = args[0]
if (cmd === "s") {
let c_id = args[1]
if (!c_id) return message.reply("You need to mention a channel/provide id")
c_id = c_id.replace(/[<#>]/g, '')
if (client.channels.cache.get(c_id)) {
console.log('old channel')
console.log(db.get('_channel_'))
await db.set(`_channel_`, c_id); //Set in the database
message.reply(`sending in this channel ${message.guild.channels.cache.get(c_id)}`);
} else {
return message.reply("Not a valid channel")
}
}
})

I'm having issues in Discord.js with functions like client.users.cache.size

Whenever I try to use a function like client.users.cache.size or client.guilds.size, they keep giving me an error like "TypeError: Cannot read property 'guilds' of undefined" or "TypeError: Cannot read property 'cache' of undefined".
I was also trying to use let guilds = client.guilds.cache.array().join('\n') but it also throws the same error.
Command's code:
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(client, message) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
Bot's main file:
const path = require('path');
const fs = require("fs");
const { token, prefix } = require('./config.json');
const Discord = require('discord.js');
const db = require ('quick.db');
const client = new Discord.Client
client.commands = new Discord.Collection();
const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);
getDirectories(__dirname + '/commands').forEach(category => {
const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));
for(const file of commandFiles) {
const command = require(`${category}/${file}`);
client.commands.set(command.name, command);
}
});
client.on("ready", () => {
console.log(`ready!.`);
console.log(token);
// Activities
const activities_list = [
`Serving Tacos | .help`,
`Preparing Orders | .help`
];
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index]);
}, 10000);
});
//Joined Guild
client.on("guildCreate", (guild) => {
const EmbedJoin = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Joined Guild: ${guild.name}!`)
.setTimestamp()
console.log(`Joined New Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedJoin)
});
//Left Guild
client.on("guildDelete", (guild) => {
const EmbedLeave = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Left Guild: ${guild.name}.`)
.setTimestamp()
console.log(`Left Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedLeave)
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `${message.author}, wrong usage`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
process.on("error", () => {
console.log("Oops something happened!");
});
client.login(token);
In your code, client.guilds returns a manager, so you have to use client.guilds.cache.size. The rest of the code works fine.
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(message, args, client) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.cache.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
In your main bot file you're only passing the message and the args (in this order) to command.execute(). You can add the client too, and update the parameters in your command's code to match this order.
try {
command.execute(message, args, client);
} catch (error) {
...
}

ROBLOX Discord bot

I'm trying to create a discord bot that connects to a Roblox account that I made.
I'm trying to create a command that will shout a message in a group, but there's a problem at the login and I can't figure out how to fix the problem.
let roblox = require('noblox.js');
const { Client } = require("discord.js");
const { config } = require("dotenv");
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
});
let prefix = process.env.PREFIX
let groupId = groupid;
client.on("ready", () => {
console.log("I'm Ready!");
function login() {
roblox.cookieLogin(process.env.COOKIE)
}
login()
.then(function () {
console.log(`Logged in to ${username}`);
})
.catch(function (error) {
console.log(`Login error: ${error}`);
});
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "shout") {
if (!args) {
return;
message.reply("You didn't specify a message to shout.")
}
const shoutMSG = args.join(" ");
roblox.shout(groupId, shoutMSG)
.then(function() {
console.log(`Shouted ${shoutMSG}`);
})
.catch(function(error) {
console.log(`Shout error: ${error}`)
});
}
})
client.login(process.env.TOKEN);
It gives me the error:
Shout error: Error: Shout failed, verify login, permissions, and message
At the first you don`t close you client.on('ready') state.
if (!args) {
return;
message.reply("You didn't specify a message to shout.")
}
This funcyion will never reply, because you use return, before reply.
Your groupId looks like undefined, because you declarate it let groupId = groupid;, so this is the one way, why got you got this error.
let roblox = require('noblox.js');
const { Client } = require("discord.js");
const { config } = require("dotenv");
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
});
let prefix = process.env.PREFIX
let groupId = groupid;
client.on("ready", () => {
console.log("I'm Ready!");
})
function login() {
roblox.cookieLogin(process.env.COOKIE)
}
login()
.then(function () {
console.log(`Logged in to ${username}`);
})
.catch(function (error) {
console.log(`Login error: ${error}`);
});
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "shout") {
if (!args) return message.reply("You didn't specify a message to shout.")
const shoutMSG = args.join(" ");
roblox.shout(groupId, shoutMSG)
.then(function() {
console.log(`Shouted ${shoutMSG}`);
})
.catch(function(error) {
console.log(`Shout error: ${error}`)
});
}
})
client.login(process.env.TOKEN);

Save JSON file to grab other data from it later

I want to be able to save my json file with new data and then call upon that data so that I can save new data again. Right now all it is doing is it is, when I call upon any part of the JSON file's data, staying the same the last time I manually saved it. (I did edit some code and a better description of my problem) Thank you in advance! Here is my code there is no error log:
const Discord = require('discord.js');
const botconfig = require("./botconfig.json");
const fs = require("fs");
const bot = new Discord.Client();
bot.on("message", async message => {
let prefix = botconfig.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
console.log(message.member.id)
var playerFile = require(`./playerData/${message.member.id}.json`);
if (message.author.bot) return;
if (message.channel.type === "dm") return;
if (cmd.charAt(0) === prefix) {
if(cmd === `${prefix}fc`){
fs.exists(`./playerData/${message.member.id}.json`, function(exists) {
if(exists){
let ar = args[0];
let ninConsole = args[1];
let code = args[2];
if(ar === "add" || ar === "remove"){
if(code){
if(ar === "add"){
console.log("Add");
if(ninConsole === "switch"){
console.log("Switch " + code);
let fileContent = `{"switch": "${code}","threeDS": "${playerFile.threeDS}"}`
fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
if (err) {
console.error(err);
return;
};
});
}
if(ninConsole === "3ds"){
let fileContent = `{"switch": "${playerFile.switch}","threeDS": "${code}"}`
fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
if (err) {
console.error(err);
return;
};
});
}
}
if(ar === "remove"){
if(ninConsole === "switch"){
let fileContent = `{"switch": "None","threeDS": "${playerFile.threeDS}"}`
fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
if (err) {
console.error(err);
return;
};
});
}
if(ninConsole === "3ds"){
let fileContent = `{"switch": "${playerFile.switch}","threeDS": "None"}`
fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
if (err) {
console.error(err);
return;
};
});
}
}
}
}
}else{
return;
}
});
}
Here is an example of saving data to a JSON file using fs:
JSON.parse(fs.readFileSync("./points.json", "utf8"));
There is an example on how to use this code to make a points system for a discord bot here: https://anidiotsguide_old.gitbooks.io/discord-js-bot-guide/content/coding-guides/storing-data-in-a-json-file.html
Here is the code for this example:
const Discord = require("discord.js");
const fs = require("fs");
const client = new Discord.Client();
let points = JSON.parse(fs.readFileSync("./points.json", "utf8"));
const prefix = "+";
client.on("message", message => {
if (!message.content.startsWith(prefix)) return;
if (message.author.bot) return;
if (!points[message.author.id]) points[message.author.id] = {
points: 0,
level: 0
};
let userData = points[message.author.id];
userData.points++;
let curLevel = Math.floor(0.1 * Math.sqrt(userData.points));
if (curLevel > userData.level) {
// Level up!
userData.level = curLevel;
message.reply(`You"ve leveled up to level **${curLevel}**! Ain"t that dandy?`);
}
if (message.content.startsWith(prefix + "level")) {
message.reply(`You are currently level ${userData.level}, with ${userData.points} points.`);
}
fs.writeFile("./points.json", JSON.stringify(points), (err) => {
if (err) console.error(err)
});
});
client.login("SuperSecretBotTokenHere");
I hope this helps!

Categories