So I have this strange problem. I am trying to validate that the channel ID exist in the guild and if it does then I want it to do something. But I just can't get it to work.
Normally bot.channels.cache.get(args[0]) would return all the channel info, but for whatever reason it always returns undefined and I don't understand why. (This was written in Discord.JS 1.12.5 not the latest version)
const mongoDB = require("../../utility/mongodbFramework");
const Discord = require("discord.js");
const bot = new Discord.Client();
module.exports = {
name: "welcome",
aliases: ["setwelcome", "welcome"],
description: "Server config",
args: true,
maxArgs: 2,
minArgs: 2,
cooldown: 1,
permissions: "ADMINISTRATOR",
usage: "<channelId> <message>",
async execute(message, args) {
const { guild } = message;
if (!bot.channels.cache.get(args[0]))
return message.channel.send(
"Send a valid channel ID. (You can use the `.id` command. Or you could use the Discord developer tools)"
);
const channelId = args[0];
args.shift();
welcomeMessage = args.join(" ");
await mongoDB.setWelcome(guild.id, channelId, welcomeMessage);
message.channel.send(`Channel ID: ${guild.id}, message: ${welcomeMessage}`);
},
};
The problem is your bot is not the one you've logged with so its cache will always be empty. Try to get the client from your message:
const mongoDB = require('../../utility/mongodbFramework');
module.exports = {
name: 'welcome',
aliases: ['setwelcome', 'welcome'],
description: 'Server config',
args: true,
maxArgs: 2,
minArgs: 2,
cooldown: 1,
permissions: 'ADMINISTRATOR',
usage: '<channelId> <message>',
async execute(message, args) {
const { client, guild } = message;
const channelId = args[0];
if (!client.channels.cache.get(channelId))
return message.channel.send(
'Send a valid channel ID. (You can use the `.id` command. Or you could use the Discord developer tools)',
);
args.shift();
const welcomeMessage = args.join(' ');
await mongoDB.setWelcome(guild.id, channelId, welcomeMessage);
message.channel.send(`Channel ID: ${guild.id}, message: ${welcomeMessage}`);
},
};
PS: you could also try to fetch the channel by its ID instead of relying on the cache:
const channelId = args[0];
const channel = await client.channels.fetch(channelId);
if (!channel)
return message.channel.send( /* ... */)