I am getting an error when I am trying to run:
(node:9164) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'applications' of undefined
Here is my code:
const discord = require('discord.js');
const client = new discord.Client();
const guildId = '820368493017825333';
client.on('ready', async () => {
console.log('ready');
const commands = await client.api.
applications(client.user.id)
.guilds(guildId)
.commands.get();
console.log(commands);
});
client.login(require(`./config.json`).Token);
Issues With the Accepted Answer
The accepted answer is incorrect in several ways. I'll walk through the inaccuracies in that answer and highlight the more likely causes of this problem, for the sake of anyone that may stumble upon this question in the future (and would've been misled by the accepted answer into believing that Slash Commands cannot be implemented in discord.js).
Well, the answer is pretty simple here. According to Discord.js docs, Class Client doesn't have api property. That's why you have the undefined error.
Incorrect. The Client class does have an api property. Or rather, it inherits the api property from the BaseClient class that it extends. This can be found in the source code of BaseClient. It is true that this is not documented in the discord.js docs. That is intentional, as the api property is intended to be a private property, more for discord.js' own use than for general use. You may notice in the source code that the property is annotated with #private, which usually indicates that it will not appear in the docs. There are many such private properties and methods that exist in discord.js classes, which are undocumented but are usable in your own code.
It seems like the tutorial that you are looking at is a bit outdated, or probably the tutor adds this property manually because Discord.js have relevant classes, like Application and ClientApplication but I still don't see an api property there as well.
The tutorial that the OP was going off of was actually more up-to-date than the tutorials posted and used by the accepted answer. The Application and ClientApplication classes are not at all relevant, as neither can access Slash Commands. Nor did hundreds of different tutorials each implement their own api property that all work in exactly the same way; they were all using the api property included in the latest versions of discord.js.
If you want to implement commands to your Discord bot with slash support, just add the following code, after ready stage.
The accepted answer misunderstood what 'Slash Commands' are, and provided code simply for creating a command with a slash for a prefix. That is not what the Slash Command system is. Slash Commands allow you to do things such as documenting, autocompleting, and validating commands and command arguments that users are typing in, in real-time while they are entering their input.
Not it shouldn't. Actually, the Discord.js lib is updated more often, the [YouTube] creators do it with their videos. I have already placed in my answer, a relevant guide made by the Discord.js community.
Yes it should. Hundreds of tutorials used the same code as each other, containing the api property, in instructing developers on how to work with Slash Commands in unmodified discord.js. I am not sure what exactly was meant by this comment.
If you look at the actual source code of discord.js, you'll find that the latest versions use the client's api property several times internally, usually in methods that directly query the Discord API for information (such as .fetch() methods). If the api property is undefined and you are using the latest version of discord.js, then much of your bot would not be working properly. So the latest client class not having an api property is not the main issue, which leads us to what the main issue really is.
So What Is the Real Issue?
There truly isn't enough context provided in the question to know for sure what exactly was causing the issue in the question. However, we can narrow the cause down to a few potential suspects, especially given the information aforementioned. Double check these to ensure they are not causing your problem:
Discord.js version. The api property does not exist for versions older than v12. Make sure you are using the latest version of discord.js. This is most likely the cause of the issue.
Missing access. You need to give your bot the application.commands scope when generating its invite link, otherwise you cannot interact with or create Slash Commands. This shouldn't really cause the api property to be undefined and should give you a different error, but it's worth double-checking.
If working with Slash Commands in simple discord.js is still not working for you even after double-checking both of these potential issues, you may want to consider an alternate (and somewhat simpler) approach to implementing Slash Commands: the discord-slash-commands-client module.
You would initialize this module like so:
const interactions = require("discord-slash-commands-client");
const iclient = new interactions.Client(
"you unique bot token",
"your bots user id"
);
Then to get a list of all existing Slash Commands, as the code in this question is attempting to do, all you would need to do with this module is:
let commands = await iclient.getCommands();
A single, clean line. As simple as it gets. The only downside to this alternate approach is that this module may not stay up-to-date as reliably as discord.js itself does. However, it would certainly be helpful if you are not able to figure out how to get Slash Commands working in discord.js itself.
If you need more help on this or want to see a more complete implementation of either approach, this question has several good, working examples on how to get Slash Commands code working properly on your bot.
This answer is a outdated!
When it was accepted Discord haven't introduced truly /slash commands. So use the answer below, if you want to integrate or migrate to newest version of Discord.js
Well, the answer is pretty simple here. According to Discord.js docs, Class Client doesn't have api property. That's why you have the undefined error.
It seems like the tutorial that you are looking at is a bit outdated, or probably the tutor adds this property manually because Discord.js have relevant classes, like Application and ClientApplication but I still don't see an api property there as well.
If you are looking for a good guide, I might recommend you this one from the official Discord recommendation page.
If you want to implement commands to your Discord bot with slash support, just add the following code, after ready stage.
const prefix = '/'
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.channel.send('Pong.');
}
})
Related
Here’s the situation:
In my server I have a bot (not mine) that replies to specific user actions with a message containing an embed that has the word “Done!” in the description. I want to set it up so that once this bot sends the “Done!” message the user it replied to receives a role.
Today being the first day I’ve ever used javascript means I’m not surprised I’ve encountered an error, however I simply could not figure out how to fix it. I tried working around the error by attempting to achieve my intended result by different methods, but I cannot find an actual alternative so I’ve ended up back at the error.
The code that I’m experiencing the error with is this:
client.on('messageCreate', (message) => {
let role = message.guild.roles.cache.find(r => r.id === "1001628984829816952");
let member = message.mentions.repliedUser();
let done = "done!"
if (done(w => message.embeds.description.toLowerCase().includes(w))) {
member.roles.add(role);
}
});
and the error I'm receiving is this:
let member = message.mentions.repliedUser();
^
TypeError: message.mentions.repliedUser is not a function
I'm a bit confused as I was sure .repliedUser is valid, although this may be my absolute inexperience with javascript shining through.
On a side note, I believe I have the necessary intents enabled:
import { Client, GatewayIntentBits } from 'discord.js';
import dotenv from 'dotenv'
dotenv.config()
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
so those shouldn't be a problem.
What I've tried by means of my own intuitive bumbling is replacing message.mentions.repliedUser() with message.mentions.repliedUser.get() since I've seen .get used at the end a bit like that and it sounds about right (I'm laughing at my own explanation here, please bear with me...), however I receive a different error with that in place:
let member = message.mentions.repliedUser.get();
^
TypeError: Cannot read properties of null (reading 'get')
I'm not surprised by this result, though, (even if I don't fully understand what it's trying to tell me...) since .repliedUser isn't recognised anyways.
I'm not really sure where to go from here, especially since there seems to be no mention of .repliedUser anywhere on the internet except for the discord.js docs, and also because much of the general help for discord.js is still aimed at v13, whereas I'm running v14, and the two are not compatible.
Any and all help is much appreciated, and I'm sorry if this question is stupid and the answer to it is incredibly rudimentary, which I'm guessing it is. I also hope that my code is readable; it seems to mostly work, except for the error, but it is also mostly patchwork so it could just be some nonsense that's pretending to work.
(At least this has convinced me to get into javascript properly, even if only for my own peace of mind.)
Looking at the documentation, message.mentions.repliedUser is of type ?User. You are expecting it to be of type (...) => ?User, which it isn't.
Simple fix, just replace .repliecUser() with .repliedUser.
If I'm trying to figure out how to get the id of a dmChannel, with only the user's object so I can bulk delete in user's dms, how would I do this? The code I have so far is:
let dm = client.users.get('123481923481234').createDM()
the error I got was:
TypeError: Cannot read property 'createDM' of undefined
I also tried getting the user from a guild members list, here's the code:
let dms = client.guilds.get('783871449466142750').then(guild=>{
guild.members.get('432325763753050122').createDM().channel.id
})
This got the error:
TypeError: client.guilds.get(...).then is not a function
Anyone know whats wrong? Any help would be appreciated!
Did you try looking at the discord.js docs? That's the website where discord.js documents exactly how to use every method and property available in discord.js, and you would be able to solve every issue you experienced in this question in seconds by simply looking at the documentation. The docs, being the place that tells you how to use everything in discord.js, should've been the first place you looked for answers; StackOverflow is more of a last resort situation that you come to when you are completely stuck, and this is certainly not one of those situations.
In the first issue you are having, the error tells you everything: Cannot read property 'createDM' of undefined. What does that tell us? It tells us that client.users.get('123481923481234') is undefined, or in other words, the user with that ID cannot be found in your bot's cache (client.users represents the bot's user cache). Either you used an incorrect ID, or the bot's cache simply hasn't been updated to include that specific user. If you want to get that user even if they are not in your bot's cache, you can directly ask the Discord API for that information using client.fetchUser(). This method returns a Promise, so you'll want to use .then() to access its asynchronous data. (.createDM() is also a Promise so you'll need a .then() to access the created DMChannel as well). Here's what it should look like:
client.fetchUser('123481923481234', true).then(user => {
user.createDM().then(dmchannel => {
//Now do whatever you want with the ID
var channelID = dmchannel.id;
});
})
As for the second thing you tried, that's just completely wrong. I don't know how you created that code, but you definitely didn't look at the docs to see if you were doing it right; it honestly looks like you just guessed without checking how it actually works. First of all client.guilds.get() does not return a Promise, so you don't use .then() on it. You should already know that, since you didn't use .then() on the .get() in the first thing you tried. Second, as previously mentioned, .createDM() does return a Promise and therefore does require a .then() which you did not use in your attempt. You ended up doing the opposite of what you needed to do in each of the two above parts of this second attempt. Third, the Promise of .createDM() provides you with a DMChannel object and not a DM object, so you're attempting to do DMChannel.channel.id when you should just be doing DMChannel.id. Fixing all of that might get this second attempt to work, but it might still not work due to the reason your first attempt did not work. If that's the case, you would just need to switch all of your uses of .get() in this second attempt to its fetching equivalent, which you can find easily on the docs. For the sake of a simple, readable answer, I am not going to use the fetching equivalents in this second answer. So here's how your second attempt should look:
var guild = client.guilds.get('783871449466142750');
guild.members.get('432325763753050122').createDM().then(dmchannel => {
//Now do whatever you want with the ID
var channelID = dmchannel.id;
});
Here are the links to the pages in the documentation that explain how to use the methods and objects in these two answers. Please go to these pages and look at how the methods work, and refer to the documentation in the future when you're not sure how something works, when you want to figure out how to do something, or when something you've developed in discord.js is not working properly. Most of the methods on the docs come with provided, understandable examples along with documentation of all available options and parameters. Only ask a question here if it cannot be answered by the docs.
https://discord.js.org/#/docs/main/v11/class/Client?scrollTo=fetchUser
https://discord.js.org/#/docs/main/v11/class/User?scrollTo=createDM
https://discord.js.org/#/docs/main/v11/class/DMChannel
https://discord.js.org/#/docs/collection/master/class/Collection?scrollTo=get
I'm attempting to use a cursor:
const cursor = Thing.find({}).cursor();
cursor.next().then((a,b) => { console.log(a); console.log(b); })
But this never resolves; it just sits there. There doesn't seem to be a cursor.exec() or anything like that. cursor.close() even throws TypeError: Cannot read property 'close' of null.
All the documentation I can find ignores this and just goes about its example, thus implying I don't need it. But I quite obviously do, as it doesn't actually load any documents from Mongo.
This is on a legacy project and I'm unable to change the version of Mongoose. Node is 8.15.0, MongoDB is 3.2, and both are in a similar boat.
Ok, look, I'm going to own up to my stupidity here and admit that I hadn't actually connected to mongo before attempting to load the data. I'm also going to leave this question up as a combination of reference and penance.
Though to be fair I have no idea why mongoose wouldn't tell me it's not connected instead of blocking on a nonexistent connection. But I still should have known.
Hoping someone can shed some light on using Cognito with plain JavaScript. No npm, no webpack, just plain JavaScript. I found a post that had a great example including the required AWS JavaScript libraries. I worked from this example until I ran into the problem of sign out not working. I thought perhaps the libraries in the example were out of date so I went looking for the latest. This is where things got confusing. In the example I had the following JavaScript libraries - amazon-cognito-identity.min.js, aws-cognito-sdk.min.js, and aws-sdk.min.js. I assume that aws-cognito-sdk must no longer exist? I updated the other two and see that there is an amazon-cognito-auth library. Do I need that? Anyhow with those three libraries the existing code no longer functions. I end up with errors like "AWSCognito is undefined" etc.
Hoping someone can point me in the right direction and show me where the downloads, documentation, etc for using Cognito in plain JavaScript are
Find hereunder a template I created for myself to work from. It is in "plain javascript" and in an angularjs app.
My template: https://github.com/PouncingPoodle/aws-cognito-angularjs/tree/master
based on: https://github.com/takanorig/aws-cognito-angularjs
Always make sure that you use the correct versions of scripts and the correlating apiVersion when you call a Lambda function for example
There might be bad practice involved but as far as I could research it should be all fine.
You can perform the logout using below code snippet. I haven't faced such strange errors while using this function.
var poolData = {
UserPoolId: '...', // Your user pool id here
ClientId: '...', // Your client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: 'username',
Pool: userPool,
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.signOut();
if you want to make the user logout from all the devices that he has got logged in from, then you can replace the last line of previous code with below code line.
cognitoUser.globalSignOut(callback);
You can refer below article to get a better understanding about the usage of amazon-cognito-identity-js package.
https://medium.com/#sankharathnayaka/aws-cognito-authentication-without-using-amplify-8d0e3af997c2
Hi recently I have to implement a git API for a node module, so we can have version control through programmatic interface. I came upon this post to find some good modules that I can use.
However, after playing around with some of them, I realized that none of them provide the feature of querying the commit history of a single file (like calling 'git log --follow '). I would like to extend that feature into my module but since I have no experience before, does anyone know where I should start?
The libraries you mentioned should be a good starting point. Take node-git's lib/git.js file for example. There you can find the following lines:
// Call the native git binary
Git.prototype.call_git = function(prefix, command, postfix, options, args, callback) {
// ...
This is a good starting point to understand how the author maps Node functions on system calls and and allows the callback to work with the output.
I would start a fork of the project. Look for the log function in the same file, which starts like
Git.prototype.log = function(commit, path, options, callback) {
Copy the function, give it a proper name and try to adopt it to meet your needs.
If you succeed and like to help, you could start a pull request on GitHub to help the author and add the functionallity to the official project.
I would do it this way. I hope this helps.