Cannot read property 'find' of undefined Discord.js - bots

I am trying to make a discord.js bot delete a censored message from one channel and log it in an admin channel, this is my code:
msg.channel.send(exampleEmbed1);
msg.guilds.find("721079782833520651").send("Test")
It says this error:
TypeError: Cannot read property 'find' of undefined
at Client.<anonymous> (/Users/DShirriff/rebelbot/rebel.js:35:16)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (/Users/DShirriff/rebelbot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/Users/DShirriff/rebelbot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32) etc.
Pls someone help :) im pretty new to discord.js and I can't find the answer in other people's questions

msg.guilds does not exist.
Did you mean msg.guild? If you want to get a channel from that guild you will need to use msg.guild.channels
Depending on what version you are using:
v11:
const channel = msg.guild.channels.get("channel_id");
v12:
const channel = msg.guild.channels.cache.get("channel_id");

Use that (v12)
let channelID = "channeid";
client.channels.cache.get(channelID).send("Your Text")
// replace channelid to your channel id
Easy, No?

Related

Discord.js V13 sending a message to a specific channel of a specific guild

I'm failing to achieve something very simple. I can't send a message to a specific channel of a specific guild. I've browsed through the documentation and similar threads on stack overflow.
const guild = client.guilds.cache.find(g => g.id === process.env.guildId)
const channel = guild.channels.cache.find(ch => ch.name === "log-channel")
channel.send('👍')
Does not work. Instead, I'm getting this error:
const channel = guild.channels.cache.find(ch => ch.name === "log-channel")
^
TypeError: Cannot read properties of undefined (reading 'channels')
What am I missing?
I actually figured out what the problem was. I didn't set the GUILDS intent (thanks to Jakye in the comments).

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

Error Message : InvalidKey: A key should contain at least a kind

I am getting following error while trying to update the entity in google cloud datastore:
InvalidKey: A key should contain at least a kind.
at keyToKeyProto (/Volumes/Drive B/dev/zapi/node_modules/#google-cloud/datastore/src/entity.js:696:11)
at Array.map (<anonymous>)
at DatastoreRequest.createReadStream (/Volumes/Drive B/dev/zapi/node_modules/#google-cloud/datastore/src/request.js:226:23)
at DatastoreRequest.get (/Volumes/Drive B/dev/zapi/node_modules/#google-cloud/datastore/src/request.js:461:8)
at /Volumes/Drive B/dev/zapi/node_modules/#google-cloud/common/build/src/util.js:681:32
at new Promise (<anonymous>)
at Datastore.wrapper [as get] (/Volumes/Drive B/dev/zapi/node_modules/#google-cloud/common/build/src/util.js:662:20)
at fetchEntity (/Volumes/Drive B/dev/zapi/node_modules/gstore-node/lib/model.js:204:36)
at Function.get (/Volumes/Drive B/dev/zapi/node_modules/gstore-node/lib/model.js:174:16)
at Promise (/Volumes/Drive B/dev/zapi/node_modules/gstore-node/lib/utils.js:39:35)
at new Promise (<anonymous>)
at Function.wrapper (/Volumes/Drive B/dev/zapi/node_modules/gstore-node/lib/utils.js:27:16)
at resolve (/Volumes/Drive B/dev/zapi/graphql/mutations/user/linkConsult.js:101:44)
I don't know why is this coming for.
Thanks in advance.
When you trying to access key and key is not available when no data available, it gives the error
"Error Message : InvalidKey: A key should contain at least a kind"
To avoid this error first make sure that [datastrore.KEY] is available.
Thanks
I want to add to this answer with a little more detail. Here are some other helpful points to investigate if you run into this error when using the datastore.save method. The entity needs the correct key property like the example below.
// remember to use the key method on the google data store instance
const entity = {
key: dataStore.key('Name of your Kind') // this is Kind property you see on the GCP dashboard,
data: {
example: 'this is an example',
...
}
};
// then save the entity
const dbResult = await dataStore.save(entity)

How can I resolve these errors in my code?

bot.on('guildMemberAdd', (guildMember, channel, message) => {
guildMember.addRole(guildMember.guild.roles.find(role => role.name === "ew"));
embed = new discord.RichEmbed()
.setTitle("User Join Notification")
.setDescription("**guildMember.username** has joined this server.")
.setColor("#21a1e1")
message.channel.id('430681100956991511').sendEmbed(embed);
});
When I execute this code, when a user joins, it reports in the console TypeError: Cannot read property 'channel' of undefined. How could I resolve this?
Thanks.
The guildMemberAdd event only provides you with the GuildMember object so your channel and message variables are undefined.
Instead you want to get the channel to send the embed to through the GuildMember object:
guildMember.guild.channels.get("430681100956991511")
I believe

roleDelete event having problems after leaving guild

This error has appeared after I added a .catch statement to Promises after sending messages to guilds.
Quick Explanation: My bot is trying to retrieve data from a guild it no longer belongs to.
Here's my code:
Filename: roleDelete.js
'use strict';
const Discord = require('discord.js');
const Error = require('debug')('Event:roleDelete:Error');
/**
* #param {object} client - The client instance
* #param {object} role - The deleted role object
*/
module.exports.run = (client, role) => {
let embed = new Discord.RichEmbed();
const guildID = role.guild.id;
const guildName = role.guild.name;
const guildIcon = role.guild.iconURL;
const modLog = client.guilds.get(guildID).channels.find('name', client.config.modLog);
const tempIcon = 'https://images-ext-2.discordapp.net/external/ouGhEoGzz1ZyBG9mMFrYClvdv9V0FZ0jGSEHa_kLLYk/https/discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png';
if (!modLog) return;
embed = new Discord.RichEmbed()
.setAuthor(guildName, guildIcon ? guildIcon : tempIcon)
.addField('Role Name', role.name, true)
.addField('Role Color', role.hexColor, true)
.addField('Role Hoisted', role.hoist, true)
.setFooter('Role Deleted At')
.setTimestamp()
.setColor(client.config.colors.red);
return modLog.send(embed).catch(err => Error(err));
};
Additional Info:
bufferutil: 3.0.3
chalk: 2.3.0
clear: 0.0.1
debug: 3.1.0
discord.js: 11.3.0
dotenv: 4.0.0
firebase-admin: 5.8.1
moment: 2.20.1
opusscript: 0.0.6
Expected Result:
Discord.JS ignores and no error is thrown.
Current Result:
2018-01-23T12:34:05.029Z Event:guildDelete Left Guild: 395928739201941506, removed into database.
2018-01-23T12:34:05.212Z Event:roleDelete:Error DiscordAPIError: Missing Access
at item.request.gen.end (/app/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:71:65)
at then (/app/node_modules/snekfetch/src/index.js:218:21)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
2018-01-23T12:34:05.255Z Event:guildMemberRemove:Error DiscordAPIError: Missing Access
at item.request.gen.end (/app/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:71:65)
at then (/app/node_modules/snekfetch/src/index.js:218:21)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7
Is there any way to ignore the fact that it has left and completely ignore it?
This sounds like an error with multiple events running asynchronously. If that is the case, a simple check if the client is still in the guild should fix the issue. An example of one of the few ways to do this can be found below.
const guild = bot.guilds.get(myguildid); // Should return null if the guild is not found
if (!guild) // The guild does not exist.
The property used can be found here in the documentation. Of course, there are other ways to do this, but this also sounds like a bug with the library and caching. If this causes any further bugs and the above does not fix the issue, try reporting the issue in more detail on the Discord (to find and identify the bug). From there, they'll direct you to report it to their GitHub if it does turn out to be a bug. Happy coding!

Resources