client.guilds.cache.get(...). members.get It is not a function - javascript

I'm doing a command with cargo, this error comes and I can't understand it, here's the script:
const member = client.guilds.cache.get('980553630480474232').members.get(interaction.user.id);
And here is the error:
client.guilds.cache.get(...).members.get is not a function.

In v13, you need to use .cache.get(), if the error persists double check your guild ID.
If you encounter such an error try console.log() to see wich value is undefined, because such errors results from having undefined values.
And for future advice if you need a value more than once in your code define it first, in this case use
const guild = client.guilds.cache.get('980553630480474232');
const member = guild.members.cache.get('ID')
Side Note: If this is a command file, you can directly get the guild using:
interaction.guild.members.get(interaction.user.id)

Related

How do I fix the error TypeError: can't access property "isRoot", location is undefined in Firebase?

I have an issue where, when I use firebase storage, I get the error:
TypeError: can't access property "isRoot", location is undefined
I am using SvelteKit, and have tested (because location is a browser object) it in an onMount call, as well as checking the browser form $app/environment. I have found the error is caused by these lines, I believe the listAll function:
listAll(filesRef).then((list)=>{
list.items.forEach(item=>{
files.push({
filetype:item.name.split(".").at(-1).toString(),
name:item.name
});
});
});
For context, the files variable is a list of objects with the filetype and filename.
I render these in a list.
If it helps, here's the entire traceback:
list$2 requests.ts:182
list$1 reference.ts:406
listAllHelper reference.ts:361
listAll$1 reference.ts:343
listAll api.ts:257
instance +page.svelte:58
init index.mjs:2002
Page +page.svelte:791
createProxiedComponent svelte-hooks.js:341
ProxyComponent proxy.js:242
Proxy<+page> proxy.js:349
construct_svelte_component_dev index.mjs:2218
update root.svelte:274
update_slot_base index.mjs:98
update +layout.svelte:154
update index.mjs:1193
flush index.mjs:1160
promise callback*schedule_update index.mjs:1118
make_dirty index.mjs:1970
ctx index.mjs:2008
$$set root.svelte:581
get proxy.js:83
$set index.mjs:2109
key proxy.js:46
update client.js:320
navigate client.js:1077
goto client.js:182
goto client.js:1249
gotoNext +page.svelte:11
instance +page.svelte:18
registerStateListener auth_impl.ts:565
promise callback*registerStateListener auth_impl.ts:565
onAuthStateChanged auth_impl.ts:407
onAuthStateChanged index.ts:128
instance +page.svelte:17
run index.mjs:18
mount_component index.mjs:1939
flush index.mjs:1175
promise callback*schedule_update index.mjs:1118
make_dirty index.mjs:1970
ctx index.mjs:2008
$$set root.svelte:581
get proxy.js:83
$set index.mjs:2109
key proxy.js:46
update client.js:320
navigate client.js:1077
goto client.js:182
goto client.js:1249
default Goto.ts:3
instance +page.svelte:14
run index.mjs:18
mount_component index.mjs:1939
flush index.mjs:1175
init index.mjs:2034
Root root.svelte:633
createProxiedComponent svelte-hooks.js:341
ProxyComponent proxy.js:242
Proxy<Root> proxy.js:349
initialize client.js:374
_hydrate client.js:1630
start start.js:39
<anonymous> [page]:10039
I found the problem
I figured out that, when I define the filesRef variable using the ref function, I forgot to define the storage attribute.
Original Definition (broken):
let filesRef = ref(`/user-generated/${$user.uid}`);
New Definition (working):
const storage = getStorage(app);
let filesRef = ref(storage, `/user-generated/${$user.uid}`);
I think that this is a bit of a problem because I spent literal hours looking for this bug. I am puzzled by the fact that it only causes an error in the listAll function, and not one relating to the storage parameter missing in the ref function. I am further puzzled that it refers to the location variable in the browser, as if it needs to check if the path is root, but can't do that in the event that the storage attribute is missing. I also know that isRoot is not a part of the location API, so maybe Firebase is extending the location API? I have used devTools to find the script and it is of the type of the window.location, so maybe Firebase should add a check for this. If this is some error that doesn't occur in JavaScript, as I'm using Typescript, but I heavily doubt this is the problem, as Typescript is complied into normal JS.

