discord.js "member is undefined" - javascript

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 */
}

Related

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

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;
}
})
})

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))
});

Detect Reaction on discord.js

I am making a discord bot, and I have a problem with a waifu command.
With this command the bot sends an embed, and I want to detect when someone reacts to this embed. I tried this code but nothing happens.
const Discord = require("discord.js");
const axios = require("axios")
const Client = new Discord.Client;
module.exports = {
name : 'waifu',
description : "waifu command",
execute(message, args) {
Client.on('messageReactionAdd', (reaction, user) => {
message.channel.send("Reacted")
})
axios.get("https://api.waifu.pics/sfw/waifu")
.then((res) => {
let wembed = new Discord.MessageEmbed()
.setTitle(`Voici votre waifu ${message.author.username}`)
.setImage(res.data.url)
message.channel.send(wembed)
.then(function (message) {
message.react("❤")
Client.on('messageReactionAdd', (reaction, user) => {
console.log("reacted")
})
})
})
.catch((err) => {
console.error("ERR: ", err)
})
}
}
You can't add a messageReactionAdd listener inside your message listener. You can however set up a reaction collector using createReactionCollector for example, like in my example below:
const { MessageEmbed } = require('discord.js');
const axios = require('axios')
module.exports = {
name: 'waifu',
description: 'waifu command',
execute(message, args) {
axios
.get('https://api.waifu.pics/sfw/waifu')
.then((res) => {
let wembed = new MessageEmbed()
.setTitle(`Voici votre waifu ${message.author.username}`)
.setImage(res.data.url);
// make sure you use a different var name here
// like msg instead of message
message.channel.send(wembed).then((msg) => {
msg.react('❤');
// set up a filter to only collect reactions with the ❤ emoji
let filter = (reaction, user) => reaction.emoji.name === '❤';
let collector = msg.createReactionCollector(filter);
collector.on('collect', (reaction, user) => {
// in case you want to do something when someone reacts with ❤
console.log('reaction added');
});
collector.on('remove', (reaction, user) => {
// in case you want to do something when someone removes their reaction
console.log('reaction removed');
});
});
})
.catch((err) => {
console.error('ERR: ', err);
});
},
};
A couple things here.
First, you defined message twice; once as the message initiating the command that originated from your command handler, and once as the message the bot sent. You need to rename one of these or else various unexpected issues may arise.
Second, you should never define your client twice. Instead, you should reuse the client. To do this, you can either export it to your command handler the same way you export message and args, or you can access it via <message>.client and use it the same way you did here.

Discord.js : A part of the code does not work, but there is no error

When I start the bot there comes the Ready message but wehen one of somebody send for example a link into a channel nothing happens. Ther comes no error. I had to reduce the code because of the stackoverflow limit. There were three other parts but they worked. Only these two parts doesnt work.
const Discord = require('discord.js');
const client = new Discord.Client();
const TOKEN = '';
const PREFIX = '!';
//ready
client.once('ready', () => {
console.log('Ready!');
});
//welcome
client.on('guildMemberAdd', member => {
console.log('User joind');
});
//commands
client.on('message', message => {
if (!message.content.startsWith(PREFIX)) return;
if (message.author.bot) return;
if (!message.guild) return;
}
//delete links
else if (message.content.includes('https://')) {
console.log('Link!!!');
}
});
client.login(TOKEN);
Most likely the message does not have the required prefix, thus the the function just returns.

Categories

Resources