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);
Related
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');
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:
So, I created a discord.js bot and added the following into index.js:
client.on("guildCreate", guild = {
const logsServerJoin = client.channels.get('757945781352136794');
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
client.channels.cache.get('channel id paste here').send(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
var guildMSG = guild.channels.find('name', 'general');
if (guildMSG) {
guildMSG.send(` Hello there! My original name is \`Bryant\`!\n\ This bot created by **R 1 J 4 N#7686**\n\ For more info
type \`/help\`!\n\ \`Bryant - Official Server:\`
https://discord.gg/UsQFpzy`);
} else {
return;
}
});
// Logs of the bot leaves a server and changed the game of the bot
client.on("guildDelete", guild = {
client.channels.cache.get('757945781352136794').send(`The bot just
left ${guild.name}, Owned by ${guild.owner.user.tag}`);
console.log(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
logsServerLeave.send(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
});
It does not show any error in the terminal. It is supposed to log me where the bot joined and left in the mentioned channel but does not 🤷♂️. Can anyone help me out with this?
If you are getting no console log and no message in the channel / an error telling you that the channel could not be found, the issue is most likely in how you are registering the events, make sure client is an instance of the discord.js Client, below is a minimal working example
const { Client } = require("discord.js")
const client = new Client()
client.on("guildCreate", guild => {
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`)
})
client.login("yourtoken")
If you are trying to get the logs from your bot alert you in your home discord server you can do this multiple ways: Getting the channel from cache, Constructing the channel or Using webhooks. Currently you are trying to fetch the channel from cache. Although a decent solution it can fall down when using sharding later down the line. Personally I prefer webhooks as they are the easiest and most isolated.
Channel from cache
This technique is very similar to the way you were doing it.
const channel = client.channels.cache.get('757945781352136794')
channel.send('An Event occurred')
Just place this code anywhere you want to log something and you'll be fine.
Constructing the channel
const guild = new Discord.Guild(client, { id: '757945781352136794' });
const channel = new Discord.TextChannel(guild, { id: '757945781352136794' });
channel.send('An Event occurred')
This method is similar to fetching the channel from cache except it will be faster as you are constructing your home guild and channel and then sending to it. Mind you will need a client which you can get from message.client
Webhooks
My Favourite method uses webhooks. I recommend you read up on how discord webhooks work in both Discord and Discord.js
You will also need to create a webhook. This is very easy. Go into the channel you want the webhooks to be sent to and then go to integrations and create a new webhook. You can change the name and profile as you wish but copy the url and it should look something like this:
https://discord.com/api/webhooks/757945781352136794/OkMsuUHwdStR90k7hrfEi5*********
The last part of the path is the webhook token and the bit before is the channel ID
I recommend you create a helper function that can be called like this:
sendWebhook('An event occurred');
And then write the function to create and then send to the webhook
function sendWebhook(text) {
const webhook = new Discord.WebhookClient('757945781352136794', 'OkMsuUHwdStR90k7hrfEi5*********');
webhook.send(text);
webhook.destroy();
}
This will not be very dynamic and will be a pain to change the channel but for constant logging ( like guild joins and leaves ) I think it is the best solution
The problem is probably that you don't have "Privileged Gateway Intents" enabled. To turn them on, go to https://discord.com/developers, click on your application, then on "Bot" then scroll down and enable "PRESENCE INTENT" and "SERVER MEMBERS INTENT" and save. It should probably work for you now.
I have the following code which returns me the following error. The error says channel not found, howerver I am following the docs for a private channel to either use the name of the channel or to use the string that is in the url with a G at the beginning. I have given the correct chat write permissions to the bot for the channel and am using the correct bot api generated toekn, I was able to post via webhook before but I want to use the web-api.
This is the docs I am referring to https://api.slack.com/methods/chat.postMessage#channels
const { WebClient } = require('#slack/web-api');
const token = process.env.SLACK_BOT_TOKEN;
const web = new WebClient(token);
const conversationId = 'private-channel-name'; & tried this instead 'GCV2FGELX'
const result = await web.chat.postMessage({
text: 'Hello world!',
channel: conversationId,
});
This is the error response I am getting
{
code: 'slack_webapi_platform_error',
data: {
ok: false,
error: 'channel_not_found',
response_metadata: { scopes: [Array], acceptedScopes: [Array] }
}
}
I'm not quite sure what I am doing wrong, but doing a little digging, even when I try to use the tester get request for groups.list here https://api.slack.com/methods/groups.list/test with a auth token with the correct permissions I just get a empty response back, vs a list of groups.
Not sure here.
I did note that it said this Post into any channel it has access to for what the bot can do how do I know what channel's the bot has access to. I have given it write permissions to my whole orginization?
any help would be appreciated
I too had faced the same issue.
Did you trying adding the BOT/APP to the private channel (You find this under the Channel Details >> More >> Add Apps.
Once you have added your BOT/APP to the channel. Your messages will be getting posted into the channel.
Hope this will solve your issue.
Still ran into this in 2022 with slack bolt.
The error slack_webapi_platform_error with error channel_not_found seems to mean that there is no ACCESS to this channel because app needs to be specifically added to this private channel. Thanks #Anumoy Sutradhar
Here a newer screenshot (not possible to add in comments):
The modal opens when you click on the channel name.
I've been coding a Discord bot using js for a couple days now and most everything has been working fine. I am trying to get my bot to respond to a code word but the command isn't working unless I use my prefix which is !.
I've tried pretty much every variation of the code, but none is working.
Example of the command:
if(message.content.includes('ping')) {
message.reply('Pong');
}
if your code looks like
const Discord = require('discord.js');
const client = new Discord.Client();
let token = "your token here";
client.on('message', message => {
if(message.content.includes('ping')) {
message.reply('Pong');
}
});
client.login(token)
and nothing happens when you send 'ping', then it looks like some technical issue. Otherwise, you have to send the whole code so people can take a look and tell you what is wrong.