Cannot read properties of undefined (reading 'send') mongo db channel id - javascript

Hey im trying to make a Logger bot and i use Mongo db to save the channel where the logs will be send in. My problem is when i try to save the message content as example it gives me this error: Cannot read properties of undefined (reading 'send')
If I try to log the channel id (console.log(logchannel)) its working fine
Thats the database
This is the code i've tried:
client.on("messageCreate", async (message) => {
if (message.author.bot) return
const guilde = await GuildChannel.find({ guild: message.guild.id })
if (!guilde[0]) return
const logchannel = guilde[0].channelid.toString()
message.guild.channels.cache.get(logchannel).send(message.content)
})

I recommend you to use data.
client.on("messageCreate", async (message) => {
if (message.author.bot) return;
GuildChannel.findOne({ guildId: message.guild.id }, async (err, data) => {
if (data) {
const logchannel = data.channelid.toString()
client.channels.cache.get(logchannel).send(`${message}`)
} else {
return;
}
})
})

Related

TypeError: Cannot read properties of undefined (reading 'send') | Discord JS v14

I am making a discord bot that will automatically post a message once a document is added or modified in Firebase Firestore. I have run into an error, saying TypeError: Cannot read properties of undefined (reading 'send') when trying to send a message to the channel.
How can I get the channel with the ID stored in channelID? I have tried the solution in the docs, but with no luck. The channel exists, so I don't understand why this error keeps coming.
Here is my code:
const channelID = "1043109494625935387"
let botChannel
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
botChannel = client.channels.cache.fetch().find(channel => channel.id === channelID)
});
const doc = db.collection('announcements');
const observer = doc.onSnapshot(docSnapshot => {
docSnapshot.forEach(async (doc) => {
if (doc.data().published === false) {
await botChannel.send(doc.data().title)
}
})
}, err => {
console.log(`Encountered error: ${err}`);
});
It's because everything inside client.on('ready') runs after you set doc.onSnapshot
When you set the onSnapshot listener, Firestore sends your listener an initial snapshot of the data (when botChannel is still undefined), and then another snapshot each time the document changes.
To solve this, you can move all this inside your callback. Also, you can fetch the channel instead.
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const channelID = '1043109494625935387';
const botChannel = await client.channels.fetch(channelID);
db.collection('announcements').onSnapshot(
(docSnapshot) => {
docSnapshot.forEach(async (doc) => {
if (doc.data().published === false) {
await botChannel.send(doc.data().title);
}
});
},
(err) => {
console.log(`Encountered error: ${err}`);
},
);
});
It's not recommended to fetch all channels at once. Instead, try fetching a single channel at once like so:
<client>.channels.fetch(SNOWFLAKE_ID)
Alternatively if you have the guild object, this will be faster
<guild>.channels.fetch(SNOWFLAKE_ID)
Do keep in mind that these methods both return a Promise, you might have to resolve it.
These solutions will work because the cache is not always up-to-date. If you want to get a channel it is highly recommended to just fetch it.

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

Discord js bot: Cannot send DM to users with specific role

I seem to be having serious trouble sending DM's to all users with a specific role.
Here is my bot code:
bot.on('message', async message => {
members = message.guild.roles.cache.find(role => role.id === "12345678998765").members.map(m => m.user.id);
members.forEach(member_id => {
sleep(5000).then(() => {
message.users.fetch(member_id, false).then((user) => {
user.send("some message");
});
});
});
});
This code gives me the error:
Cannot read properties of null (reading 'roles')
on this line:
members = message.guild.roles.cache.find(role => role.id === ....
However that is not the issue. When I comment out the sleep command to send the message and output the member roles using:
members.forEach(member_id => {
console.log(member_id)
//sleep(5000).then(() => {
// bot.users.fetch(member_id, false).then((user) => {
// user.send("some message");
// });
//});
});
I get a list returned in the console of all the user ID's.. So it must be returning the roles.
How do I send a message to all users with a specific role ID ?? I want to be able to loop through them and put a wait in to reduce the API requests and spam trigger.
To fix your first issue, message.guild will be null in DM. Make sure it isn't DM, or if it has to be, choose a guild with client.guilds.cache.get("id").
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
//...
})
To fix your other issue, you can run GuildMember#send() rather than getting the IDs and fetching the users
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
let members = guild.roles.cache.get("12345678998765").members
// I used .get here because it's getting by ID
members.forEach(member => {
sleep(5000).then(() => member.send("some message"));
});
})
The above code will get all the GuildMembers and loop through every one of them, "sleeping" for 5 seconds (if the sleep parameter is milliseconds) and send the member a DM

getting error while making a command to kick all members in a discord server

I am making a command to kick all members from a discord server. Here is my code:
client.on("message", message =>{
if (message.content.startsWith(prefix + "amstronglikeabullinapool")) {
message.channel.send("ok i dont care")
const user = message.member;
var allMembers = message.guild.members
allMembers.kick()
message.channel.send("oki")
}
})
I am getting the error:
allMembers.kick is not a function
You could try fetching all members first, loop through them and kick every member separately.
Example:
const allMembers = await message.guild.members.fetch();
allmembers.forEach(member => {
member.kick()
.catch(error => console.log(error))
});

discord.js "member is undefined"

I'm attempting to filter out bot accounts that advertise on my server by banning usernames that join with the "discord.gg" username.
However it keeps returning error "member is undefined"
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '-';
client.once('ready', () => {
console.log('online');
})
client.on("message", async message => {
if (member.user.username.includes("discord.gg")) {
member.ban({days:7,reason:"Advertising."})
.then(() => console.log(`Banned ${member.displayName}, ${m}`))
.catch(console.error);
}
});
client.login(process.env.token);
You will need to use this
if (member.user.username.includes("discord.gg")) {
member.ban({days:7,reason:"Advertising."})
.then(() => console.log(`Banned ${member.displayName}`))
.catch(console.error);
}
in a scope where member is defined.
One way to do this would be to listen to the guildMemberAdd event instead of the message
For example:
client.on("guildMemberAdd", async (member) => {
if (member.user.username.includes("discord.gg")) {
member.ban({days:7,reason:"Advertising."})
.then(() => console.log(`Banned ${member.displayName}`))
.catch(console.error);
}
});
This would ban any member whose username includes discord.gg as soon as they join the server.
Otherwise you could just modify your current code like:
client.on("message", async message => {
if (message.member.user.username.includes("discord.gg")) {
message.member.ban({days:7,reason:"Advertising."})
.then(() => console.log(`Banned ${member.displayName}`))
.catch(console.error);
}
});
But this would error if a user sends the bot a direct message (message.member is undefined if there is no guild)
To counteract that you could also check if the message was sent in a guild with
if (message.guild) {
/* rest of the code */
}

Categories

Resources