Discord.js const guild = member.guild; - javascript

Hello Programmers I Have Problem With Discord.js I Made Bot Which Is Says Hello #user But It Doesn't Work
Here Is My Code:
Javascript
const Discord = require("discord.js");
const TOKEN = "private";
const PREFIX = "!";
const newUser = new Discord.Collection();
const talkedRecently = new Set();
var bot = new Discord.Client();
var fortunes =
[
"Yes",
"No",
"Maybe",
"IDK"
];
bot.on("ready", () => {
});
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
newUsers.set(member.id, member.user);
if (newUsers.size > 0) {
const defaultChannel = guild.channels.find(c=> c.permissionsFor(guild.me).has("SEND_MESSAGES"));
const userlist = newUsers.map(u => u.toString()).join(" ");
defaultChannel.send("Hello Creativistian!\n" + userlist);
newUsers.clear();
}
});
});
bot.login(TOKEN);
Does Anyone Know How To Fix It

Replace client.on("guildMemberAdd", (member) => { with this:
bot.on('guildMemberAdd', member => {
Note: as #Noobly387 said, you have an extra });, on line 15, please remove that.
Cheers

To fix your problem remove }); on line 15 just after bot.on("ready", () => {.

In the future, please provide more information on your issue.
Although, your error is that you have an extra unnecessary });.

In the future, be sure to state your question in the title so people can help you easier.
On line 15, you have an extra }); below your bot.on("ready", () => { code. This breaks the code because by ending the bot.on line, the rest of the code below will not work since it becomes just regular functions.
Also, as a side note, I would recommend for you to make your arrays single line if they are small (such as your fortunes array) and also don't space out your code too much or you won't be able to see the small problems such as the one that broke your code.

Replace client.on("guildMemberAdd", (member) => { with this :
bot.on('guildMemberAdd', member => {
PS: on line 15 you have an extra unnecessary });

Use that with ALL THE INTENTS ON.
bot.on("guildMemberAdd", member => {
// Code..
});
That work in discord.jsv12, to install type this command
npm install discord.js#v12

Related

Member online counter

My member counter didn't work
Why always my channel have name "online 0" 0 errors, console log working I don't know why
This is my code
const guild = client.guilds.cache.get('693805106906398722');
setInterval(() =>{
const memberCount = guild.memberCount;
const channel = guild.channels.cache.get('824050164376666182');
channel.setName(`Użytkownicy ${memberCount.toLocaleString()}`);
console.log('Member Status: Updating...');
}, 1200000);
setInterval(() =>{
const memberCollection = guild.members.cache;
const online = memberCollection.filter(member => {
member.presence.status === 'online'
}).size;
const channel1 = guild.channels.cache.get('824050194177720391');
channel1.setName(`Online ${online}`);
console.log('Member online Status: Updating...');
}, 1200);
} ```
Do you have Intents Enabled in your bot? If you do not: Then please do it in the Discord Developers Portal for your Application. You need to enable Guild Members intent. Also please do not forget to update your stuff in the Client Constructor (aka const client = new Discord.Client()) so that you can access the guild Member information!
There's a mistake in the code
const online = memberCollection.filter(member => {
member.presence.status === 'online'
}).size;
Please make it
const online = memberCollection.filter(member => {
return member.presence.status === 'online'
}).size;
Since for the filter to work, you need to have a function which returns a boolean and you're not returning anything from your filter function, it is getting a bit messed up.

Can't Convert undefined or null?

const Discord = require('discord.js');
const randomPuppy = require('random-puppy');
const subreddits = [
"memes",
"DeepFriedMemes",
"bonehurtingjuice",
"surrealmemes",
"dankmemes",
"meirl",
"me_irl",
"funny"
]
exports.exec = (client, message, args, user) => {
var randSubreddit = subreddits[Math.round(Math.random() * (subreddits.length - 1))];
randomPuppy(randSubreddit)
.then(url => {
const embed = new Discord.RichEmbed()
.setFooter(`${randSubreddit} ● Subreddit`)
.setDescription(`[Image URL](${url})`)
.setImage(url)
.setColor(0);
return message.channel.send({ embed });
})
};
Hey guys, left discord coding behind about a year ago and I've come back to this error (title) It was working quite fine a year ago, and now nothing. (Haven't changed anything).
I'm a wee bit confused on how or why this is now happening.
Any help is appreciated as I've got no clue.
Thank you in advance :)
Edit - Not running Discord.js v12 so RichEmbed still applies. :)
[unhandledRejection]
TypeError: Cannot convert undefined or null to object
at Function.entries (<anonymous>)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\lowercase-kevs\index.js:5:36)
at normalizeArguments (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\node_modules\got\index.js:222:5)
at got (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\node_modules\got\index.js:302:20)
at randomPuppy (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\index.js:31:12)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\node_modules\random-puppy\index.js:67:16)
at Object.exports.exec (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\commands\image-fetch\meme.js:17:9)
at module.exports (C:\Users\worrit\Downloads\Peepo_Redacted\Peepo_Revive\handlers\commandHandler.js:299:34)
[/unhandledRejection]
const Discord = require('discord.js');
const randomPuppy = require('random-puppy');
const subreddits = [
"memes",
"DeepFriedMemes",
"bonehurtingjuice",
"surrealmemes",
"dankmemes",
"meirl",
"me_irl",
"funny"
]
exports.exec = (client, message, args, user) => {
var randSubreddit = subreddits[Math.round(Math.random() * (subreddits.length - 1))];
randomPuppy(randSubreddit)
.then(url => {
const embed = new Discord.RichEmbed()
.setFooter(`${randSubreddit} ● Subreddit`)
.setDescription(`[Image URL](${url})`)
.setImage(url)
.setColor(0);
message.channel.send({embed});
})
};
Issue is on this line. embed is undefined.
return message.channel.send({ embed });
If this was working in the past and only recently stopped working then I suspect it's either one of two things;
One of the subreddits in your array no longer exists, or the api is outdated.
You can debug this by adding a console.log(embed) before the return statement and then one by one, remove each .function() call until embed no longer === undefined.
Might also be worth npm install every package again.

Cannot get bot to autoban new accounts on Discord

The bot is very simple and will ultimately not require any input from me. What I want the bot to do is to check the age of an account that joins and then ban them if they are a new account made within the past 10 minutes. The part that I'm stuck on is calculating the time I think. The bot isn't giving any errors, it's just not banning the new account that I made. For testing purpose, I put the bot onto a new server I"m making that doesn't have anyone else on it and also changed the amount of time to 14400 seconds so that it's within 10 days and should give me enough time to figure out what's wrong.
Here's my code as it stands:
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", (member) => {
if (Date.now() - member.user.createdAt <= 14400) {
guildMember.ban({ days: 14, reason: 'New account' })
}
});
client.login("Token");
member.client.user.createdAt is the section that I think I'm having a problem with. When I run a debug on Date.now() that works fine but I can't seem to get it to calculate the age of an account that joins.
I'm pretty sure that this is the property I need but I must be calling it incorrectly. Please forgive any ignorance, I'm super new to js.
https://discord.js.org/#/docs/main/master/class/User?scrollTo=createdAt
I would love to know what I'm doing wrong. Thanks!
Finally figured out the problem. The issue is actually multi-part here. The first issue is that I thought it was calculating in seconds, but instead it's actually calculating in milliseconds so the if statement was never true. Once I made that true by increasing the time to 10 days in milliseconds, I got an error on the guildMember since it wasn't defined. I changed that to member and then got an error on the days that it can't be more than 7. Here's the final working code.
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", (member) => {
if (Date.now() - member.user.createdAt <= 864000000) {
member.ban({ days: 7, reason: 'New account' })
}
});
client.login("Token");
You need to put the "async" for it to work
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", async member => {
if (Date.now() - member.user.createdAt <= 1209600000) {
member.ban({ days: 14, reason: 'New account' })
}
});
client.login("Token");

Making a bug report command but kept getting "Type Error: client.fetchUser is not a function" Discord.js

Just like the title says, I want to make a bug report command that will send me the report.
But I kept getting this for some reason:
UnhandledPromiseRejectionWarning: TypeError: client.fetchUser is not a function
Here is my code:
var lockedList = []; //replace the userID stuff here with the ID's of the users you want to blacklist
const pfix = "h."
const arg = message.content.slice(pfix.length).split(/ +/);
const commnd = arg.shift().toLowerCase();
const person = message.author.username;
const userID = message.author.id;
if (commnd === 'bugreport') {
if (userID == lockedList) {
message.channel.send('***You have abused and f##ked this feature before so you\'re in our blacklist***')
} else {
let bug = arg.slice(0).join(' ');
if (!bug) {
message.channel.send('Huh?! What and Where\'s the f##king bug?!')
} else {
client.fetchUser(myID).then((user) => {
user.send(`${person} of ${message.guild.name} (Guild ID: ${message.guild.id}, User ID: ${userID}) reported the bug: ${bug}`);
});
message.reply('**Your bug was reported. If you abuse and f##k this feature, you\'ll be blacklisted and stopped from using this command.**');
};
};
};
Side notes:
This code is inside the client.on('message', async message => {
I have some codes that is just copied from this one, the feedback and suggest command. Just saying this because it might be related to the problem.
Since discord.js v12 the fetchUser() method was removed.
You should instead use client.users.fetch()
client.users.fetch(myID).then((user) => {
user.send(`${person} of ${message.guild.name} (Guild ID: ${message.guild.id}, User ID: ${userID}) reported the bug: ${bug}`);
})

How to tell if a message mentions any user on the server?

I want to, with discord.js, tell if any given message mentions any user on the server.
Message.mentions is what you're looking for: you can either check .users or .members. If there's at least one element in one of these collections, then someone has been mentioned:
client.on('message', message => {
if (message.mentions.members.first()) // there's at least one mentioned user
else // there's no mentioned user
});
Keep a map of users and match with incoming messages
const Discord = require('discord.js')
const client = new Discord.Client()
const map = {}
client.on('message', msg => {
if (msg.content.indexOf('#') !== -1) {
const users = msg.content.match(/#[a-z\d]+/ig)
users.forEach((user) => {
if (map[users.slice(1)]) {
console.log(`${users.slice(1)} mentioned in server`)
}
})
}
})
client.on('ready', () => {
setInterval (function (){
for(u in Bot.users){
map[client.users[u].username] = true
}
}, 10000)
})
client.login('token')

Categories

Resources