Get presence/activity of mentioned user - javascript

I'm trying to create a command for my bot in Discord JS that when triggered, takes the command's mentioned user and retrieves their current game (If no game, then status) and sends a message saying Mentioned user has been playing Game for Time elapsed (And if possible, send the image of the game if it has one).
This is my current code:
module.exports = {
name: 'game',
aliases: ['gm', 'status'],
category: 'Commands',
utilisation: '{prefix}game',
execute(client, message) {
let msgMention = message.mentions.members.first() || message.guild.member(message.author)
console.log(msgMention.presence.activities[0])
message.channel.send(msgMention.presence.activities[0].name);
},
};
All it does with the .name extension says name is undefined and if I remove .name it says cannot send an empty message. Also, I mention myself currently playing a game that so shown publicly on my discord activity status. What can I do so it actually reads the name and time of the activity to then send it?

You need the GUILD_PRESENCES intent.
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_PRESENCES] });
Also btw I'd recommend using message.member instead of message.guild.member(message.author)
let msgMention = message.mentions.members.first() || message.member

Related

Members arent cached

I'm trying to make a selfbot and before receiving messages saying that's against Discord ToS, I take that risk. My bot sends messages only to people it already has a DM channel opened with, probably because members aren't cached.
I want my bot to send message to everyone in my server. How do I cache members on a selfbot?
Code:
const guild = client.guilds.cache.get("id");
if(!guild) return;
guild.members.fetch();
guild.members.cache.random().createDM().then((dm => {
dm.send("Dont forget to verify !").catch(e => console.log('error'))
})).catch(() => {});
console.log("message sent");
Server Members Intent Image
Image above shows example to this answer;
Did you enable SERVER MEMBERS INTENT when creating your Discord bot?
https://discord.com/developers/applications/"ClientId"/bot
And/or did you create a new discord client with the GUILD_MEMBERS intent?
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.GuildMembers
]
});
And whether or not you know the risks, you should NOT be using self bots.

Get a List of Members in a Guild Discord.js

Can you list members of a guild you're not a part of with a Discord bot? I'm trying to grab guild members but it looks like:
You can only add a bot to a discord server you have admin privileges in
Your bot needs to be part of the "guild" (discord server) to access a member list
Number 2 is the one I'm uncertain of, some documentation seems to indicate that you can just add the guild's ID (which I grabbed via developer view) but the guild is returning "undefined" so I'm wondering if the problem is that number 2 is true but just not explicitly mentioned in any docs i could find.
I also thought of a workaround being to use my personal account that's already in the server's client id but I'm not sure I can set a client instance to my personal user ID.
If so how would I do that? I've already checked that my bot has privileged gateway intents enabled to grab members, but my client.guilds.cache.get("GUILD_ID"); is returning "undefined" (note that in my actual code this is the real guild ID).
Below is the full code, including configuration since I haven't seen anyone list that and I'm not even sure how the code is supposed to know what my clientID is meant to be
//Gets Discord API Wrapper
const discord = require("discord.js");
const fs = require('fs')
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
//This doesn't seem to actually do anything :/
client.on("ready", () => {
console.log("I am ready!");
});
//GUILD_ID is my actual guild ID in live code
const list = client.guilds.cache.get("GUILD_ID");
console.log(list);
// Fetch and get the list named 'members'
list.members.each(member => {
console.log(member.user.username)
let content = member.displayName + "_" + member.user.id + "_" + member.user.nickname + "_" + member.user.username
console.log(content)
// Do whatever you want with the current member
fs.writeFile('/memberinfo.txt', content, { flag: 'a+' }, err => {
if (err) {
console.error(err)
return
}
})
});
//official docs include this after other code, but why after? TOKEN_VALUE is actual token in live code
client.login("TOKEN_VALUE");
I haven't even gotten past list.members.each(member => { so the code below is probably incorrect, but I just can't figure out why console.log(list); spits out "undefined" which is causing the following error:
TypeError: Cannot read properties of undefined (reading 'members')
Do I need to set clientId? How would I do that? What's the point of the token the bot generated if it's being set after the call is supposed to be made?

How to get users in voice channel without cache in DiscordJS?

