0

I'm trying to add a Global Variable (server) that contains my guild's ID, then I could use, for example: const channel_NAME = server.channels.cache.get('MY CHANNEL ID'); in the top of the code to define all my channels, instead of: member.guild.roles.cache.get('MY ROLE ID'); in every function.

I did it, but this error is returning to me:

const channel_boi_salve = server.channels.cache.get('MY CHANNEL ID');  
TypeError: Cannot read property 'channels' of undefined

My code is:

const Discord = require('discord.js');
const bot = new Discord.Client();
const config = require('./config.json');
const fs = require('fs');
// Guild ID
const server = bot.guilds.cache.get("MY GUILD ID");
// Channels (channel_NAME)
const channel_boi_salve = server.channels.cache.get('MY CHANNEL ID');

I'm new to JavaScript so I would appreciate it if someone could explain in detail how to do it.

1 Answers1

0

You need to put this code in the client.on("ready"...) section of your code, because the client has not yet connected to the discord api, so of course, the servers/channels are undefined.

Levi_OP
  • 945
  • 1
  • 9
  • 22
  • I tried this, but with this method I can use the server variable only in client.on("ready") function. – Pedro Henrique Aug 01 '20 at 20:44
  • that's what global variables are for. https://stackoverflow.com/questions/33659398/javascript-use-variable-outside-a-function-issue – Levi_OP Aug 01 '20 at 20:46
  • I tried this too, I put "const server;" in the top of the code, then "server = bot.guilds..." inside "bot.on("ready"...)" and the "channels consts" after the key "bot.on("ready"){ ... }); const channel_Name = server .channels...". And I have the same error, "Cannot read property 'channels' of undefined". – Pedro Henrique Aug 01 '20 at 20:59