mr noob
mr noob

Reputation: 365

UnhandledPromiseRejectionWarning when trying to send message

I am trying to send a message through discord.js and I am getting the following error:
(node:10328) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined

Here is my code:

// Init
const Discord = require("discord.js");
const bot = new Discord.Client();
const channel = bot.users.cache.get('4257');

// Vars

// Code
bot.on("ready", () => {
    console.log("The Bot is ready!");

    channel.send("Test");
});


// Login
bot.login(" "); // I will hide this.

What is wrong? Is it the id on the channel variable? I just put in the id of my bot since I didn't know what to put in it. enter image description here


At first I gave it all the permissions under "Text Permissions", but I also tried giving him admin privs. It still didn't work. What am I doing wrong?

Upvotes: 1

Views: 112

Answers (2)

Lioness100
Lioness100

Reputation: 8412

The problem is this line:

const channel = bot.users.cache.get('4257');

Here's what's wrong with it:

const channel = bot.users.cache // this returns a collection of users, you want channels.
.get('4257'); // this is a user discriminator, you want a channel ID

Here's how to fix it:

const id = <ID of channel you want to send the message to>
const channel = bot.channels.cache.get(id)

// ...

channel.send('Test')

Here's an example:

const channel = bot.channels.cache.get('699220239698886679')
channel.send('This is the #general channel in my personal Discord')

Upvotes: 3

Rahul Beniwal
Rahul Beniwal

Reputation: 677

const channel is empty here. You need to make sure value should be assigned in it.

channel.send("Test");

If its not mendatory that value will come then use try-catch.

try {
 channel.send("Test");
} catch(e) {
 console.log(e)
}

Please support with vote or answered if it helps, thanks.

Upvotes: -1

Related Questions