I'm trying to use client.guilds , but it just seems to return this really weird object that I have no idea how to parse.
Object:
GuildManager {
cacheType: [Function: Collection],
cache: Collection(1) [Map] {
'11111111111111111' => Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '1111111111111111111',
shardID: 0,
name: 'My Server Name',
icon: '11111111111111111111111111111',
splash: null,
region: 'us-west',
memberCount: 46,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: null,
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'NONE',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1590266012969,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
vanityURLCode: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
ownerID: '111111111111111111',
emojis: [GuildEmojiManager]
}
}
}
I just simply don't know how to parse this to get the name of the servers I'm connected to. Right now I'm only connected to one server but in the future there will be more, I just want to ideally be able to say:
client.guilds.forEach(server => {
console.log(guild.name+" id: "+guild.id);
});
This object is basic collection you can iterate over.
client.guilds.forEach(server => {
console.log(server.name + " (id: " + server.id + ")");
});
Turns out I had to reference the cache object:
client.guilds.cache.forEach(server => {
console.log(server.name + " id: " + server.id);
});
Related
This is the piece of important code -
const Members = msg.guild.members.fetch();
console.log(Members)
I want to access the variables in "Members" and also want to know what data type it is (object,array,etc.)
This is the log -
Promise {
Collection [Map] {
'518759221098053634' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1595386815939,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
},
'680036979106512914' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1594698809775,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array]
},
'717347622532153396' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1595919969136,
lastMessageID: '738997364949254154',
lastMessageChannelID: '735330127944220725',
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
},
'730309712133881916' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1594954679836,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
},
'730624908748521613' => GuildMember {
guild: [Guild],
user: [User],
joinedTimestamp: 1594698780260,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
},
'738658236957458472' => GuildMember {
guild: [Guild],
user: [ClientUser],
joinedTimestamp: 1596183671593,
lastMessageID: '738997347387965531',
lastMessageChannelID: '735330127944220725',
premiumSinceTimestamp: null,
deleted: false,
_roles: [Array],
nickname: null
}
}
}
How do you store, for example, the user ID in this line:
'518759221098053634' => GuildMember {
I think there is one duplicate of this question, but i think the solutions there are outdated or for a different language.
Guild.members.fetch() is a Promise that will return:
A GuildMember if you provide a UserResolvable as the first parameter.
A Collection containing all the members in the guild if you don't provide anything as the first parameter.
message.guild.members.fetch("UserID").then(member => {
// This will return a single GuildMember object, if found.
console.log(`Found ${member.user.tag}. They are ${member.presence.status}.`);
}).catch(e => console.log("Couldn't fetch the member."));
// This will return a Collection containing all members in the Guild.
message.guild.members.fetch().then(members => {
// To store the user id(s) you can map the Collection by ID:
const IDs = members.map(user => user.id);
// --> ["UserID", "UserID", "UserID", "UserID"]
// To store certain id(s) you can use the filter method of Collection:
const OnlineMembers = members.filter(member => member.presence.status == "online");
}).catch(e => console.log("Couldn't fetch members."));
References:
Collection
GuildMember
Guild
GuildMemberManager
Promise
I have been working on a bot for 12 days now and I need to upgrade to v12. Everything was going smoothly until I tried a command that will give a specified role to a mentioned user.
I have 2 variables. One is a role variable that the user has specified and the member variable (which is equaled to message.guild.members.get(args[0])).
The code looks like this:
let Member = message.mentions.members.first() || message.guild.members.get(arguments[0]);
if (!Member) return message.channel.send("Error: Either the member does not exist or you haven't put the member to give the role to!");
let role = message.guild.roles.cache.some(r => r.name === arguments[1]) || message.guild.roles.cache.some(r => r.id === arguments[1]) || message.mentions.roles.first();
if (!role) return nessage.channel.send("Error: Please provide a valid role!");
// if (role === "undefined") {
// let role = message.guild.roles.cache.some(r => r.name === arguments[1]) || message.guild.roles.cache.some(r => r.id === arguments[1]) || message.mentions.roles.first();
// }
if (Member.roles.cache.has(role.id)) {
return message.channel.send("Error: The mentioned user already has that role!");
} else {
let role = message.guild.roles.cache.some(r => r.name === arguments[1]) || message.guild.roles.cache.some(r => r.id === arguments[1]) || message.mentions.roles.first();
console.log(message);
console.log("role" + role);
Member.roles.add(role.id).catch(e => console.log("Error: " + e.message));
}
The code looked fine to me and expected it to work, but then I got an error in the console. It doesn't say what variable is not defined, it just says it's undefined.
I tried checking if the role variable is undefined, but I commented out since it didn't work. Then, I have let it print the message and check if the role is undefined. The role variable is fine. The message variable is fine. Even the Member variable is fine.
I use the latest Node.js.
Here's the console log:
Message {
channel: TextChannel {
type: 'text',
deleted: false,
id: '729663938148565134',
name: 'general',
rawPosition: 0,
parentID: '729663938148565132',
permissionOverwrites: Collection [Map] {},
topic: 'Beware, there will be a lot of mentions.',
nsfw: undefined,
lastMessageID: '733951355240316948',
rateLimitPerUser: 0,
lastPinTimestamp: 1594845448699,
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '729663937557168181',
shardID: 0,
name: 'Bot Testing',
icon: null,
splash: null,
region: 'europe',
memberCount: 6,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '729663938148565134',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'MEDIUM',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1594035922599,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
vanityURLCode: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
ownerID: '402159567200583680',
emojis: [GuildEmojiManager]
},
messages: MessageManager {
cacheType: [Function: LimitedCollection],
cache: [LimitedCollection [Map]],
channel: [Circular]
},
_typing: Map { '402159567200583680' => [Object] }
},
deleted: false,
id: '733951355240316948',
type: 'DEFAULT',
content: '>giveRole <#!655895332722442282> Mod',
author: User {
id: '402159567200583680',
bot: false,
username: '🎁🎄KFM🎄🎁',
discriminator: '3147',
avatar: '5f322e4ab3ec14e9fa83e1c77d8bb36d',
lastMessageID: '733951355240316948',
lastMessageChannelID: '729663938148565134',
flags: UserFlags { bitfield: 0 }
},
pinned: false,
tts: false,
nonce: '733951341017169920',
system: false,
embeds: [],
attachments: Collection [Map] {},
createdTimestamp: 1595058039246,
editedTimestamp: null,
reactions: ReactionManager {
cacheType: [Function: Collection],
cache: Collection [Map] {},
message: [Circular]
},
mentions: MessageMentions {
everyone: false,
users: Collection [Map] { '655895332722442282' => [User] },
roles: Collection [Map] {},
_members: Collection [Map] { '655895332722442282' => [GuildMember] },
_channels: null,
crosspostedChannels: Collection [Map] {}
},
webhookID: null,
application: null,
activity: null,
_edits: [],
flags: MessageFlags { bitfield: 0 },
reference: null
}
roletrue
Error: undefined
Thanks in advance!
EDIT: It looks like the role.id is undefined. I will try to see how to fix that.
I think problem with this part of code
console.log("role" + role); // true
Member.roles.add(role.id).catch(e => console.log("Error: " + e.message));
You trying add undefined in roles, because:
const roleId = (true).id;
console.log(roleId); //undefined
Your got your Boolean from some function which always return true or false, try change this to find
try add some id like 733951355240316948.
I dont know how looks role.id, but role must be Object
for example:
{
id:'asdasdawe3534536456',
// other fields
}
You need find what expect .add function in Member.roles.add
I am trying to set up a belongsTo and hasMany association which seems to be working, but when I run .set I am getting the error fighterData.setUsers is not a function. The dialect is mySql. Here is my code:
Fighters.belongsTo(Users)
Users.hasMany(Fighters);
Users.sync()
Fighters.sync()
//creates the table if it doesn't exist
const insertFighter = function(obj, sessId) {
return Fighters.create(obj, {returning: true}).then((fighterData) => {
//console.log('inserted a fighter \n', fighterData);
return Users.findOne({
where: {
id: sessId
}
}).then((userData) => {
//console.log('fighterData in findOne promise \n', fighterData)
return fighterData.setUsers(userData)
}).then((success)=> {
console.log('user fighter join success')
return
}).catch((err)=> {
console.log('user fighter join error \n', err)
return
})
}).catch((err)=> {
console.log('error inserting fighter \n', err);
})
}
The error that's logging is user fighter join error.
interestingly, userData.setFighters(fighterData) works successfully, but that is not what I need
EDIT
This is what fighterData is:
fighterData in findOne promise
Fighters {
dataValues:
{ id: 7,
name: 'Gilbert Burns',
image:
'https://www.sherdog.com/image_crop/200/300/_images/fighter/20140806063215_IMG_8432.JPG',
next_opponent: 'Kamaru Usman',
next_fight: 'July 11, 2020 ',
style: 'mma',
updatedAt: 2020-06-17T06:00:40.368Z,
createdAt: 2020-06-17T06:00:40.368Z },
_previousDataValues:
{ name: 'Gilbert Burns',
image:
'https://www.sherdog.com/image_crop/200/300/_images/fighter/20140806063215_IMG_8432.JPG',
next_opponent: 'Kamaru Usman',
next_fight: 'July 11, 2020 ',
style: 'mma',
id: 7,
createdAt: 2020-06-17T06:00:40.368Z,
updatedAt: 2020-06-17T06:00:40.368Z,
UserId: undefined },
_changed:
{ name: false,
image: false,
next_opponent: false,
next_fight: false,
style: false,
id: false,
createdAt: false,
updatedAt: false,
UserId: false },
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'Fighters', singular: 'Fighter' },
omitNull: false,
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: {} },
hooks: {} },
_options:
{ isNewRecord: true,
_schema: null,
_schemaDelimiter: '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined },
isNewRecord: false }
This is returned from entering one fighter's information into the database.
The problem is with the naming of your models.
Sequelize expects your models to be named in singular form (User instead of Users), so it's getting confused with what it should name the generated setter and getter methods for your association.
If you try fighterData.setUser(userData) instead of fighterData.setUsers(userData), it should work.
If you you want to use setUsers instead, you will have to make adjustments to your model to tell Sequelize to use Users as the singular form of User:
Users.init({
sessId: Sequelize.STRING
}, {
sequelize: sequelize,
name: {
singular: 'users'
}
});
You can overwrite the plural form the same way as well.
You can read more about this here: Sequelize naming strategy
I'm writing a Node.JS code which acts as an intermediate between JavaScript client and Google DialogFlow. My problem is, when I try to echo the JSON object response to the client through a web socket connection, the nested values always read as null.
My JSON Object:
{
responseId: 'xxxx-xxxxxx-xxxxxx-xxxx',
recognitionResult: null,
queryResult: {
fulfillmentMessages: [ [Object] ],
outputContexts: [ [Object], [Object], [Object] ],
queryText: '21',
speechRecognitionConfidence: 0,
action: 'age',
parameters: { fields: [Object] },
allRequiredParamsPresent: true,
fulfillmentText: 'All right!',
webhookSource: '',
webhookPayload: null,
intent: {
inputContextNames: [],
events: [],
trainingPhrases: [],
outputContexts: [],
parameters: [],
messages: [],
defaultResponsePlatforms: [],
followupIntentInfo: [],
name: 'Intent name',
displayName: 'Default Intent',
priority: 0,
isFallback: false,
webhookState: 'WEBHOOK_STATE_UNSPECIFIED',
action: '',
resetContexts: false,
rootFollowupIntentName: '',
parentFollowupIntentName: '',
mlDisabled: false
},
intentDetectionConfidence: 1,
diagnosticInfo: null,
languageCode: 'en',
sentimentAnalysisResult: null
},
webhookStatus: { details: [], code: 0, message: '' },
outputAudio: <Buffer >,
outputAudioConfig: {
audioEncoding: 'OUTPUT_AUDIO_ENCODING_OGG_OPUS',
sampleRateHertz: 0,
synthesizeSpeechConfig: null
}
}
I'm trying to access the name value of intent. I also need to pass all the other values as well.
My Web Socket code:
const ws = require('ws');
const wss = new ws.Server({ noServer: true });
function onConnect(ws) {
ws.on('message', function (newMessage) {
ws.send(JSON.stringify(data));
}
}
(I've trimmed out parts that are irrelevant)
How can I wrap all of the data here in an array? This is auto generated from a website system and the app I'm feeding it into requires the data to be in an array. There are multiple sets of data in the JSON, this is just 2 of about 5 or 6.
collection: {
id: "5096f729e4b02d37bef658f2",
enabled: true,
starred: false,
type: 10,
ordering: 3,
title: "About",
navigationTitle: "About",
urlId: "about",
itemCount: 0,
updatedOn: 1347025745523,
publicCommentCount: 0,
folder: false,
dropdown: false,
tags: [ ],
categories: [ ],
homepage: true,
typeName: "page",
synchronizing: false,
typeLabel: "page",
fullUrl: "/"
},
websiteSettings: {
id: "5096f728e4b02d37bef658e0",
websiteId: "5096f728e4b02d37bef658df",
type: "Business",
subject: "Personal",
country: "US",
state: "NY",
markdownMode: false,
simpleLikingEnabled: true,
commerceEnabled: false,
defaultPostFormat: "%y/%m/%d/%t",
commentLikesAllowed: true,
commentAnonAllowed: true,
commentThreaded: true,
commentApprovalRequired: false,
commentAvatarsOn: true,
commentSortType: 2,
commentFlagThreshold: 0,
commentFlagsAllowed: true,
commentEnableByDefault: true,
commentDisableAfterDaysDefault: 0,
disqusShortname: "username",
homepageTitleFormat: "%s - This is a test",
collectionTitleFormat: "%c — %s - This is a test",
itemTitleFormat: "%i — %s - This is a test",
commentsEnabled: true,
allowSquarespacePromotion: false,
storeSettings: {
storeTitle: "Test",
returnPolicy: null,
termsOfService: null,
privacyPolicy: null,
stockLevelAlertLimit: 5,
useLightCart: false,
stripeConnected: false,
storeState: 3
}
}
Okay so assume you have the JSON returned from the API in a variable called rawJson. That is easy enough for you to do with jquery, for example with getJSON. Now you can you acheive what you want with this code:
var rawJson = // get this yourself, pretend I'm inserting the JSON literal from the url you linked to above in your comments
arrayYouWant = [];
for (category in rawJson) {
for (key in rawJson[category]) {
arrayYouWant.push( {key: rawJson[category][key]} )
}
}
You can also flat those two objects and convert them into an array, see the snippet below.
var rawJSON = {
collection: {
id: "5096f729e4b02d37bef658f2",
enabled: true,
starred: false,
type: 10,
ordering: 3,
title: "About",
navigationTitle: "About",
urlId: "about",
itemCount: 0,
updatedOn: 1347025745523,
publicCommentCount: 0,
folder: false,
dropdown: false,
tags: [],
categories: [],
homepage: true,
typeName: "page",
synchronizing: false,
typeLabel: "page",
fullUrl: "/"
},
websiteSettings: {
id: "5096f728e4b02d37bef658e0",
websiteId: "5096f728e4b02d37bef658df",
type: "Business",
subject: "Personal",
country: "US",
state: "NY",
markdownMode: false,
simpleLikingEnabled: true,
commerceEnabled: false,
defaultPostFormat: "%y/%m/%d/%t",
commentLikesAllowed: true,
commentAnonAllowed: true,
commentThreaded: true,
commentApprovalRequired: false,
commentAvatarsOn: true,
commentSortType: 2,
commentFlagThreshold: 0,
commentFlagsAllowed: true,
commentEnableByDefault: true,
commentDisableAfterDaysDefault: 0,
disqusShortname: "username",
homepageTitleFormat: "%s - This is a test",
collectionTitleFormat: "%c — %s - This is a test",
itemTitleFormat: "%i — %s - This is a test",
commentsEnabled: true,
allowSquarespacePromotion: false,
storeSettings: {
storeTitle: "Test",
returnPolicy: null,
termsOfService: null,
privacyPolicy: null,
stockLevelAlertLimit: 5,
useLightCart: false,
stripeConnected: false,
storeState: 3
}
}
}
var myObject = Object.assign({}, rawJSON.collection); // merging objects aka extend
myObject = Object.assign(myObject, rawJSON.websiteSettings);
// {a: 1, b: 2} => [['a', 1], ['b', 2]]
var objAsAnArray=Object.keys(myObject).map((k)=>[k, JSON.stringify(myObject[k])])
console.log(objAsAnArray)