node.jsdiscord.js

DiscordJS - Send Message


Im Trying To Send A Message Through DiscordJS

Can Someone Help Me

I Tried This Code

const channel = client.channels.cache.get('example discord guild');
channel.send('content');

But It Doesent Work

index.js

// Credetials
const { token } = require('./json/token.json');
const { guild } = require('./json/guild.json');
const { client } = require('./json/client.json')

// Init
const { Client, Intents } = require('discord.js');
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_>

bot.login(guild);
console.log("Logged In As DeltaBOT");
const channel = client.channels.cache.get(guild);
channel.send('content');

Error

const channel = client.channels.cache.get(guild);
                                ^

TypeError: Cannot read properties of undefined (reading 'cache')
    at Object.<anonymous> (/storage/emulated/0/Download/node/index.js:15:33)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47

Solution

  • You should wait for your client to login before attempting to send a message / fetching a channel. You can do this by using the ready event. For example:

    bot.on('ready', async () => {
        console.log('Logged in as: ' + bot.user.tag);
        const channel = await bot.channels.fetch(guild);
        await channel.send('content');
    })
    

    Another thing I noticed is that you use client instead of bot. client is a json object but you defined your discord bot object as the bot variable. So use the bot variable and not the client one.

    Make sure that the guild is a valid guild ID. I don't know what is in your client json file but you don't appear to be using it.