Cannot read properties of undefined (reading 'channels') - javascript

I'm trying to make an event that when someone added my bot it will send a message embed on a channel that my bot can send the message embed.
discord.js: v13.6.0
Node: v17.7.2
events/guildCreate.js
const client = require("../index");
const discord = require("discord.js")
client.on("guildCreate", async (client, guild) => {
let channel = guild.channels.cache.find(
channel =>
channel.type === "text" &&
channel.permissionsFor(guild.me).has("SEND_MESSAGES")
);
channel.send( new discord.MessageEmbed()
.setDescription("**Thank you for adding me!**")
.setColor("#fcba03"))
})
edit:
I kinda of fix my problem with the reading channels:
const client = require("../index");
const { MessageEmbed } = require("discord.js")
client.on("guildCreate", async (guild, message) => {
let channel = guild.channels.cache.find(
channel =>
channel.type === "text" &&
channel.permissionsFor(guild.me).has("SEND_MESSAGES")
);
const embed = new MessageEmbed()
embed.setDescription("Thank you for adding me!")
embed.setColor("#2f3136")
message.guild.channels.cache.get(channel).send(embed)
})
but then again got new error:
TypeError: Cannot read properties of undefined (reading 'guild')

I think your “channel” is an array instead of a channel object, because you're filtering all text channels. Make sure to select the first channel of the array/collection.
Try to show what shows up when you log the “channel”

Related

Does fetching embeds through messages from msg.reference.messageID not work?

I am coding a discord bot, and I am trying to get the content of embeds through the command user replying to the message and using a prefix. When I try running the command, it says that fetchedMsg.embeds[0] isn't a thing. Is there anything wrong with my code?
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
The error is on the line console.log(fetchedMsg.embeds[0]), and looking at the log from the code before it includes embeds: [ [MessageEmbed] ],.
The error reads TypeError: Cannot read properties of undefined (reading '0'), and when I remove the [0], it's undefined. This whole thing is in a module.exports.run, if that helps.
module.exports.run = async (client, msg, args) => {
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');
if (args.length === 5) {
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(await msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
//do things with fetchedMsg
You can get the MessageEmbed() same as normal Message using:
const messages = args[0]
if(!messages) return message.reply("Provide an ID for message.")
if(isNaN(messages)) return message.reply("Message ID should be
number, not a letter")
message.channel.messages.fetch(`${messages}`)
.then(msg => {
console.log(msg.content) || console.log(msg.embeds)
})
You can find more here about fetching a message

How do I get the bot to write user's name

This is the code, I want it to write user's name and then auction word (p.s I am new to this)
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageEmbed } = require('discord.js');
const channel = client.channels.cache.get('889459156782833714');
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
var message = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle() // want user's name + "Auction"
.addField('Golden Poliwag', 'Very Pog', true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction')
if (msg.content === "d.test") {
msg.reply(message)
}
})
You can access the user's username by using msg.author.tag. So. the way to use the user's tag in an embed would be:
const { MessageEmbed, Client } = require("discord.js");
const client = new Client();
const channel = client.channels.cache.get("889459156782833714");
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
var message = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle(`${msg.author.tag} Auction`)
.addField("Golden Poliwag", "Very Pog", true)
.setImage("https://graphics.tppcrpg.net/xy/golden/060M.gif")
.setFooter("Poliwag Auction");
if (msg.content === "d.test") {
msg.reply(message);
}
});
I suggest you to read the discord.js documentation, almost all you need to interact with Discord API is from there.
You can't control the bot if you don't login to it. Get the bot's token from Developer Portal and login to your bot by adding client.login('<Your token goes here>') in your project.
You can't get the channel if it's not cached in the client. You need to fetch it by using fetch() method from client's channels manager:
const channel = await client.channels.fetch('Channel ID goes here');
P/s: await is only available in async function
message event is deprecated if you are using discord.js v13. Please use messageCreate event instead.
You are able to access user who sent the message through msg object: msg.author. If you want their tag, you can get the tag property from user: msg.author.tag, or username: msg.author.username or even user ID: msg.author.id. For more information about discord message class read here.
The reply options for message is not a message. You are trying to reply the message of the author with another message which is wrong. Please replace the reply options with an object that includes embeds:
msg.reply({
embeds: [
// Your array of embeds goes here
]
});
From all of that, we now have the final code:
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
client.on("ready", () => {console.log(`Logged in as ${client.user.tag}!`)});
client.on("messageCreate", async (msg) => {
const channel = await client.channels.fetch('889459156782833714');
const embed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle(`${msg.author.tag} Auction`)
.addField('Golden Poliwag','Very Pog',true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction');
if (msg.content === "d.test") {
msg.reply({
embeds: [ embed ],
});
}
});
client.login('Your bot token goes here');
Now your bot can reply to command user with an rich embed.

TypeError: Cannot read property 'roles' of undefined in discord.js

I am trying to get the bot to add roles in one discord and also add a role in another discord. but I keep getting the "roles" is not defined error. I have little to no coding knowledge and most of my code is a combination of things I find on google or friends teach me, so please excuse me if it is a dumb problem with a simple solution.
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.GUILD_ROLES] });
module.exports = {
name: 'accept',
description: 'Adds A Player To The Whitelist',
permissions: `ADMINISTRATOR`,
execute(message, args, add, roles, addRole, guild) {
message.delete()
let rMember = guild.roles.cache
message.mentions.members.first() || // `.first()` is a function.
message.guild.members.cache.find((m) => m.user.tag === args[0]) ||
message.guild.members;
let role1 =
message.guild.roles.cache.find((r) => r.id == roleID)
let role2 =
message.guild.roles.cache.find((r) => r.id == roleID)
let server = client.guilds.cache.get('guild ID')
let memberRole = server.guild.roles.get("role ID");
rMember.roles.add(role1).catch((e) => console.log(e));
rMember.roles.add(role2).catch((e) => console.log(e));
rMember.roles.add(memberRole).catch((e) => console.log(e));
rMember.send(`message content`);
message.channel.send('message content')
}};
The error occurs in this line:
let memberRole = server.guild.roles.get("872432775330955264");
let server = client.guilds.cache.get('guild ID')
let memberRole = server.guild.roles.get("role ID");
These particular lines justify your error, in the first case you are assigning the property of a guild object to server by getting the guild from the cache, now you see a guild object does not have a property further named guild to it so your error actually rests in the next line, where you are trying to get from server.guild it's same as saying guild.guild which makes no actual sense.
Only correction you would want to make with your code would be something of this sort:
let server = client.guilds.cache.get('guild ID')
let memberRole = server.roles.cache.get("role ID");

