Member Status command shows number of people streaming - javascript

I made a member status command for my discord bot. Here is my code:
const { stripIndent } = require('common-tags');
client.on("message", (message) => {
if (message.content.toLocaleLowerCase().startsWith("+members")) {
const members = message.guild.members.cache.array();
const online = members.filter((m) => m.presence.status === 'online').length;
const offline = members.filter((m) => m.presence.status === 'offline').length;
const dnd = members.filter((m) => m.presence.status === 'dnd').length;
const afk = members.filter((m) => m.presence.status === 'idle').length;
const streaming = members.filter((m) => m.presence.status === 'streaming').length;
const embed = new MessageEmbed()
.setTitle(`Member Status [${message.guild.members.cache.size}]`)
.setThumbnail(message.guild.iconURL({ dynamic: true }))
.setDescription(stripIndent`
**Online:** \`${online}\` members
**Busy:** \`${dnd}\` members
**AFK:** \`${afk}\` members
**Offline:** \`${offline}\` members
**Streaming:** \`${streaming}\` members
`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send(embed);
}
});
I want the number the number of people who are streaming to be shown too. However even when there are users who are streaming my bot shows 0 at the Streaming People count. Anyway to fix this out?
Thanks in Advance

PresenceStatus via member.presence.status can only be online, idle, offline or dnd.
To check if a user is streaming, you need to use the activities of a Presence.
member.presence.activities returns an Array<Activity>. You can use the ActivityType to check if a member is streaming.
To put it all together:
member.presence.activities.forEach(activity => {
if (activity.type == "STREAMING") {
// member is currently streaming
}
});

Related

How can I show every voice channel ID/name of a guild with DiscordJS?

I'm trying to get and show all the voice channels name from guild.
That's my code, that not working
client.on('ready', () => {
client.channels.fetch().then(channel =>
{
console.log(channel.name)
});
}
I'd like to list all names of voice channels (not text).
Filter the channels by type ChannelType.GuildVoice then map them to their name and id.
// import or require ChannelType from discord.js
const allChannels = await client.channels.fetch();
const voiceChannels = allChannels
.filter(ch => ch.type === ChannelType.GuildVoice);
console.log(
voiceChannels
.map(ch => `${ch.id} | ${ch.name}`)
.join('\n')
);
First you have to retrieve all channels using the channel cache of your client object. Then you filter by their type:
let voiceChannels = client.channels.cache.filter(m => m.type === 'voice');
voiceChannels.forEach(channel => console.log(channel.name));

Discord.js online members command

I am making a discord bot and I'm trying to make a command that sends a message with all the members that are currently online.
You cannot reliably check whether a user is online or not. However you could use their presence.status and count all people that don't have a status of "offline". But as I said even online users are still able to set their status to "offline".
With cache:
const onlineMembers = message.guild.members.cache.filter(
member => !member.user.bot && member.user.presence.status !== "offline"
).size;
With fetch:
const onlineMembers = (await message.guild.members.fetch()).filter(
member => !member.user.bot && member.user.presence.status !== "offline"
).size;
According to the offical Discord.js docs these are all options a PresenceStatus can be set to:
The status of this presence:
online - user is online
idle - user is AFK
offline - user is offline or invisible
dnd - user is in Do Not Disturb
Also you may encounter some issues due to Discord Privileged Intent.
You might need to explicitly allow them like so:
const client = new Client({
ws: { intents: ["GUILD_PRESENCES", "GUILD_MEMBERS"] },
});
Edit
I really dislike that kind of spoonfeeding but there you go:
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("message", async (message) => {
if (message.author.bot) return;
if (message.content === "!online") {
const onlineMembers = (await message.guild.members.fetch()).filter(
(member) => !member.user.bot && member.user.presence.status !== "offline"
).size;
return message.channel.send(`Online users: ${onlineMembers}`);
}
});
client.login("your-token");

Missing permissions error when using mute command discord.js

I have two servers with my bot on it with two groups of friends. On one server, the bot and I both have admin perms, and I can mute someone who doesn't have those perms. On the other server, I'm the owner and the bot has admin, but I can't mute anyone. I get the error 'Missing Permissions'.
Here's the code:
const Discord = require('discord.js')
const ms = require('ms')
module.exports = {
name: 'mute',
execute(message, args) {
if(!args.length) return message.channel.send("Please Specify a time and who to mute. For example, '!mute #antobot10 1d' And then send the command. Once the command is sent, type the reason like a normal message when I ask for it!")
const client = message.client
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send("You don't have permission to use that command!")
else {
const target = message.mentions.members.first();
const filter = (m) => m.author.id === message.author.id
const collector = new Discord.MessageCollector(message.channel, filter, { time: 600000, max: 1 })
const timeGiven = args[1]
message.channel.send('The reason?')
collector.on('collect', m => {
collector.on('end', d => {
const reason = m
message.channel.send(`${target} has been muted`)
target.send(`You have been muted on ${message.guild.name} for the following reason: ***${reason}*** for ${timeGiven}`)
if(message.author.client) return;
})
})
let mutedRole = message.guild.roles.cache.find(role => role.name === "MUTE");
target.roles.add(mutedRole)
setTimeout(() => {
target.roles.remove(mutedRole); // remove the role
target.send('You have been unmuted.')
}, (ms(timeGiven))
)
}
}
}
Ok, I'm not exactly sure what I did, but it's working now. I think I just changed it so that the MUTE role had 0 permissions instead of normal permissions but making it so that if you have the role you can't talk in that certain channel.
Thanks for the answers!
If your bot's role is below the role of the user you are attempting to mute, there will be a missing permissions error. In your server settings, drag and drop the bot role as high in the hierarchy it will go. This will solve your problem.

discord.js v12 Userinfo command works when user isn't mentioned or when user id is given

I made a userinfo command which works on mentioning the user. Here is the code:
client.on('message', async message => {
if (message.content.startsWith('+ui')) {
const args = message.content.slice(4).trim().split(/ +/g);
const member = message.mentions.members.first();
const embed = new MessageEmbed()
.setTitle(`${member.displayName}'s Information`)
.setThumbnail(member.user.displayAvatarURL({
dynamic: true
}))
.addField('User', member, true)
.addField('Discriminator', `\`#${member.user.discriminator}\``, true)
.addField('ID', `\`${member.id}\``, true)
.addField('Status', statuses[member.presence.status], true)
.addField('Bot', `\`${member.user.bot}\``, true)
.addField('Color Role', member.roles.color || '`None`', true)
.addField('Highest Role', member.roles.highest, true)
.addField('Joined server on', `\`${moment(member.joinedAt).format('MMM DD YYYY')}\``, true)
.addField('Joined Discord on', `\`${moment(member.user.createdAt).format('MMM DD YYYY')}\``, true)
.setFooter(message.member.displayName, message.author.displayAvatarURL({
dynamic: true
}))
.setTimestamp()
.setColor(member.displayHexColor);
if (activities.length > 0) embed.setDescription(activities.join('\n'));
if (customStatus) embed.spliceFields(0, 0, {
name: 'Custom Status',
value: customStatus
});
if (userFlags.length > 0) embed.addField('Badges', userFlags.map(flag => flags[flag]).join('\n'));
message.channel.send(embed);
}
});
However, this only works when the message sent is +ui #User. However, if I want my own userinfo I need to use +ui #mention where I mention myself.
How can I make the bot send the message author's output when no mentions are given and userinfo if a user's id is given instead of mention.
Sorry for any kind of misunderstanding caused by the question. Thanks in advance
You can add a fallback value when message.mentions.members.first() gives you undefined.
const member = message.mentions.members.first() || message.member

Creating invite on guildCreate

I'm trying to create a Discord bot that'll create an invite to the first channel of a Guild when it's added to the aforementioned guild and sending it to the console.
My code (it doesn't work):
client.on("guildCreate", guild => {
const channel = Array.from(guild.channels).sort((a, b) => a.calculatedPosition - b.calculatedPosition)[0];
channel.createInvite({
unique: true
})
.then(invite => {
console.log(`Joined to: ${guild.name} Invite: https://discord.gg/${invite.code}`);
})
});
// Listeing to the guildCreate event.
client.on("guildCreate", guild => {
// Filtering the channels to get only the text channels.
const Channels = guild.channels.cache.filter(channel => channel.type == "text");
// Creating an invite.
Channels.first().createInvite({
maxUses: 1,
unique: true
}).then(invite => {
console.log(`[INVITE] I've created an invite for ${guild.id}:${guild.name} - ${invite.url}`);
});
});

Categories