discord.js attempting to get guildMember.presence.status results in "Cannot read properties of undefined (reading 'status')"

I've been messing around with discord.js and have been trying to make a command that will allow me to list out all the online users in a server (Guild). This snippet isn't entirely mine, but from my understanding, I'm taking out the guild object from the interaction, and going further in to take out the guild member manager. From there the fetch method is called to get a collection of all the members which then gets filtered by the status.
async execute(interaction) {
let { guild: { members } } = interaction;
let allMembers = await members.fetch();
let onlineUsers = allMembers.filter((member) => member.presence.status !== 'offline');
let usernames = onlineUsers.map((member) => member.displayName);
// array of usernames of users who are not offline
console.log(usernames);
The error that I get is:
TypeError: Cannot read properties of undefined (reading 'status')
It seems that this error occurs when there are other users/other bots which are offline at the time when I run node index.js which I think is worth mentioning.
I believe to have declared my intents correctly:
client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MEMBERS] });
This is what the Discord developer portal looks like.
Any help would be appreciated!
Yeah I had the same issue a few weeks ago... this solved my problem:
let guildMembers = await <guild>.members.fetch({ withPresences: true })
var onlineMembers = await guildMembers.filter(member => member.presence?.status != "offline").size
If you want to exclude bots from counting, change the second line to this:
var onlineMembers = await guildMembers.filter(member => !member.user.bot && member.presence?.status != "offline").size
So you may have noticed, that it works now only by adding ?. after presence, but why?
Mozilla explains it like this:
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
This means, if presence is undefined or null, the ?. returns undefined or null instead of stopping the program and throwing an error. This member's status won't be added to the collection and the bot continues counting.
If you want to learn more, here's the source
Note
Keep in mind that onlineMembers will never be 100% accurate. There are always members whose status cannot be read!

Error: credentials argument needs to implement signRequest method?

When I get the Azure Credentials using "ms-rest-azure" library.
let credentials = await msRestAzure.loginWithServicePrincipalSecret(id, secret, tanent);
let newCred = JSON.stringify(credentials);
let duplicateCred = JSON.parse(newCred); // Create duplicate credentials object
Now if I going to use the "duplicateCred" for my further Azure function call, then I'll get the above error.
But if I'm using "credentials", then all is well.
So how to I assign the "credentials" object to other variable? So that i'll use the variable for my future azure API call.
Example:
let credentials = await msRestAzure.loginWithServicePrincipalSecret(id, secret, tanent);
let newCred = JSON.stringify(credentials);
let duplicateCred = JSON.parse(newCred); // Create duplicate credentials object
// Okay, here I'm getting the proper client object. Because I am using "credentials" in the below line of code.
// I'm getting the results from the below lines of code.
const client = new MonitorManagementClient(credentials, subscription);
const results = await client.operations.list();
context.log('results==> ', results);
// Error, here not getting the proper client object. Because I am using "duplicateCred" as credentials in the below line of code.
// I'm not getting the results from the below lines of code.
// At the below line I'm getting the above error.
const client = new MonitorManagementClient(duplicateCred, subscription);
const results = await client.operations.list();
context.log('results==> ', results);
How do I create a duplicate credential object from actual credentials object ?
This is incorrect method to do so. Credentials returned by msRestAzure.loginWithServicePrincipalSecret call is not a plain object it's an instance of ApplicationTokenCredentials. When you call JSON.stringify you loose this class reference and convert the whole value to Object. So cloned credentials object looses prototype chain with ApplicationTokenCredentials methods.
Also ApplicationTokenCredentials has no cloning logic what could mean it shouldn't be cloned. Using your own cloning logic could conflict with future versions of Azure library. It's better to add an issue in the official Azure SDK repository if you need to have a cloning method.
Note! ⚠️ Such way of cloning could be dangerous and leads to unexpected behaviour. You should strongly avoid it, except of cases when you really need to erase value's prototype chain!