I have the TypeError: Cannot read property 'toString' of undefined

I'm making a discord welcomer bot and there's a problem where when someone joins the server it sends this error:
TypeError: Cannot read property 'toString' of undefined
Here is the source code:
module.exports = (client) => {
const channelid = "865471665168580628";
client.on("guildMemberAdd", (member) => {
const serverid = member.guild.id
const guild = client.guilds.cache.get(serverid);
console.log("member");
const ruleschannel = guild.channels.cache.find(channel => channel.name === "rules");
const message = `welcome <#${member.id}> to music and chill! please read the ${member.guild.channels.cache.get(ruleschannel).toString()} before you start chatting.`;
const channel = member.guild.channels.cache.get(channelid);
channel.send(message);
})
}
Can someone please help me?
It means member.guild.channels.cache.get(ruleschannel) is undefined. As ruleschannel is a channel object, and the Collection#get() method needs a snowflake, you need to use its id property.
So member.guild.channels.cache.get(ruleschannel.id) should work.
A better way would be to check if the ruleschannel exists though. Also, you can just simply add rulesChannel inside the backticks and it gets converted to a channel link. Check out the code below:
client.on('guildMemberAdd', (member) => {
// not sure why not just: const { guild } = member
const guild = client.guilds.cache.get(member.guild.id);
const rulesChannel = guild.channels.cache.find((channel) => channel.name === 'rules');
if (!rulesChannel)
return console.log(`Can't find a channel named "rules"`);
const channel = guild.channels.cache.get(channelid);
const message = `Welcome <#${member.id}> to music and chill! Please, read the ${rulesChannel}.`;
channel.send(message);
});

"send" is undefined? | Discord.js

const Discord = require ("Discord.js")
exports.exec = async (client, message, args) => {
const bug = args.slice().join(" ");
if (!args[0]) return message.channel.send(`${message.author}\` Please right, in as much detail about the bug\``);
const channel = client.channels.get('498750658569306123')
const embed = new Discord.RichEmbed()
.setAuthor(message.author.tag, message.author.avatarURL)
.setColor(0)
.setDescription(bug)
.setTimestamp()
.setFooter(`Suggestion by ${message.author.tag} from ${message.guild.name}`)
channel.send(embed)
Error thrown back is:
TypeError: Cannot read property 'send' of undefined
at Object.exports.exec (C:\Users\Cake\Peepo\modules\help\bugreport.js:14:11)
Everything seems to work fine.. I'm unsure how "send" is undefined? Someone care to explain?
Try doing this to find your report channel.
let channel = message.guild.channels.find(c => c.name === "report-channel-name-here");
channel.send(embed);
if that fails, make sure that your bot can access the channel.

Categories

Resources