How to set Discord.js v13 slash commands permissions? - javascript

I'm following the Discord.js guide to create slash commands for my bot, but I'm stuck at this point here:
https://discordjs.guide/interactions/slash-command-permissions.html#user-permissions
There are two things I can't figure out:
where I'm supposed to write this block of code I linked above,
how I'm supposed to find each command's ID
I'm creating my commands using the SlashCommandBuilder and a deploy-commands.js script as described here:
https://discordjs.guide/creating-your-bot/creating-commands.html#command-deployment-script
and here:
https://discordjs.guide/interactions/registering-slash-commands.html#guild-commands
If you can help me on either one of these two things, that would be great!
Thanks!

I've looked into the codes of the #discordjs/builders and #discordjs/rest and there is no way to set custom permissions with these packages. What you can do is create the slash commands with the Discord.js package. By creating them in the Discord.js package the id of the slash command will be returned in the fullfilled Promise. With this id you can set the permissions for the command. The only problem by doing it in this way is that it can take a while before the slash commands are working again. Here is an example:
const { Client } = require('discord.js');
const client = new Client({intents: ['Your Intents here']});
client.once('ready', () => {
client.application.commands.create({
name: 'your_command',
description: "Your command's description"
}).then(id => {
client.application.commands.set({command: id, permissions: [
id: 'some_user_id',
type: 'USER',
permission: false // Can not use the slash command
]}).catch(console.log);
});
});
client.login('Your token here');
I thought that there is another way to do it, but I'm not pretty sure. If I'm right you can also fetch all the commands after you've refreshed them with the #discordjs/builders and #discordjs/rest packages. Once you've fetched them the Promise will return a Collection once it's got fullfilled. In the Collection will be all the ids of all the slash commands which you can use to set the permissions. So if this theory works, this will be the example:
const { Client } = require('discord.js');
const client = new Client({intents: ['Your Intents here']});
client.once('ready', () => {
// Your refresh code here
client.application.commands.fetch().then(collection => {
collection.forEach(command => {
if(command.name === `The specified command name`){
client.application.commands.permissions.set({command: command.id, permissions: [
{
id: 'some_user_id',
type: 'USER',
permission: false // Can not use the slash command
}
]}).catch(console.log);
}
});
}).catch(console.log);
});
client.login('Your token here');

Related

Delete Button/Component of a specifc message (discord.js)

I am now trying in vain to remove buttons from a bot message. I have created a command for this purpose. When executing it, it should at best remove a specific, the last or at least all buttons that are on a specific message.
I have tried various things, but in all attempts the buttons are not removed.
module.exports = {
category: 'Utilities',
description: 'Delete Buttons',
permissions: ['ADMINISTRATOR'],
callback: async ({ client, message }) => {
const channel = client.channels.cache.get('the channel id')
channel.messages.fetch('the message id').then(msg => msg.edit({components: []}));
console.log(msg)
}
}
When I try to do this, I get the following console error:
TypeError: Cannot read properties of undefined (reading 'messages')
When I try this, I neither get a console log, nor does the bot do anything ...
const { Client, Message } = require("discord.js");
module.exports = {
category: 'Utilities',
description: 'Delete Buttons',
permissions: ['ADMINISTRATOR'],
callback: async ({ client, message }) => {
client.on('ready', async () => {
const channel = client.channels.cache.get('the channel id')
channel.messages.fetch('the message id').then(msg => {
msg.edit({ components: [] })
});
},
)}
}
Maybe one of you knows a solution or an idea. :)
Thanks a lot!
When I try this, I neither get a console log, nor does the bot do anything
The second example does not do anything because you are creating a ready event handler on running your command. Meaning, it's waiting for the bot to once again be "ready", i.e. the state of having logged in to the API as it does on startup. But your bot is already ready, and will not become ready again until the next time it restarts, so nothing will happen.
As for the first example, the error you are getting suggests channel is undefined, meaning either:
A) You have the incorrect channel ID
- OR -
B) The specified channel is no longer in the channel cache
If you are 100% sure the ID is correct, we can assume the issue you are having is the latter (the channel not being in the cache). There are many ways to solve this, but one simple way is to simply fetch the channel similar to how you are trying to fetch the message. Here's an example:
const channel = await client.channels.fetch('the channel id');
const msg = await channel.messages.fetch('the message id');
msg.edit({components: []});
That should fix the issue. If it doesn't, then the issue is much more complicated and not enough information has been provided. Also note that in the above example, I swapped Promise syntax for async/await since you are using an async function anyways; I did this just to make this answer more readable, you can choose whichever format you prefer.

Use Slash Commands in all servers where have a bot without GuildID (Discord.js v12)

I want people to be able to use Slash Commands against my bot on any server, as long as the bot is there. I have further granted the bot application.commands permission. I was referencing this answer, but it seems to require the server's GuildID. Can I allow anyone using Slash Commands to come to my bot without a GuildID? And how do people use it? (I use Commands Handler)
sorry for my bad english
You probably want to use a global slash command. Global meaning that it works across all guilds the bot is in and you don't need to provide any guild id.
client.on("ready", () => {
// Register global slash command
client.api.applications(client.user.id).commands.post({
data: {
name: "hello",
description: "Say 'Hello, World!'"
}
});
// Listen for an interaction (e.g. user typed command)
client.ws.on("INTERACTION_CREATE", (interaction) => {
// Access command properties
const commandId = interaction.data.id;
const commandName = interaction.data.name;
// Reply only to commands with name 'hello'
if (commandName == "hello") {
// Reply to an interaction
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "Hello, World!"
}
}
});
}
});
});
This is how would a user use your command:
And the reply looks like this:

Trying to fetch a guild, using the "get()" method, but client returns undefined, although I have passed in client

