UnhandledPromiseRejectionWarning when trying to send message - node.js

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.
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?

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')
How to get a Channel ID
ChannelManager Docs

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.

Related

How edit messages in Discord.js V12 using message ID

There is the way to edit a message on DiscordJS
To do this, we just need to pass it to the function, the client variable.
exports.myNewFunction = async function myNewTestFunction(client)
First, in order to edit a message using the Discord.JS API, we will need to find the server's GuildID.
const guild = client.guilds.cache.get(`Your Guild ID`);
Now, we're going to need to find the channel the message is on. For this, we will use the channel ID
const channel = guild.channels.cache.find(c => c.id === `Your message Channel` && c.type === 'text');
Finally, let's go to the editing part of the message. For this, we will only need to provide the ID of the message that you want to be edited.
channel.messages.fetch(`Your Message ID`).then(message => {
message.edit("New message Text");
}).catch(err => {
console.error(err);
});

how to move a member to a different channel

So I have been looking around how to make a command to move someone to a different channel but they use a command called .setVoiceChannel but I can't find it? I know think might be kind of a noob question.
here is what I currently have
const user = message.author.id;
const member = message.guild.member(user);
// what a I trying to do
member.setVoiceChannel(/* them parameters */); // not defined and I can't find it in documents
// The member is the message author.
const member = message.member;
// Getting the channel.
const channel = client.channels.cache.get("Channel");
// Checking if the channel exists and if the channel is a voice channel.
if (!channel || channel.type !== "voice") return console.log("Invalid channel");
// Checking if the member is in a voice channel.
if (!member.voice.channel) return console.log("The member is not in a voice channel.");
// Moving the member.
member.voice.setChannel(channel).catch(e => console.error(`Couldn't move the user. | ${e}`));
Note: setVoiceChannel() is a valid method of GuildMember in Discord JS v11.
It has been changed to GuildMember.voice.setChannel(ChannelResolvable) in Discord JS v12.

Sending message to specific channel, not working

