How do I get specific values from a collection map - javascript

So I'm trying to make a bot using DiscordJS here.
I am currently trying to display user details. When I get the details, I'm not sure how to fetch specific details.
So I'm getting a user by doing
const user = await utils.findUser(message, args[0]);
Now here I get a user based on whatever the user entered in args.
The user variable looks something like this:
Collection [Map] {
'211975876747853825' => GuildMember {
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
shardID: 0,
name: 'Elchea Kingdom',
icon: 'cd8156aed6c8ebc482df2252936afcee',
splash: null,
region: 'eu-west',
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: null,
verificationLevel: 'MEDIUM',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
defaultMessageNotifications: 'MENTIONS',
systemChannelFlags: [SystemChannelFlags],
vanityURLCode: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
ownerID: '211975876747853825',
emojis: [GuildEmojiManager]
},
user: User {
bot: false,
discriminator: '0006',
avatar: '5ebd62928be9bd413a2b5f6e638587ea',
lastMessageID: null,
lastMessageChannelID: null,
flags: [UserFlags]
},
premiumSinceTimestamp: null,
deleted: false,
_roles: [
'600421802702929920',
'600737807664939008',
'603343858549391360',
'600425094598361091',
'600422841279578118',
'603314411243044875',
'617699524474830859',
'603316305495326740',
'617505016328224790',
'617449137767710743'
]
}
}
Now let's say I want to get get the Guild name which is "Elchea Kingdom". How could I do that? I have tried using Map.prototype.values() and iterate with it, but it doesn't work. I get an undefined value. I've tried doing stupid things such as user[0] and user.Guild to get guild information. But I always keep getting undefined value. What am I doing wrong, could you please guide me.

https://discord.js.org/#/docs/main/stable/class/Collection
You should call the variable users and then get member by .first()
const users = await utils.findUser(message, args[0]);
const member = users.first();
const user = member.user;
Which library are you using for the variable utils btw?

Related

Filtering for activity with certain property

In discordjs, I'm trying to read a users presence and then do "If one of presences stated (A user can have Spotify and a game simultaneously as an example) has a name of, say Spotify, in it's properties, do something". My code is:
let uset = msgMention.presence.activities
if (uset.filter(game => game.name == 'Spotify')){
//something
}
Since multiple games return multiple items in an array (seen below)
[
Activity {
name: 'Spotify',
type: 'LISTENING',
url: null,
details: null,
state: 'NO',
applicationID: 'NO',
timestamps: no,
party: null,
assets: RichPresenceAssets {
largeText: null,
smallText: null,
largeImage: 'no',
smallImage: null
},
syncID: no,
flags: ActivityFlags { bitfield: 1 },
emoji: null,
createdTimestamp: no
},
Activity {
name: 'Visual Studio Code',
type: 'PLAYING',
url: null,
details: 'Editing league.js',
state: 'Workspace: Vibin-Tachanks',
applicationID: '383226320970055681',
timestamps: { start: 2021-12-04T18:35:34.918Z, end: null },
party: null,
assets: RichPresenceAssets {
largeText: 'Editing a JAVASCRIPT file',
smallText: 'Visual Studio Code',
largeImage: '808841241142755358',
smallImage: '565945770067623946'
},
syncID: undefined,
flags: ActivityFlags { bitfield: 0 },
emoji: null,
createdTimestamp: 1638645018501
}
]
how can I make this if statement work to filter out this returned array and only keep Spotify in it, and then access the name (or any property) of said filtered item. yes, i do have detecting presences working with intents and such so I know I've gotten that far, it's just filtering with an if (Also no just means I dont want to show whats in it)
You could just use this filter that you used inside a variable and as the condition of the if statement you could just check if it's different than empty array "[]".
Doing this way you can use the values inside the variable if you have any.

Sending stickers in Discord.js V13

I am trying to forward messages sent to my bot via DM.
Everything works, except sending the stickers.
Every time I try to send the a message with a sticker, I just get an Error DiscordAPIError: Cannot use this sticker.
This is part my code:
let userMessage = new discord.MessageEmbed().setDescription(message.content || "᲼")
let messageAttachment =
message.attachments.size > 0 ? message.attachments.first().url : null
userMessage.setImage(messageAttachment)
let messagePayload = {
content: null,
embeds: [],
stickers: null
}
messagePayload.content = `User <#${message.author.id}> said:`
messagePayload.embeds.push(userMessage)
messagePayload.stickers = message.stickers?.size > 0 ? [message.stickers.first()] : null
client.users.fetch(config.ids.me, false).then((user) => {
user.send(messagePayload)
})
and the messagePayload looks like this:
{
content: 'User <#USERID> said:',
embeds: [
MessageEmbed {
type: 'rich',
title: null,
description: '᲼',
url: null,
color: null,
timestamp: null,
fields: [],
thumbnail: null,
image: [Object],
video: null,
author: null,
provider: null,
footer: null
}
],
stickers: [
Sticker {
id: '749054660769218631',
description: null,
type: null,
format: 'LOTTIE',
name: 'Wave',
packId: null,
tags: null,
available: null,
guildId: null,
user: null,
sortValue: null
}
]
}
In the Docs about sending stickers, it just says it has to be an Array either a Sticker-Object or a Snowflake. Since I am fetching the sticker Object, I assumed that just grabbing it and passing it into my messagePayload would do the job, but somehow the API does not accept it.
discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS, is set, but it does not work with standard stickers aswell (e.g. messagePayload above)
As it turns out, you can only send stickers from a guild, inside that same guild.
See Github Issue.