It was working fine earlier, but now it's just being weird.
module.exports = {
commands: 'test',
callback: (message, args, client) => {
const guild = client.guilds.cache.get('ID') // 'ID' is a replacement for the actual guild ID I'm using.
console.log(guild) // client returns undefined
}
}
(dumbed down to exclude code that is not relevant.)
It was working before, I changed nothing regarding fetching the guild. It's been the same for weeks now, somehow it just doesn't work.*
UPDATE: Found the issue, originally, callback() accepted three params, I edited it to include text (Everything after the command, e.g. !test test would only pick up test and not !test)
So, in reality, client has been arguments.join() all along.
I figured this out after logging client, something I should have done before I posted it here.
I would suggest changing your code to this.
module.exports = {
name: "test",
description: "test",
execute(message, args, client){
const guild = client.guilds.cache.get('ID') // 'ID' is a replacement for the actual guild ID I'm using.
console.log(guild) // client returns undefined
}
}

New Discord Slash Commands

Recently, discord added support for slash commands for your own application. I read through the documentation for it, and I've tried to search for some videos (however the feature did JUST come out) but I do not understand what I actually have to do to get it working. I am using WebStorm (js, node.js). Has anyone successfully made a slash command, and if so, how?
Documentation
You can use the regular discord.js, by now its v12.5.1.
This is just a sample, but worked for me.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
client.api.applications(client.user.id).guilds(YOUR_GUILD_ID_HERE).commands.post({
data: {
name: "hello",
description: "hello world command"
// possible options here e.g. options: [{...}]
}
});
client.ws.on('INTERACTION_CREATE', async interaction => {
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command === 'hello'){
// here you could do anything. in this sample
// i reply with an api interaction
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "hello world!!!"
}
}
})
}
});
});
client.login(token);
Of course you can have options, see documentation...
IDE won't register the new code...at least my php storm currently does'nt :)
However, its important to give the bot the correct permissions to use this type of command!
So go to Discord.com/developers, select your application, go to OAuth2 and select
application.commands
from the scope section. This should be at the bottom of the middle column. You should select bot as well and under Bot Permissionsyou set some other specific permissions. Then use that new invite link to reinvite the bot.
Without application.commands permission, the command won't work and you will receive some error like Missing Access or some similar.
IMPORTANT THINGS
Use .guilds('11231...').comma to test these commands. When not using this, it takes round about 1h to get active. Using it will activate it immediately.
Give the bot the correct permission. application.commands
Hi I don't usually work with discord.js but I was able to find some good documentation on this. You should be able to do it like this with "client" defined.
const interactions = require("discord-slash-commands-client");
const client = new interactions.Client(
"you unique bot token",
"your bots user id"
);
If the client is defined as shown, then a /command should work if defined like this.
// will create a new command and log its data.
//If a command with this name already exist will that be overwritten.
client.createCommand({
name: "your command name",
description: "description for this command",
})
.catch(console.error)
.then(console.log);

nodejs-dialogflow library returning TypeError: dialogflow.SessionsClient is not a constructor

I am trying to make a script that takes input from the user, runs it through Dialogflow, then returns it back to the user. The platform I am taking input from only supports Node.js. I am hosting the bot through glitch.com, but I don't think that's what's causing the issue. I wanted to check on here before I submit a bug report onto the GitHub repo.
var bot = 'the platform i use to accept inputs and send outputs'
bot.on("message", async message => {
console.log(message.content); // Log chat to console for debugging/testing
if (message.content.indexOf(config.prefix) === 0) { // Message starts with your prefix
let msg = message.content.slice(config.prefix.length); // slice of the prefix on the message
let args = msg.split(" "); // break the message into part by spaces
let cmd = args[0].toLowerCase(); // set the first word as the command in lowercase just in case
args.shift(); // delete the first word from the args
// You can find your project ID in your Dialogflow agent settings
const projectId = process.env.PROJECT_ID; //https://dialogflow.com/docs/agents#settings
const sessionId = 'quickstart-session-id';
var query = msg;
const languageCode = 'en-US';
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: languageCode,
},
},
};
// Send request and log result
sessionClient
.detectIntent(request)
.then(responses => {
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
})
.catch(err => {
console.error('ERROR:', err);
});
}
return;
});
That is the relevant part of the code. For those wondering, the process.env.PROJECT_ID is something glitch.com uses for anything private. Because I don't want random people getting their hands on my project id, I hide it in there and glitch hides it from anyone I don't explicitly invite.
Every time I execute this and try to query the bot, it returns an error Uncaught Promise Error: TypeError: dialogflow.SessionsClient is not a constructor.
If someone can direct me to what I'm missing, or what the problem is, that would be great!
As per #google-cloud/dialogflow - npm
IMPORTANT NOTE
Version 2.0.0 renames dialogflow to #google-cloud/dialogflow on npm, along with introducing TypeScript types.
So to update the dialogflow to use latest version, first uninstall dialogflow and then install with following command:
npm uninstall dialogflow
npm i #google-cloud/dialogflow
Also, if you were using older version 1.2.0 of dialogflow before then in code, make following changes as per their sample or refer the sample from above link (in require and to get the sessionPath):
const dialogflow = require('#google-cloud/dialogflow');
const sessionPath = sessionClient.projectAgentSessionPath(
projectId,
sessionId
);
It worked fine for me after doing this without any errors.
I figured it out. After many many refreshes, I decided to look at the npm documentation for it. Turns out some idiot listed the earliest version as 4.0.3, and the latest version as 0.7.0. I needed to explicitly tell it to use version 0.7.0 in order for it to work. Thank goodness!
Mine worked by reinstalling the dialogflow package
npm uninstall dialogflow
npm install dialogflow --save
put the code inside try and catch block. In my case by doing this, this error was removed.

Categories

Resources