I'm trying to get all users connected to a voice channel on my server. When someone talks to a bot in #general, I want to get the users inside Voice Channel 1.
I'm using Node 17 and DiscordJS 13.
This is my code:
message.guild.channels
.fetch(channelID, { cache: false, force: true })
.then((channels) => {
console.log(channels.members);
});
Also, I tried this one:
let voiceChannel = client.guilds.cache
.get(process.env.DISCORDJS_GUILD_ID)
.channels.cache.get(process.env.DISCORDJS_CHANNEL_ID);
let membersInChannel = voiceChannel.members;
console.log(membersInChannel);
But, it always returns the voice channel users that joined when I start the node app. If someone leaves the voice channel, it keeps showing him in the console.log when I say something to the bot in #general. How can I achieve this?
I've had the same problem. Although I added { force: true } as the option in fetch, it always showed the same number of members when I started the app, ignoring the ones who joined/left the channel.
Enabling the GUILD_VOICE_STATES intent solved this. So don't forget to add it to your client:
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_VOICE_STATES,
],
});

Event messageCreate not firing/emitting when I send a DM to my bot (discord.js v13)

I made this code for logging the DMs that are sent to my bot:
client.on('messageCreate', async message => {
if (message.author.bot) return;
const attachment = message.attachments.first()
if (message.channel.type === 'DM') {
console.log(message.content)
const dmLogEmbed = new MessageEmbed()
.setColor("RANDOM")
.setTitle(`${message.author.tag} dmed the bot and said: `)
.setDescription(message.content)
.setFooter(`User's id: ${message.author.id}`)
if (message.attachments.size !== 0) {
dmLogEmbed.setImage(attachment.url)
}
client.channels.fetch("852220016249798756").then((channel) => {
channel.send({ embeds: [dmLogEmbed] })
})
}
});
But when updating to discord.js v13 it didn't work anymore, for what I understood the only change is that the 'dm' channel type isn't 'dm' anymore but 'DM', so I changed it in my code, but it is still not working and I don't really know why.
Make sure you have DIRECT_MESSAGES in your client's intents.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"] });
There is a breaking change in the Discord API v8. For reference see here.
On Discord API v8 and later, DM Channels do not emit the CHANNEL_CREATE event, which means discord.js is unable to cache them automatically. In order for your bot to receive DMs, the CHANNEL partial must be enabled.
So we need to enable the partial CHANNEL as well. Keep in mind that when dealing with partial data, you often want to fetch the data, because it is not complete. However this doesn't seem to be your case, if you are using the messageCreate event. The message received is not partial nor message.channel. To check if something is partial, you can use the .partial property. For example Message.partial or Channel.partial.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES"], partials: ["CHANNEL"] });
Now it should work as good old discord.js v12.

Why am I getting an undefined when trying to get a Guild in Discord.js?

I'm pretty new to working on Discord bots, but I'm trying to create a bot for Discord that gets all the members in a guild, so they can be used later on. But everytime I try to get the guild with its ID it gives an undefined back, even though I know I put in the right ID.
const Discord = require("discord.js");
const client = new Discord.Client();
const members = client.guilds.cache.get("guildID");
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
console.log(members);
});
client.login('token');
Am I doing something wrong?
You aren't being very clear. You stated you want your bot to get all members in a guild, but you proceed to get a guild ID instead.
Assuming you want to get all members in a guild. First thing you need is Privileged Gateway Intents enabled in your bot and implemented in your code.
Step 1: Enable Intents
Go to your Bot App Dev
Select your bot
Head to the Bot section of your bot and scroll down till you see "Privileged Gateway Intents" and select both "PRESENCE INTENT" and "SERVER MEMBERS INTENT
"
Example
Step 2: Implementing In Code
const Discord = require('discord.js');
const client = new Discord.Client({ ws: { intents: new Discord.Intents(Discord.Intents.ALL) }});
^^^^^^^
This is what is making you access all server members within a guild
Code for getting all server members:
// If prefix not set: do this: const prefix = "!"; whatever you want
const prefix = "!";
// Usernames
const members = message.guild.members.cache.map(member => member.user.tag);
// ID's
const members = message.guild.members.cache.map(member => member.user.id);
if(message.content.startsWith(prefix + "test")){ // Gets all members usernames within the guild this message was sent on.
console.log(members) // Logs all each members username
}
In depth but I hope it helps.
I believe it's just:
client.guilds.get("guildID");
and not:
client.guilds.cache.get("guildID");
Try using this instead:
client.guilds.fetch("guildID");
Also, I recommend you put that line in your ready event or somewhere where you are sure the client has fully logged in when ran to make sure that it is logged in when you run that.
Before client is ready, use client.guilds.fetch('<guild id>') which returns a promise. Note that before the ready event is triggered many things on the client are uninitialized such as client.user
Put the const members = client.guilds.cache.get("guildID"); inside the ready event.
Try:
const members = client.guilds.cache.get("guildID");
list.members.cache.forEach(member => console.log(member.user.username));

Categories