Discord Bot Online But Does not Respond - javascript

I have a simple reaction roles bot with a nice anticrash coded with Chalk Package. It was originally made in replit and worked just fine, but I wanted better uptime so I made a repository, loaded it into vscode and compiled it into an executable but I get this error
I tried changing my intents and even going into the discord.js discord server and no one answered me
const express = require('express')
const app = express()
const chalk = require("chalk")
app.get('/', (req, res) => {
res.send('Bot Loaded! Changes Saved!');
});
app.listen(3000, () => {
console.log(
chalk.white('['),
chalk.cyan('Express'),
chalk.white(']'),
chalk.gray(':'),
chalk.white('Connected')
);
});
const {
Client,
Collection,
GatewayIntentBits,
Partials,
} = require("discord.js");
const Discord = require('discord.js')
const client = new Client({
intents: [
"Guilds",
"GuildMessages",
"DirectMessages",
GatewayIntentBits.DirectMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildBans,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const db = require("quick.db")
let pagination = require('./function/pagination')
// ———————————————[Global Variables]———————————————
client.commands = new Collection();
client.aliases = new Collection();
client.cooldowns = new Collection();
client.slashCommands = new Collection();
const Timeout = new Collection();
client.snipes = new Collection()
client.config = require("./botconfig/main.json");
require("./handler")(client);
// Initializing the project.
// ———————————————[Logging Into Client]———————————————
client.login('');
// ———————————————[Error Handling]———————————————
process.on("unhandledRejection", (reason, p) => {
console.log(chalk.gray("—————————————————————————————————"));
console.log(
chalk.white("["),
chalk.red.bold("AntiCrash"),
chalk.white("]"),
chalk.gray(" : "),
chalk.white.bold("Unhandled Rejection/Catch")
);
console.log(chalk.gray("—————————————————————————————————"));
console.log(reason, p);
});
process.on("uncaughtException", (err, origin) => {
console.log(chalk.gray("—————————————————————————————————"));
console.log(
chalk.white("["),
chalk.red.bold("AntiCrash"),
chalk.white("]"),
chalk.gray(" : "),
chalk.white.bold("Uncaught Exception/Catch")
);
console.log(chalk.gray("—————————————————————————————————"));
console.log(err, origin);
});
process.on("multipleResolves", (type, promise, reason) => {
console.log(chalk.gray("—————————————————————————————————"));
console.log(
chalk.white("["),
chalk.red.bold("AntiCrash"),
chalk.white("]"),
chalk.gray(" : "),
chalk.white.bold("Multiple Resolves")
);
console.log(chalk.gray("—————————————————————————————————"));
console.log(type, promise, reason);
});
const Levels = require("discord-xp");
const { mongooseConnectionString } = require("./botconfig/main.json");
Levels.setURL(mongooseConnectionString);
// ———————————————[Anti Ghost ping]———————————————
let { MessageEmbed } = require("discord.js")
client.on('messageCreate', message => {
if(message.author.bot) return;
if(!message.guild) return;
const args = message.content.split(" ").slice(1)
if(message.content.toLowerCase().startsWith("+ghostpingdetector")) {
//=====
let embedon = new MessageEmbed()
.setDescription(":green_square: | Turned On GhostPingDetector")
.setTimestamp()
//===
let embedoff = new MessageEmbed()
.setDescription(":red_square: | Turned Off GhostPingDetector")
.setTimestamp()
//====
if(!args[0]) return message.reply('Do You Want To Turn On or Off ghostpingdetector? Please Type \`w?ghostpingdetector true/false\` or \`on/off\`');
if(args[0] === "on" || args[0] === "true") {
message.reply({embeds: [embedon]})
db.set(`gp_${message.author.id}`, true)
} else if(args[0] === "off" || args[0] === "false") {
db.delete(`gp_${message.author.id}`)
message.reply({embeds: [embedoff]})
}
}[![enter image description here](https://i.stack.imgur.com/4SanR.png)](https://i.stack.imgur.com/4SanR.png)
})
client.on('messageDelete', message => {
message.mentions.users.forEach(m => {
if(db.has(`gp_${m.id}`) && m.id !== message.author.id && !message.author.bot){
let emb = new MessageEmbed()
emb.setTitle('GhostPingDetector')
emb.setDescription(`<#${m.id}>, You've Been Ghost Pinged.\nUserName: \`${message.author.username}\`\nUserID: \`${message.author.id}\`\nServerName: ${message.guild.name}\nChannel: <#${message.channel.id}>\nContent: ${message.content}`)
emb.setColor("GREEN")
emb.setFooter(`Anti-Ghost Ping! woop woop`)
m.send({embeds: [emb]})
message.channel.send({embeds: [emb]})
}
})
})
client.on('message', message => {
if (message.channel.id === '1029286082879180832') {
message.react('✅');
}
});

Related

discord.js 12.5.3 can't send message, but status online

Index.js
const Discord = require("discord.js");
const client = new Discord.Client({ disableMentions: 'everyone' });
require('dotenv').config();
const Eco = require("quick.eco");
client.eco = new Eco.Manager();
client.db = Eco.db;
client.config = require("./config");
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
const fs = require("fs");
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err);
files.forEach(f => {
if (!f.endsWith(".js")) return;
const event = require(`./events/${f}`);
let eventName = f.split(".")[0];
client.on(eventName, event.bind(null, client));
});
});
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(f => {
if (!f.endsWith(".js")) return;
let command = require(`./commands/${f}`);
client.commands.set(command.help.name, command);
command.help.aliases.forEach(alias => {
client.aliases.set(alias, command.help.name);
});
});
});
client.login(process.env.TOKEN);
Message.js
const { MessageEmbed } = require('discord.js');
const fs = require('fs');
let visitor = require('../database/visitor.json');
let level = require('../database/level.json');
let place = require('../database/place.json');
let money = require('../database/money.json');
module.exports = async (client, message) => {
if (message.content === "market") {
message.reply(`yup, what?`);
}
if(!visitor[message.author.id]){
visitor[message.author.id] = {
totalvis: 0,
totalbuyer: 0
};
}
if(!level[message.author.id]){
level[message.author.id] = {
level: 1,
exp: 0
};
}
if(!place[message.author.id]){
place[message.author.id] = {
pla: "Hongria"
};
}
if(!money[message.author.id]){
money[message.author.id] = {
balance: 20
};
}
if(level[message.author.id].exp > 300) {
let amount = Math.floor(Math.random() * 60) + 20;
money[message.author.id].balance = money[message.author.id].balance + amount;
level[message.author.id].level++;
level[message.author.id].exp = 0;
let embed = new MessageEmbed()
.setTitle(`${message.author.username} Level Up`)
.addField(`Rewards`, `+ ${amount} Money`)
.setColor("#E5E5E5")
.setTimestamp()
message.channel.send(embed);
}
fs.writeFile('./database/visitor.json', JSON.stringify(visitor, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/level.json', JSON.stringify(level, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/place.json', JSON.stringify(place, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/money.json', JSON.stringify(money, null, 2), (err) => {
if (err) console.log(err);
});
if (!message.guild || message.author.bot) return;
if (message.channel.id === client.config.countChannel) require("../counter")(message, client);
client.prefix = client.db.fetch(`prefix_${message.guild.id}`) ? client.db.fetch(`prefix_${message.guild.id}`) : client.config.prefix;
if (!message.content.startsWith(client.prefix)) return;
let args = message.content.slice(client.prefix.length).trim().split(" ");
let commandName = args.shift().toLowerCase();
let command = client.commands.get(commandName) || client.commands.get(client.aliases.get(commandName));
if (!command) return;
client.ecoAddUser = message.author.id;
command.execute(client, message, args);
};
Command.js
const { MessageEmbed } = require("discord.js");
const fs = require('fs');
exports.execute = async (client, message, args) => {
if (!client.config.admins.includes(message.author.id)) return;
message.channel.send("**Rebooting system..**").then(m => {
setTimeout(() => {
m.edit("**Wait a sec...**").then(ms => {
setTimeout(() => {
ms.edit("**Done.**")
}, 3000)
})
}, 3000);
})
.then(message => process.exit())
.then(() => client.login(process.env.TOKEN))
}
exports.help = {
name: "reboot",
aliases: ["rb"],
usage: `reboot`
}
I use Discord.js version 12.5.3, my discord bot status is online, but if I try some command, my bot not send any message but in console, no errors. I used to be able to use this method, but now I want to try to make a discord bot again, and I use the same code without changing anything, but now my bot can't send any messages
I turn Privileged Gateway Intents in Discord Developer Portal, and it work!

message event updating discord.js from v12 to v13

I have a discord bot, and I was using v12. When the new v13 version came out, I tried to update my bot but it was too much for me. Now, I tried again and it went a little better. Now at least it gets on, but doesn´t reply! When I execute the help command, it returns me this error:
TypeError: message.channel.startTyping is not a function
at Client.module.exports (/app/events/messageCreate.js:172:21)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
This is my bot.js file:
const { Client, Intents } = require('discord.js');
const Discord = require("discord.js");
const { I18n } = require("locale-parser");
const Mongoose = require("mongoose");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
//client.errors = require("./modules/errors");
client.config = require("./config.json");
client.i18n = new I18n({ defaultLocale: "en" });
Mongoose.connect(client.config.mongo_uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
client.database = Mongoose.connection;
client.database.on("error", err => {
throw err;
});
client.database.once("open", async () => {
require("./models");
require("./handlers/eventHandler")(client);
require("./handlers/moduleHandler")(client);
client.login(process.env.BOT_TOKEN);
});
And this one, is app/events/messageCreate.js:
const Discord = require("discord.js");
const embeds = require("../modules/embeds.js");
const cooldown = {};
const Uses = require("../models/uses.js");
const Enmap = require("enmap");
const db = require("megadb"); //aca definimos db para lo que necesitemos mas adelante
let desactivadodb = new db.crearDB("ComandosDesactivados");
const fs = require("fs");
const guildModel = require("../models/guildModel");
var language = "";
module.exports = async message => {
try {
const bot = message.client;
const funcs = require("../modules/functions.js");
bot.color = funcs.color(message);
bot.lang = funcs.lang(message) || "en";
bot.langs = message.guild.language || language;
const msg = message;
if (msg.author.bot || !msg.guild) return;
let prefix = bot.config.prefixes[0];
let argsSlice = prefix.length;
if (!msg.content.toLowerCase().startsWith(prefix.toLowerCase())) {
let content = msg.content.trim();
let mention1 = "<#!" + bot.user.id + ">";
let mention2 = "<#" + bot.user.id + ">";
if (content == mention1 || content == mention2)
return embeds.mention(msg, prefix, bot);
if (content.startsWith(mention1)) argsSlice = mention1.length;
else if (content.startsWith(mention2)) argsSlice = mention2.length;
else return;
}
let args = msg.content
.slice(argsSlice)
.trim()
.split(/ +/g);
let command = args.shift().toLowerCase();
let cmdFile =
bot.commands.get(command) ||
bot.commands.find(
cmdFile => cmdFile.aliases && cmdFile.aliases.includes(command)
);
if (!cmdFile) return;
if (message.guild && !message.guild.language) {
let language = "en";
let guildDocument = await guildModel.findOne({
guildID: message.guild.id
});
if (guildDocument && guildDocument.language)
message.guild.language = guildDocument.language;
}
if (!message.guild) {
let language = "en"
};
if (cmdFile.guildOnly && !message.guild)
return await message.channel.send(
message.client.i18n.get(language, "errors", "command_guild_only")
);
if (
!cmdFile.enabled ||
desactivadodb.tiene(
`ComandosDesactivados_${command}_${message.guild.id}`,
`g${message.guild.id}`
)
)
return await message.channel.send(
message.client.i18n.get(
message.guild.language,
"errors",
"command_disabled"
)
);
if (
cmdFile.ownerOnly &&
!message.client.config.owners.includes(message.author.id)
)
return await message.channel.send(
message.client.i18n.get(
language,
"errors",
"command_owner_only",
{ command: cmdFile.name }
)
);
if (cmdFile.nsfwOnly && !message.channel.nsfw)
return await message.channel.send(
message.client.i18n.get(language, "errors", "nsfw_only", {
command: cmdFile.name
})
);
if (
cmdFile.permissions &&
!// message.client.config.owners.includes(message.author.id) ||
message.member.permissions.has(cmdFile.permissions || "ADMINISTRATOR")
)
return await message.channel.send(
message.client.i18n.get(
language,
"errors",
"not_enough_permission",
{ permissions: cmdFile.permissions.join(", ") }
)
);
if (
cmdFile.botpermissions &&
!message.guild.me.permissions.has(
cmdFile.botpermissions || "ADMINISTRATOR"
)
)
return await message.channel.send(
message.client.i18n.get(
language,
"errors",
"not_bot_enough_permission",
{ permissions: cmdFile.botpermissions.join(", ") }
)
);
let numuses = 1;
Uses.findOne(
{
command: cmdFile.name
},
(err, res) => {
if (err) console.log(err);
if (!res) {
const newDoc = new Uses({
command: cmdFile.name,
uses: 0
});
newDoc.save().catch(err => console.log(err));
} else {
res.uses = res.uses + numuses;
res.save().catch(err => console.log(err));
}
}
);
if (cmdFile.cooldown) {
if (!cooldown[msg.author.id]) cooldown[msg.author.id] = {};
let time = cooldown[msg.author.id][cmdFile.name] || 0;
if (time && time > Date.now()) {
let wait = ((time - Date.now()) / 1000).toFixed(2);
return message.channel.send(
message.client.i18n.get(
language,
"errors",
"wait_cooldown",
{ cooldown: wait, command: cmdFile.name }
)
);
}
cooldown[msg.author.id][cmdFile.name] =
Date.now() + cmdFile.cooldown * 1000;
}
message.channel.startTyping();
cmdFile.exec(bot, msg, args).then(message.channel.stopTyping());
} catch (err) {
console.error(err);
}
};
I just changed the Client thing of the bot.js, but I think I don´t understand the actual module.exports and I am very sure that there is where the error is.
In discord.js v13 TextChannel.startTyping() method was replaced by TextChannel.sendTyping() which you have to use now! As moving to v13 guide says: "This method automatically stops typing after 10 seconds, or when a message is sent"!

Discord.js "cannot read properties of undefined" when trying to put event handler into a seperate file

So I have been working on a discord bot. At first, I've put every event handler into index.js, which worked perfectly well.
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json');
const fs = require('fs');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS],
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
}
catch (err) {
console.log(err);
await interaction.reply('There was an error while executing this command!');
}
});
client.on('messageReactionAdd', (reaction, user) => {
const channel = client.channels.cache.find(channel => channel.name === "test");
let message = 874736592542105640;
let emotes = [ "kannathinking", "🍎"];
let roleID = (reaction.emoji.name == emotes[0] ? "874730080486686730" : "874729987310235738")
if (message == reaction.message.id && (emotes[0] == reaction.emoji.name || emotes[1] == reaction.emoji.name)) {
channel.send(`${user} was given the <#&${roleID}> role`);
}
});
client.on('messageReactionRemove', (reaction, user) => {
const channel = client.channels.cache.find(channel => channel.name === "test");
let message = 874736592542105640;
let emotes = [ "kannathinking", "🍎"];
let roleID = (reaction.emoji.name == emotes[0] ? "874730080486686730" : "874729987310235738")
if (message == reaction.message.id && (emotes[0] == reaction.emoji.name || emotes[1] == reaction.emoji.name)) {
channel.send(`${user} was removed from the <#&${roleID}> role`);
}
});
client.login(token);
Then I tried storing the event-handlers in seperate files, just like I did with the commands.
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json');
const fs = require('fs');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS],
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('js'));
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
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);
This however didn't work well. As I started the bot it gave me positive feedback. As soon as I tried to react to a message on my discord server however, it threw the following error:
TypeError: cannot read properties of undefined (reading 'cache')
The messageReactionAdd.js event file looks like this:
module.exports = {
name: 'messageReactionAdd',
execute(client, reaction, user) {
const channel = client.channels.cache.find(channel => channel.name === "test");
let message = 874736592542105640;
let emotes = ["kannathinking", "🍎"];
let roleID = (reaction.emoji.name == emotes[0] ? "874730080486686730" : "874729987310235738")
if (message == reaction.message.id && (emotes[0] == reaction.emoji.name || emotes[1] == reaction.emoji.name)) {
channel.send(`${user} was given the <#&${roleID}> role`);
}
}
}
I tried fixing the error by requiring the client object I created in index.js, aswell as requiring "Client" from discord.js. Both didn't work and I can't figure out what is missing in the event file so that it works.
When requiring the event file, you never defined client therefore when you call client.channels in the event handler, it doesn't actually know what client is.
To fix this issue, when executing the function, define client before the args.
Example:
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(client, ...args));
} else {
client.on(event.name, (...args) => event.execute(client, ...args));
}
}

