Member online counter - javascript

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.

Related

Discord.js assigning role to all users, works in test server but not on live server(command)

I have slight issue I have discord bot in discord.js, we recently added 3 roles that are defaulted on each new member. But ofc this not apply to all the old ones and I dont really fancy assigning it to each individual user. So I made this following script below, This script works fully on my test discord server but throws errors on the live server. The error is"Cannot read property 'roles' of undefined". Anyone knows why that is the case?
module.exports = {
commands: ['updatetags', 'utall'],
minArgs: 0,
expectedArgs: "Incorrect Syntax",
callback: (message) => {
let cosmeticTag = message.guild.roles.cache.find(role => role.name === "━━━━━{Cosmetics}━━━━━");
let otherTag = message.guild.roles.cache.find(role => role.name === "╶━━━━━{Other}━━━━━╴");
let gamesTag = message.guild.roles.cache.find(role => role.name === "╶━━━━━{Games}━━━━━╴");
const members = message.guild.members.cache.map((member) => member);
for (let index = 0; index < message.guild.memberCount; index++) {
members[index].roles.add(cosmeticTag)
members[index].roles.add(otherTag)
members[index].roles.add(gamesTag)
}
message.reply('Updated Role Dividers For All Members').then(message => {
message.delete({
timeout: 10000
});
}).catch();
},
}

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

Show users connected to voice channel?

I want to know is it possible to know if any member is connected to a any voice channel in discord.js v12.2.0. Please let me know if you have any clues on it.
Use VoiceChannel.members
const vc = <message>.guild.channels.cache.get('VC Id')
const members = vc.members //COLLECTION
To check if a member is in vc, use GuildMember.voice
const vc = <member>.voice.channel //VOICE CHANNEL
//if you want, you can check the vc name, id, etc with vc.name, vc.id, etc
EDIT
Here is an example for what you said in the comments
//MAKE SURE IT IS ASYNC CALLBACK
await client.guilds.fetch();
const VCs = [];
client.guilds.cache.forEach(async guild => {
await guild.channels.fetch();
let VCs = guild.channels.cache.filter(c => c.type === 'voice');
VCs.forEach(vc => {
if(vc.members) {
VCs.push(vc)
}
})
})
I hope this is what you wanted (VCs is an array with all VCs with members)

Discord js addedRole executor

Basically this code, if user gave a role or lost a role log this condition
client.on('guildMemberUpdate', (oldMember, newMember) => {
let channel = oldMember.guild.channels.cache.find(channel => channel.name === "member-log");
let addedRoles = newMember.roles.cache.filter(role => !oldMember.roles.cache.has(role.id));
let removedRoles = oldMember.roles.cache.filter(role => !newMember.roles.cache.has(role.id));
if (removedRoles.size > 0) {
const removeRoleEmbed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setAuthor(`${oldMember.user.tag}` , oldMember.user.avatarURL())
.setDescription(`<#!${oldMember.id}> kişisinden <#&${removedRoles.map(r => r.id)}> rolü alındı.`)
.setTimestamp()
.setFooter(`Kullanıcı ID : ${oldMember.id}`)
channel.send(removeRoleEmbed)
}
if (addedRoles.size > 0) {
const addRoleEmbed = new Discord.MessageEmbed()
.setColor('#80FF00')
.setAuthor(`${oldMember.user.tag}` , oldMember.user.avatarURL())
.setDescription(`<#!${oldMember.id}> kişisine <#&${addedRoles.map(r => r.id)}> rolü verildi.`)
.setTimestamp()
.setFooter(`Kullanıcı ID : ${oldMember.id}`)
channel.send(addRoleEmbed)
}
});
I have this code and i want who give role a user
Note: Sorry for my english and thank in advance
For that, I believe you need to look at the Audit logs. Now, in Djs v12, you can check audit logs easily. You're looking for the MEMBER_ROLE_UPDATE action. Here are the list of all possible actions.
Here's from the Guide on how to listen to Audit Logs:
https://discordjs.guide/popular-topics/audit-logs.html
(Assuming async function)
const log = await message.guild.fetchAuditLogs({ limit: 1, type: 'MEMBER_ROLE_UPDATE' }).then(logs => logs.entries.first());
// This should log the id of the person who gave out that role.
console.log(log.executor.id);
That's it.

Categories

Resources