I am using discord.js v13. I have successfully created a bot with scopes bot and application.commands and successfully add it to a channel on my server. Now I am following the tutorial for registering slash commands. I created a file deploy-commands.js with the following content:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
Then I run command node deploy-commands.js and I get error:
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (/home/evalenzuela/apps/discord-aurasix/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.js:198:23)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (/home/evalenzuela/apps/discord-aurasix/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.js:99:20) {
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'put',
url: 'https://discord.com/api/v9/applications/901217590259617813/guilds/901235476399280138/commands'
}
I have reviewed a lot of info on the internet but could not find the solution. I have triple checked the clientId, guildId and application token.
Adding on to Pedro's comment,
From Trying to register commands: DiscordAPIError[50001]: Missing Access:
"Have you made sure that the 'applications.commands' scope is checked in the scopes section of the OAuth2 settings for your bot in the discord developer portal?"
You mention you remade the application and bot but did not verify you correctly set the application.commands scope permission. This is likely your issue.
Related
I started programming a discord bot with nodejs on replete and I use code similar to the example in the official site of discord.js. Bot registered the command and it appears in discord but when I run it doesn't work.
The application did not respond
This is the code I use to make the command:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('hi')
.setDescription('say hi'),
async execute(interaction) {
await interaction.reply('hi');
},
};
The index code:
const { Client, Events, GatewayIntentBits } = require('discord.js');
const token = process.env['TOKEN']
const clientId = process.env['APID']
const guildId = process.env['SID']
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
//
const { REST, Routes } = require('discord.js');
/*const { clientId, guildId, token } = require('./config.json');*/
const fs = require('node:fs');
const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(token);
// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
//
client.on("ready", () => {
console.log("Bot is online!");
})
client.login(process.env['TOKEN']);
Project Structure
Command Registered
Bot Config
Bot Scopes
Bot Permissions
When I try to run the command on the powershell termianl (node .\index.js\) I get the same error every time. I changed the token multiple times but still got the same error. I run the command on the right root directory, so I don't know what to do.
Code:
import { config } from 'dotenv';
import { Client, GatewayIntentBits, Routes } from 'discord.js';
import { REST } from '#discordjs/rest';
config();
const TOKEN = process.env.BOT_TOKEN_CLOUD;
const CLIENT_ID = process.env.CLIENT_ID;
const GUILD_ID = process.env.GUILD_ID;
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
]
});
const rest = new REST({ version: '10' }).setToken('TOKEN');
client.on('ready', () => {console.log(`${client.user.tag} has logged in!`);});
async function main() {
const commands = [
{
name: 'testcommand',
description: 'test command'
},
];
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), {
body: commands,
});
client.login(TOKEN);
} catch (err) {
console.log(err);
}
}
main();
Error:
DiscordAPIError[0]: 401: Unauthorized
at SequentialHandler.runRequest (file:///C:/Users/Name/Documents/djs-v14/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.mjs:283:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (file:///C:/Users/Name/Documents/djs-v14/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.mjs:95:14)
at async REST.request (file:///C:/Users/Name/Documents/djs-v14/node_modules/#discordjs/rest/dist/lib/REST.mjs:48:22)
at async main (file:///C:/Users/Name/Documents/djs-v14/index.js:32:9) {
rawError: { message: '401: Unauthorized', code: 0 },
code: 0,
status: 401,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/CLIENT_ID/guilds/948742790421053482/commands',
requestBody: { files: undefined, json: [ [Object] ] }
}
You need to use the specific token for your bot instead of 'TOKEN' string
const rest = new REST({ version: '10' }).setToken('TOKEN');
here, .setToken() should be like .setToken(TOKEN)
Almost certain you forgot the ApplicationCommands scope(remember bot as well) when adding a bot to the server. Ensure you add that scope in the developer portal. Another possible reason is your client ID not matching the token.
when I try to run the code it gives me the error "TypeError [ClientMissingIntents]: Valid intents must be provided for the Client.". I tried using node . and node main.js to run it. I followed a yt tutorial and it looks like it should work.
Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'TOKEN HERE'
client.once('ready', () => {
console.log('GamrBot1.0 is online');
});
client.login(token);
From discord.js v13, you need Intents when you declare your client. You can add them by doing this:
const { Client, Intents } = require('discord.js')
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
// ...
]
})
For more information, I'd suggest you go here => Gateway Intents
I've been following this tutorial with this library, but the code snippets provided are producing errors. I have registered the app with Azure and followed the instructions, but when I run the code, it says SyntaxError: await is only valid in async functions and the top level bodies of modules at /script.js:74:20
Here's a relevant snippet of code, but if you have Replit, I would really appreciate it if you could collaborate with me on my Repl instead.
Replit link: https://replit.com/join/rgqcqfcohh-5pengoo
Code:
const msal = require('#azure/msal-node');
// Create msal application object
const cca = new msal.ConfidentialClientApplication(config);
const REDIRECT_URI = "http://localhost:3000/redirect";
const config = {
auth: {
clientId: "ebcb2e8c-4675-411f-a76e-25aafe0c026d",
authority: "https://login.microsoftonline.com/98ca2106-858a-413a-b7d5-31301dcf9869/",
// I wasn't sure if this meant the key value or the secret ID
clientSecret: "ee10b5ce-f9c4-460a-a402-064030841f86"
},
system: {
loggerOptions: {
loggerCallback(loglevel, message, containsPii) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose,
}
}
};
// 1st leg of auth code flow: acquire a code
app.get('/', (req, res) => {
const authCodeUrlParameters = {
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
// get url to sign user in and consent to scopes needed for application
pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
res.redirect(response);
}).catch((error) => console.log(JSON.stringify(error)));
});
// 2nd leg of auth code flow: exchange code for token
app.get('/redirect', (req, res) => {
const tokenRequest = {
code: req.query.code,
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
pca.acquireTokenByCode(tokenRequest).then((response) => {
console.log("\nResponse: \n:", response);
res.sendStatus(200);
}).catch((error) => {
console.log(error);
res.status(500).send(error);
});
});
try {
let userDetails = await client.api("/me").get();
console.log(userDetails);
} catch (error) {
throw error;
}
MohammedMehtabSiddiqueMINDTREELIMI-9821 on the Microsoft Docs informed me that...
"You can use "await" only inside a function which is "async".
Here you can try remove 'await' from the code and try to run it"
and it worked!
I am trying to setup slack bot and facing below issue.
Error: Slack request signing verification failed
I am exactly following this YT tutorial, even tried git clone his repo to try out but still facing same error.
I even tried to search other slack bot setup tutorial and come back to same issue.
Please help if any of you have experience in fixing this.
Followed tutorial: https://www.youtube.com/watch?v=Awuh2I6iFb0
-> Environment: NodeJS
-> app.js file
require('dotenv').config();
const { WebClient } = require('#slack/web-api');
const { createEventAdapter } = require('#slack/events-api');
const slackSigningSecret = process.env.SLACK_SIGNING_SECRET;
const slackToken = process.env.SLACK_TOKEN;
const port = process.env.SLACK_PORT || 3000;
const slackEvents = createEventAdapter(slackSigningSecret);
const slackClient = new WebClient(slackToken);
slackEvents.on('app_mention', (event) => {
console.log(`Got message from user ${event.user}: ${event.text}`);
(async () => {
try {
await slackClient.chat.postMessage({ channel: event.channel, text: `Hello <#${event.user}>! :tada:` })
} catch (error) {
console.log(error.data)
}
})();
});
slackEvents.on('error', console.error);
slackEvents.start(port).then(() => {
console.log(`Server started on port ${port}`)
});
Full error code:
Error: Slack request signing verification failed
at Server. (/Users/byao/CD/playground/slackcicd/node_modules/#slack/events-api/dist/http-handler.js:148:39)
at Server.emit (events.js:375:28)
at parserOnIncoming (_http_server.js:897:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17) {
code: 'SLACKHTTPHANDLER_REQUEST_SIGNATURE_VERIFICATION_FAILURE'
}
Very appreciated and full of thank you if any of you are willing to help!