Startup TypeError: Cannot read property 'Collection' of undefined

So I've had multiple problems one after another. The first being;
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client
Which I solved by changing up my code from:
const Discord = require("discord.js");
const bot = new Discord.Client();
To:
const { Client, Intents, Discord } = require("discord.js");
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
But now I am running into a seperate issue. Where I keep getting this error;
Startup TypeError: Cannot read property 'Collection' of undefined
This is really frustrated because I've been at this problem for a couple of hours. Any help would be massively appreciated!
All essential code:
const { Client, Intents } = require("discord.js");
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { prefix, token, mongoPath } = require("./jsonFiles/config.json");
const mongoose = require("mongoose");
const mongo = require("./utility/mongo.js");
const fs = require("fs");
const Levels = require("discord-xp");
bot.login(token);
bot.commands = new Discord.Collection();
bot.cooldowns = new Discord.Collection();
const commandFolders = fs.readdirSync("./commands");
for (const folder of commandFolders) {
//Finds the name of the command
const commandFiles = fs
.readdirSync(`./commands/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
bot.commands.set(command.name, command);
}
}
bot.on("ready", async () => {
console.log("Connect as " + bot.user.tag);
//levels(bot);
await mongo().then(() => {
try {
console.log("Connected to mongo!");
} finally {
mongoose.connection.close();
}
});
bot.user.setActivity(".help", {
type: "WATCHING",
});
});
bot.on("message", async (message) => {
try {
await mongo().then(async (mongoose) => {
Levels.setURL(mongoPath);
if (!message.guild) return;
if (message.author.bot) return;
const randomAmountOfXp = Math.floor(Math.random() * 20) + 1; // Min 1, Max 30
const hasLeveledUp = await Levels.appendXp(
message.author.id,
message.guild.id,
randomAmountOfXp
);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(
`${message.author}, congratulations! You have leveled up to **${user.level}** in \`${message.guild.name}\` :sunglasses:`
);
}
});
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 =
bot.commands.get(commandName) ||
bot.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.permissions) {
const authorPerms = message.channel.permissionsFor(message.author);
if (!authorPerms || !authorPerms.has(command.permissions)) {
if (message.author.id !== "344834268742156298") {
return message.reply("YOU DO NOT HAVE PERMISSION (git gud scrub)");
}
}
}
if (command.creator === true && message.author.id !== "344834268742156298")
return message.reply("Wait what, you are not creator man, you cannot use the command!!!!!");
if (command.args === true && !args.length) {
let reply = `You didn't provide a valid arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
message.delete({
timeout: 25 * 1000,
});
return message.channel.send(reply).then((message) => {
message.delete({
timeout: 25 * 1000,
});
});
}
const { cooldowns } = bot;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown ?? 1.5) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(
`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${
command.name
}\` command.`
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
const maxArguments = command.maxArgs || null;
if (
args.length < command.minArgs ||
(maxArguments !== null && command.args === "true" && args.length > command.maxArgs)
) {
let reply = `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
return message.channel.send(reply);
}
try {
command.execute(message, args, message.guild);
} catch (err) {
console.log(err);
}
} catch (err) {
console.log(err);
}
});
At the top you never defined Discord properly. You are trying to access the non-existant Discord property of the discord.js module with object destructuring. There are 2 quick fixes for this, the first one will be faster however.
//at the top change the declaration of Client
const Discord = {
Client,
Intents
} = require('discord.js')
//Discord is module discord.js
Or you can do
const {
Collection,
Client,
Intents
} = require('discord.js')
//use new Collection() instead of new Discord.Collection()
Try instead of:
const { Client, Intents } = require("discord.js");
Try:
const Discord = require("discord.js"), { Client, Intents } = Discord;
Or you can also import Collection from discord:
const { Client, Intents, Collection } = require("discord.js");
and replace:
new Discord.Collection() with new Collection()

Discord.js bot can't send message to specific channel

I'm trying to make my bot send a message to a specific channel on Discord. However, when I use the command it results in an error: TypeError: Cannot read property 'cache' of undefined .
Here's my code:
module.exports = {
name: 'send',
description: 'sends a message testing',
execute(client) {
const channel01 = client.channels.cache.find(channel => channel.id === "768667222527705148");
channel01.send('Hi');
},
};
In my index.js file, I have the following in the beginning, so I don't think the client usage in front of .channels is the problem.
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
Here's my Index.js file.
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
const cooldowns = new Discord.Collection();
client.once('ready', () => {
console.log('Ready!');
client.user.setActivity("KevinYT", {
type: "WATCHING",
url: "https://www.youtube.com/channel/UCUr50quaTjBKWL1fLuWRvCg?view_as=subscriber"
});
});
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 = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
What am I missing? Thanks!
command.execute(message, args)
You're passing the execute function message (a Message object) as the first argument but you're trying to use it as a Client object. The code fails since message.channels is undefined (the confusion arises from the argument name used in the execute function).
You can use message.client to get access to the Client object.
module.exports = {
// ...
execute (message) {
const channel01 = message.client.channels.cache.find(
(channel) => channel.id === '768667222527705148'
)
// ...
},
}

Categories

Resources