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
Related
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.
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?
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?
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
I have defined a Model with mongoose like this:
var mongoose = require("mongoose")
var Schema = mongoose.Schema
var userObject = Object.create({
alias: String,
email: String,
password: String,
updated: {
type: Date,
default: Date.now
}
})
var userSchema = new Schema(userObject, {strict: false})
var User = mongoose.model('User', userSchema)
module.exports = User
Then I created a user that I can perfectly find through mongo console like this:
db.users.findOne({ email: "coco#coco.com" });
{
"_id" : ObjectId("55e97420d82ebdea3497afc7"),
"password" : "caff3a46ebe640e5b4175a26f11105bf7e18be76",
"gravatar" : "a4bfba4352aeadf620acb1468337fa49",
"email" : "coco#coco.com",
"alias" : "coco",
"updated" : ISODate("2015-09-04T10:36:16.059Z"),
"apps" : [ ],
"__v" : 0
}
However, when I try to access this object through a node.js with mongoose, the object a retrieve is not such doc, but a wrapper:
This piece of code...
// Find the user for which the login queries
var User = require('../models/User')
User.findOne({ email: mail }, function(err, doc) {
if (err) throw err
if (doc) {
console.dir(doc)
if(doc.password == pass) // Passwords won't match
Produces this output from console.dir(doc)...
{ '$__':
{ strictMode: false,
selected: undefined,
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
version: undefined,
getters: {},
_id: undefined,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: { paths: [Object], states: [Object], stateNames: [Object] },
ownerDocument: undefined,
fullPath: undefined,
emitter: { domain: null, _events: {}, _maxListeners: 0 } },
isNew: false,
errors: undefined,
_doc:
{ __v: 0,
apps: [],
updated: Fri Sep 04 2015 12:36:16 GMT+0200 (CEST),
alias: 'coco',
email: 'coco#coco.com',
gravatar: 'a4bfba4352aeadf620acb1468337fa49',
password: 'caff3a46ebe640e5b4175a26f11105bf7e18be76',
_id: { _bsontype: 'ObjectID', id: 'Uét Ø.½ê4¯Ç' } },
'$__original_validate': { [Function] numAsyncPres: 0 },
validate: [Function: wrappedPointCut],
_pres: { '$__original_validate': [ [Object] ] },
_posts: { '$__original_validate': [] } }
Therefore, passwords won't match because doc.password is undefined.
Why is this caused?
That's exactly the purpose of mongoose, wrapping mongo objects. It's what provides the ability to call mongoose methods on your documents. If you'd like the simple object, you can call .toObject() or use a lean query if you don't plan on using any mongoose magic on it at all. That being said, the equality check should still hold as doc.password returns doc._doc.password.