Having trouble sending a bot message on a specific channel. I very simply want to have the bot send a message to #general when it activates, to let everyone know it's working again.
In the bot.on function, I've tried the classic client.channels.get().send(), but the error messages I'm getting show that it thinks client is undefined. (It says "cannot read property 'channels' of undefined")
bot.on('ready', client => {
console.log("MACsim online")
client.channels.get('#general').send("#here");
})
The bot crashes immediately, saying: Cannot read property 'channels' of undefined
The ready event doesn't pass any client parameter.
To get a channel by name use collection.find():
client.channels.find(channel => channel.name == "channel name here");
To get a channel by ID you can simply do collection.get("ID") because the channels are mapped by their IDs.
client.channels.get("channel_id");
Here is an example I made for you:
const Discord = require("discord.js");
const Client = new Discord.Client();
Client.on("ready", () => {
let Channel = Client.channels.find(channel => channel.name == "my_channel");
Channel.send("The bot is ready!");
});
Client.login("TOKEN");
You need to get the guild / server by ID, and then the channel by ID, so your code will be something like :
const discordjs = require("discord.js");
const client = new discordjs.Client();
bot.on('ready', client => {
console.log("MACsim online")
client.guilds.get("1836402401348").channels.get('199993777289').send("#here");
})
Edit : added client call
The ready event does not pass a parameter. To gain the bot's client, simply use the variable that you assigned when you created the client.
From your code, it looks like the bot variable, where you did const bot = new Discord.Client();.
From there, using the bot (which is the bot's client), you can access the channels property!

I keep getting an error in discord.js "discord is not defined" OR I get no response from the bot. Not even an error/

I am coding a discord bot using discord.js.
FOR SOME REASON it says Discord not defined error or the bot has no response. Please could you help me? I have never had this error before. Here's the code.
I have include this command in the same main.js file:
if(cmd === `${prefix}help`){
reporthelp = "Report a user. Requires a channel named `reports`to work!";
kickhelp = "Kick a user from the server. Requires a channel named `incidents` to work; you must have the manage messages permission.";
banhelp = "Ban a user from the server. Requires a channel named `incidents` to qork; toy need the BAN MEMBERS permission to use this command!";
warnhelp = "**COMMAND COMING SOON!**";
requiredperms = "**Embed Links, channel named `incidents`; channel named `reports`; channel named `suggestions`; Kick Members, Ban Members, Manage Roles, Manage Members.**"
helpEmbed = new Discord.RichEmbed()
.setDescription(" 💬 **__Help Is Here!__** 💬")
.setColor("#936285")
.addField("**/report #user <reason>**", reporthelp)
.addField("**(COMING SOON)** /warn #user <reason>", warnhelp)
.addField("**/kick #user <reason>**", kickhelp)
.addField("**/ban #user <reason>**", banhelp)
.addField("**/mytag**", "Shows you **your** discoord username#discrim and your user ID. Requires Embed Links permission.")
.addField("**/invite**", "Get a linkto incite meto our server, and an invite link to my suppoer server")
.addField("**/owner**", "see who currently owns the bot")
.addField("**/git**", "**SOURCE CODE AVAILIBLE SOON**")
.addField("**/token**", "View the bot's super secret bot token!")
.addField("**/serverinfo**", "displays some basic server information!")
.addField("**/botinfo**", "displays basic bot information!")
.addField("**/ping**", "Get the bot to respond with `pong` ")
.addField("**/hosting**", "Bot finds a good website for bot/web hosting")
.addField("**/quotes**", "bot responds with some lovely quotes!")
.addField("**__Required Permissions__**", requiredperms)
// .addField("**COMING SOON!**/suggest <suggestion>", "suggest something. Requires channel named `suggestions`")
.setTimestamp()
.setFooter("Use /invite to invite me to your server!")
return message.channel.send({embed: helpEmbed});
}
This is how I've defined everything:
const botconfig = require("./botconfig.json");
const tokenfile = require("./token.json");
const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
bot.on("ready", async () => {
console.log(`${bot.user.username} is active in ${bot.guilds.size} servers!`);
bot.user.setActivity("rewriteing main.js...", {type: "WATCHING"});
//bot.user.setGame("Lookin' out for ya!");
});
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
const prefix = botconfig.prefix;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
const bicon = bot.user.displayAvatarURL;
I either get no response/error, or I get the error discord is not defined.
I'm also very new here, sorry If I didn't ask a question clearly...
The code is correct, but I had redfined discord in a different part of the file....
my advice would be to alays read the code over again!

Discord.js -- make presenceUpdate send a message

im trying to get my super simple bot to send a message stating the user status. as if someone is offline, online,..etc it automatically sends a message to the server saying that happened.
im just doing a work around so it can get updated (i know i need to !status everytime)
anyone has an idea to make it send the same message instantly after presenceUpdate fires?
let userStatus = [];
bot.on("presenceUpdate", (oldMember, newMember) => {
let username = newMember.user.username;
let status = newMember.user.presence.status;
userStatus.push(username, status);
console.log(`${newMember.user.username} is now ${newMember.user.presence.status}`);
})
bot.on('message', (message) => {
// if (!message.content.startsWith(prefix)) return;
if (console.log())
let [username, status] = userStatus;
if (message.content.startsWith(prefix + "status")) {
let botembed = new Discord.RichEmbed()
.setDescription("Status Update")
.setColor("#FFF")
.addField('.............................................', `${username} is now ${status}`);
message.channel.send(botembed);
userStatus = [];
}
});
The issue I think you're running into is that you don't have a direct reference to a channel anymore, which is why you can't "easily" call <TextChannel>.send(...). You'll have to decide which channel you want to send a message to, in your presenceUpdate event listener. Once you decide, you can use this code to get a reference to that channel using the channel's name:
client.on('presenceUpdate', (oldMember, newMember) => {
// get a reference to all channels in the user's guild
let guildChannels = newMember.guild.channels;
// find the channel you want, based off the channel name
// -> replace '<YOUR CHANNEL NAME>' with the name of your channel
guildChannels.find('name', '<YOUR CHANNEL NAME>')
.send('test message!')
.then(msg => {
// do something else if you want
})
.catch(console.error)
});
Note: you don't have to use the channel's name property to identify a unique channel, you can use the channel's id by doing
guildChannels.get('<YOUR CHANNEL ID')
.send('...
Hope this helps!

Resources