I have the following code:
const { Client, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
const { general } = require('./config.json');
const { guild } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once('ready', () => {
console.log("Ready!");
channel.messages.fetch({ limit: 10 })
.then(messages => console.log(`Received ${messages.size} messages`))
.catch(console.error);
});
client.login(token);
console.log("Online")
But when I run the code I always get this error:
ReferenceError: channel is not defined
at Client.<anonymous> (/workspaces/proJM-bridge/index.js:14:3)
at Object.onceWrapper (node:events:628:26)
at Client.emit (node:events:513:28)
at WebSocketManager.triggerClientReady (/workspaces/proJM-bridge/node_modules/discord.js/src/client/websocket/WebSocketManager.js:385:17)
at WebSocketManager.checkShardsReady (/workspaces/proJM-bridge/node_modules/discord.js/src/client/websocket/WebSocketManager.js:368:10)
at WebSocketShard.<anonymous> (/workspaces/proJM-bridge/node_modules/discord.js/src/client/websocket/WebSocketManager.js:194:14)
at WebSocketShard.emit (node:events:513:28)
at WebSocketShard.checkReady (/workspaces/proJM-bridge/node_modules/discord.js/src/client/websocket/WebSocketShard.js:511:12)
at WebSocketShard.onPacket (/workspaces/proJM-bridge/node_modules/discord.js/src/client/websocket/WebSocketShard.js:483:16)
at WebSocketShard.onMessage (/workspaces/proJM-bridge/node_modules/discord.js/src/client/websocket/WebSocketShard.js:320:10)
I can't find anywhere what is wrong and I have tried many code and still get the same error. Does someone know what I'm doing wrong?
config.json:
{
"token": "Token hidden",
"general": "1028589311282647041",
"guild": "1028241554277679236"
}
First of all you don't need this block:
const { token } = require('./config.json');
const { general } = require('./config.json');
const { guild } = require('./config.json');
You can write it in one line:
const { token, general, guild } = require('./config.json');
And you can fix the error with just defining channel + I think you also need to add the GuildMessages intent to your bot.
const { Client, GatewayIntentBits, TextChannel } = require('discord.js');
const { token } = require('./config.json');
const { general } = require('./config.json');
const { guild } = require('./config.json');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.once('ready', () => {
console.log("Ready!");
/**
* #type {TextChannel}
*/
const channel = client.guilds.cache.get(guild).channels.cache.get(general);
if(!channel) return console.log('Invalid guildId or channelId');
channel.messages.fetch({ limit: 10 })
.then(messages => {
messages.forEach((m) => {
const content = m.content ? m.content : `<No Message Content>`;
const embeds = m.embeds ? `<${m.embeds.length} Embed(s)>` : `<No embeds>`;
const attachments = m.attachments ? `<${m.attachments.size} Attachment(s)>` : `<No Attachments>`;
console.log(`---------------------------\nAuthor: ${m.author.tag}\nContent: ${content}\nEmbeds: ${embeds}\nAttachments: ${attachments}\n---------------------------`);
});
})
.catch(console.error);
});
client.login(token);
I also removed the console.log in the last line bc it's completely useless as you already have one in the ready event.
Related
I've been getting this error recently and I don't really know how I'm supposed to fix this;
TypeError: Cannot read properties of undefined (reading 'get')
This is the line of code it refers to:
const command1 = interaction.client.commands.get(interaction.commandName);
It was working earlier, but I tried adding the command refresh thingy and it's not working anymore.
Here's my full code:
const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const { clientId, guildId, token } = require('./config.json');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
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());
}
client.once('ready', () => {
console.log('Ready!');
});
const rest = new REST({ version: '10' }).setToken(token);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command1 = interaction.client.commands.get(interaction.commandName);
if (!command1) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command1.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
hey try adding this code
const channel = await client.channels.fetch('<channel-id>')
Anything that I change to make this code work just changes said undefined thing.
I have tried to fix using multiple different answers, but no luck.
// Require the necessary discord.js classes
const { Client, GatewayIntentBits, message } = require('discord.js');
const { token } = require('./config.json');
const guildId = '1009548907015057460';
const channelId = '1009548907702915245';
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
if (commandName === 'invite') {
const guild = await client.guilds.fetch(guildId);
console.log(guild);
const channel = await guild.channels.cache.get(channelId);
let invite = await guild.channel.createInvite(
{
maxAge: 300000,
maxUses: 1,
},
'${message.author.tag} requested a invite',
).catch(console.log);
await interaction.deferReply({ ephemeral: true });
await interaction.editReply(invite ? 'Join: ${invite}' : 'Error');
}
}
Anything can help.
You don't need to fetch the guild, you can get the channel from the client
There's no need for await when you're getting information from cache
guild.channel.createInvite should be channel.createInvite
You're using single quotes for variables, they'll end up being strings
There's no need for invite to use let when the value doesn't change
Defer the reply at the beginning rather than right before replying
message.author.tag would return undefined, message doesn't exist. Use interaction.user.tag instead
Add await to channel.createInvite as it returns a promise
Replace ${invite} with ${invite.url}
Also it's best to store the token in a .env file rather than a JSON one.
// Require the necessary discord.js classes
const { Client, GatewayIntentBits, message } = require('discord.js');
const { token } = require('./config.json');
const channelId = '1009548907702915245';
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
await interaction.deferReply({ ephemeral: true });
const { commandName } = interaction;
if (commandName === 'invite') {
const channel = client.channels.cache.get(channelId);
const invite = await channel.createInvite({
maxAge: 604800, // 1 week
maxUses: 1,
reason: `${interaction.user.tag} requested an invite`
}).catch(console.log);
interaction.editReply(invite ? `Join: ${invite.url}` : 'Error');
}
}
Resolving the promise works. This is the code after:
// Require the necessary discord.js classes
const { Client, GatewayIntentBits, message } = require('discord.js');
const { token } = require('./config.json');
const channelId = '1009548907702915245';
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
await interaction.deferReply({ ephemeral: true });
const { commandName } = interaction;
if (commandName === 'invite') {
const channel = client.channels.cache.get(channelId);
const invite = channel.createInvite({
maxAge: 604800, // 1 week
maxUses: 1,
reason: `${interaction.user.tag} requested an invite`
})
.catch(console.log);
const promise = Promise.resolve(invite);
promise.then((value) => {
interaction.editReply(`Join: ${value}`);
});
}
}
I'm kinda new to coding and i cannot figure this out. im trying to add permission handler and when i run a slash command, it responds within the error given below.
error:
D:\VS Code\######\events\interactionCreate.js:9
command.run(client, inter)
^
TypeError: command.run is not a function
code (interactionCreate):
const { MessageEmbed, Message, Interaction } = require("discord.js")
const client = require("../index").client
client.on('interactionCreate', async inter => {
if(inter.isCommand()) {
const command = client.commands.get(inter.commandName);
if(!command) return;
command.run(client, inter)
if (command.help?.permission) {
const authorPerms = inter.channel.permissionsFor(inter.member);
if (!authorPerms || !authorPerms.has(command.permission)) {
const noPerms = new MessageEmbed()
.setColor('RED')
.setDescription(`bruh no perms for ya: ${command.permission}`)
return inter.editReply({embeds: [noPerms], ephemeral: true})
.then((sent) =>{
setTimeout(() => {
sent.delete()
}, 10000)
})
return;
}
}
}
}
)
this is how one of my command file looks like, its a handler which goes "commands > moderation > ban.js"
const { MessageEmbed, Message } = require("discord.js")
module.exports.run = async (client, inter) => {
const user = inter.options.getUser('user')
let BanReason = inter.options.getString('reason')
const member = inter.guild.members.cache.get(user.id)
if(!BanReason) reason = 'No reason provided.'
const existEmbed = new MessageEmbed()
.setColor('#2f3136')
.setDescription('<:pending:961309491784196166> The member does not exist in the server.')
const bannedEmbed = new MessageEmbed()
.setColor('#46b281')
.setDescription(`<:success:961309491935182909> Successfully banned **${user.tag}** from the server with the reason of: **${BanReason}**.`)
const failedEmbed = new MessageEmbed()
.setColor('#ec4e4b')
.setDescription(`<:failed:961309491763228742> Cannot ban **${user.tag}**. Please make sure I have permission to ban.`)
if(!member) return inter.reply({ embeds: [existEmbed]})
try {
await inter.guild.members.ban(member, { reasons: BanReason })
} catch(e) {
return inter.reply({ embeds: [failedEmbed]})
}
inter.reply({ embeds: [bannedEmbed]})
}
module.exports.help = {
name: 'ban',
permission: 'BAN_MEMBERS'
}
btw inter = interaction
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.',
},
})
});
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) {
...
}