Ramda: access input object's properties inside R.ifElse() function call

I have this existing function:
const inferProcessingError = R.ifElse(
R.propEq('conversionJobStatus', 3),
R.always('Last Process failed with error; please contact DevOps'),
R.always(null)
);
which is called like this:
const msg = inferProcessingError(jobStruct || {});
with this jobStruct:
{"id":9,"mediaGroupId":1000000,"conversionJobStatus":3,
"errorDetails": {
"Cause": {
"errorMessage": "MediaConvert Job Failed with ERROR status: ERROR Video codec [indeo4] is not a supported input video codec",
},
"Error": "Error",
}
}
and I need to create an error message string which includes the data from the Cause.errorMessage element.
This would be dead simple with a native JavaScript function, but I'm learning Ramda and want to just modify the existing code to include in the error message.
An R.prop('Cause')['errorMessage'] could work except that I can't figure out how to reference the jobStruct that was passed in to the inferProcessingError statement.
I can see that the R.ifElse and subsequent Ramda functions are able to get that reference, but when I embed an R.prop('Cause') in the error message string, it resolves to a function and not the value of the Cause element because it seems to be waiting for the data structure.
So...how do I gain access to the jobStruct reference? (arguments is not defined here).
UPDATE:
I can get this to work by referencing the original jobStruct as in R.Prop('ErrorDetails', jobStruct)['Cause']['errorMessage'] but that seems rather kludgy to me...
BUT if the call to inferProcessingError is actually inside a map statement and references an element in a larger structure, then the map index is not available to reference the data structure for the R.prop.
Perhaps you could use the pipe and path methods to achieve this "the ramda way".
Begin by using ramda's path() function to extract the nested errorMessage value from the input jobStruct object. Next, enclose that in a pipe() that transforms the extracted message into a string formatted with a custom error prefix:
const incCount = R.ifElse(
R.propEq('conversionJobStatus', 3),
/* Evaluate this pipe if the error case is satisfied */
R.pipe(
/* Path to extract message from input object */
R.path(["errorDetails", "Cause", "errorMessage"]),
/* Prefix string to extracted error message */
R.concat('Custom error prefix:')),
R.always('')
);
incCount({"id":9,"mediaGroupId":1000000,"conversionJobStatus":3,
"errorDetails": {
"Cause": {
"errorMessage": "MediaConvert Job Failed with ERROR etc etc",
},
"Error": "Error",
}
});
Here's a working example - hope that helps!
Update
Thanks to #customcommander for the suggestion to use concat for the string prefix, as well as returning an empty string value for the second branch

How to fix 'variable is not constructor' error in discord.js node project?

i'm experemeting with discord bot and tried to create record in database, but there's some troubles with it.
mongodb server is running and fully functioning.
there's two files.
first, with code of command:
https://sourceb.in/6834bfe20e.js
and second. with mongoose scheme:
https://sourceb.in/9f0c7858df.js
acrually, there's third file index file with command handler and
librarys initializations, but that's does not participate in the error.
I expected to create a record in the database, but there's error what says:
'token is not constructor' in command file:13:19
Problem:
Simply put, you're declaring a constant token, but also passing a parameter named token into your callback. When you're attempting to construct a new object based on the constant, you're actually using the callback's token variable.
Take note of this example, which emits the same error with your setup:
const token = class {
constructor(guild) {
this.guild = guild;
}
};
console.log(new token('1234')); // Works fine.
function foo(token) {
console.log(new token('1234')); // Throws error.
}
foo({ someOtherVar: true });
Solution:
A quick rename of your variable(s) will do. I'd suggest naming your const tokenSchema to avoid conflict (and confusion).

Categories