What is the executor property for the MEMBER_ROLE_UPDATE audit log if the role is managed by an integration?

I'm creating a Discord logging bot to log all the role updates to the members of my server and also who executed those changes. I've observed some of the audit log entries for the audit log action MEMBER_ROLE_UPDATE and I get this:
GuildAuditLogsEntry {
targetType: 'USER',
actionType: 'UPDATE',
action: 'MEMBER_ROLE_UPDATE',
reason: null,
executor: User {
id: '334911278298562561',
bot: false,
username: 'Pritt',
discriminator: '0780',
avatar: 'e5e205996571c0c7c4e69246027fb1f8',
flags: UserFlags { bitfield: 256 },
lastMessageID: null,
lastMessageChannelID: null
},
changes: [ { key: '$add', old: undefined, new: [Array] } ],
id: '732185365166817280',
extra: null,
target: User {
id: 'hidden',
bot: false,
username: 'hidden',
discriminator: '3203',
avatar: 'hidden',
flags: UserFlags { bitfield: 256 },
lastMessageID: null,
lastMessageChannelID: null
}
}
This is fairy simple, its a log I collected for when I updated the role of a user in my server. I can see the executor property is the user object.
My only confusion is when the role in question is managed by an integration (such as the nitro booster role or any of the bot roles). These roles cannot be manually assigned or removed by any members so the executor of the audit log entry cannot be a user. What would this property be then?

How to only get UserID from message.guild.members.fetch() in discord.js v12?

I'm trying to get a random winner for prizes and I would like to take the whole object variable and just sorta isolate the whole thing so i just get a list of the UserID's
Heres an example of what I get when I do console.log(message.guild.members.fetch()):
Promise {
Collection [Map] {
'123456789012345678' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1234567890123,
lastMessageID: '012345678901234567',
lastMessageChannelID: '012345678901234567',
deleted: false,
_roles: [Array]
},
'234567890123456789' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1234567890123,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array]
},
'345678901234567890' => GuildMember {
guild: [Guild],
user: [ClientUser],
joinedTimestamp: 1234567890123,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array]
}
}
}
I would like to only get the 123456789012345678 part of the '123456789012345678' => GuildMember {line
Use the keys method (inherited from Map):
message.guild.messages.fetch().then(members => {
const userIDs = [...members.keys()]
// Do something with the IDs here
})
With async/await:
const userIDs = [...(await message.guild.messages.fetch()).keys()]
// Do something with the IDs here

Loop through Snowflake array

I'm looking for a way to get data from this Collection.
The data looks like:
'0000000' => GuildMember {
guild:
Guild {
members: [Object],
id: '000000',
name: 'Zombie',
_rawVoiceStates: [Object] },
user:
User {
id: '0000000',
username: 'Orc',
_roles: [ '0000' ],
nickname: 'Orc',
joinedTimestamp: 00000,
lastMessageID: null },
'0000000' => GuildMember {
guild:
Guild {
members: [Object],
id: '000000',
name: 'Zombie',
_rawVoiceStates: [Object] },
user:
User {
id: '0000001',
username: 'Orc1',
_roles: [ '0000' ],
nickname: 'Orc',
joinedTimestamp: 00000,
lastMessageID: null },
_array: null,
_keyArray: null }
My current loop is:
var user;
for(var u in test.members){
user = test.members[u];
console.log("["+u+"] "+user.username);
}
It currently kicks back a TypeError: Cannot read property 'user' of null
I originally thought this the data was an array, but it's not according to the Discord.js docs, but I'm still not sure how to pull the username data from the collection.
Any help would be helpful.
Now i looked into the discord.js API and i think what u got todo is something like this (assuming test is your guild object):
test.members.forEach(function(guildMember, guildMemberId) {
console.log(guildMemberId, guildMember.user.username);
})
If that doesn't work try along the lines of:
var membersArray = test.members.array();
for(var guildMemberId in membersArray) {
console.log(guildMemberId, membersArray[guildMemberId].user.username);
}
TypeError: Cannot read property 'user' of null
means your user variable is null which means test.members[u] is null.
Try logging the test.members first and see if its filled.
user.user.username
is probably wrong. As it looks it should be just user.username

Categories

Resources