I'm building a bot with Discord.js.
I wrote below code, and persists same error.
How can I fix or avoid that error?
require("dotenv").config();
const fs = require("fs");
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];
const commandfiles = fs.readdirSync("./src/Commands").filter(file => file.endsWith(".js"));
commandfiles.forEach(commandfile => {
const command = require(`./Commands/${commandfile}`);
commands.push(command.data.toJSON());
});
const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);
restClient.put(Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, process.env.DISCORD_GUILD_ID),
{body: commands})
.then(()=> console.log("Successfully registered commands"))
.catch(console.error);
Error message and stacktrace:
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (C:\Users\kitel\vscode workspace\DiscordBot\node_modules\#discordjs\rest\dist\index.js:708:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\kitel\vscode workspace\DiscordBot\node_modules\#discordjs\rest\dist\index.js:511:14) {
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'put',
url: 'https://discord.com/api/v9/applications/932218396219674624/guilds/932240564102000710/commands',
requestBody: { files: undefined, json: [ [Object] ] }
{ rawError: { message: 'Missing Access', code: 50001 }
As you mentioned, it's missing access i think. Enable your intents on web and grant your bot application commands privilege.
Related
So I've been trying to integrate Next Auth to a full stack NextJS web app. I've handled logins with JWT and am storing sessions on the browser due to using a Credentials login type with Next Auth. I have managed to get the login to work, however I am now trying to protect my API route to retrieve the user's basic data from the MongoDB. The relevant files are below, however, I am running into an error with unstable_getServerSession() (at least according to the trace) that says that options.providers is not iterable. I cannot understand this as I have created it as an array...
Any help would be greatly appreciated!
[...nextauth].js
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import clientPromise from '../../../lib/mongodb'
import { compare } from 'bcryptjs'
export default NextAuth({
session: {
strategy: "jwt"
},
providers: [
CredentialsProvider({
name: "Email and Password",
credentials: {
email: { label: "Email", type: "email", placeholder: "Email Address" },
password: { label: "Password", type: "password", placeholder: "Password" }
},
async authorize(credentials, req) {
const db = (await clientPromise).db();
const employees = db.collection('employees');
const res = await employees.findOne({
email: credentials.email
});
if (!res) {
throw new Error('No user found with those details');
}
const checkPassword = await compare(credentials.password, res.password);
if (!checkPassword) {
throw new Error('Incorrect username or password');
}
return res;
}
}),
],
pages: {
signIn: "/signin"
}
})
getEmployeeData.js
import { unstable_getServerSession } from "next-auth/next"
import authOptions from "../auth/[...nextauth]"
import clientPromise from "../../../lib/mongodb";
export default async function getEmployeeData(req, res) {
const session = await unstable_getServerSession(req, res, authOptions);
if (session) {
res.status(200).json({ success: "You got it!" });
}
}
Error Message
error - TypeError: options.providers is not iterable
at assertConfig (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/core/lib/assert.js:68:34)
at NextAuthHandler (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/core/index.js:70:52)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async unstable_getServerSession (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/next/index.js:79:19)
at async getEmployeeData (webpack-internal:///(api)/./pages/api/employees/getEmployeeData.js:13:21)
at async Object.apiResolver (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/api-utils/node.js:366:9)
at async DevServer.runApi (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/next-server.js:481:9)
at async Object.fn (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/next-server.js:735:37)
at async Router.execute (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/router.js:247:36)
at async DevServer.run (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/base-server.js:347:29) {
page: '/api/employees/getEmployeeData'
}
error - TypeError: options.providers is not iterable
at assertConfig (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/core/lib/assert.js:68:34)
at NextAuthHandler (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/core/index.js:70:52)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async unstable_getServerSession (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/next/index.js:79:19)
at async getEmployeeData (webpack-internal:///(api)/./pages/api/employees/getEmployeeData.js:13:21)
at async Object.apiResolver (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/api-utils/node.js:366:9)
at async DevServer.runApi (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/next-server.js:481:9)
at async Object.fn (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/next-server.js:735:37)
at async Router.execute (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/router.js:247:36)
at async DevServer.run (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/base-server.js:347:29) {
page: '/api/employees/getEmployeeData'
}
error - TypeError: options.providers is not iterable
at assertConfig (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/core/lib/assert.js:68:34)
at NextAuthHandler (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/core/index.js:70:52)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async unstable_getServerSession (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next-auth/next/index.js:79:19)
at async getEmployeeData (webpack-internal:///(api)/./pages/api/employees/getEmployeeData.js:13:21)
at async Object.apiResolver (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/api-utils/node.js:366:9)
at async DevServer.runApi (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/next-server.js:481:9)
at async Object.fn (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/next-server.js:735:37)
at async Router.execute (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/router.js:247:36)
at async DevServer.run (/Users/MYNAME/Programming/Work/Dan/HR-System/fullstack/node_modules/next/dist/server/base-server.js:347:29) {
page: '/api/employees/getEmployeeData'
I know, same error repeated three times, don't know why that happens either...
You have to separately export the authOptions and apply them to the export default NextAuth(authOptions) as an argument.
Here is the solution for your code:
export const authOptions = {
session: {
strategy: "jwt"
},
providers: [
CredentialsProvider({
name: "Email and Password",
credentials: {
email: { label: "Email", type: "email", placeholder: "Email Address" },
password: { label: "Password", type: "password", placeholder: "Password" }
},
async authorize(credentials, req) {
const db = (await clientPromise).db();
const employees = db.collection('employees');
const res = await employees.findOne({
email: credentials.email
});
if (!res) {
throw new Error('No user found with those details');
}
const checkPassword = await compare(credentials.password, res.password);
if (!checkPassword) {
throw new Error('Incorrect username or password');
}
return res;
}
}),
],
pages: {
signIn: "/signin"
}
}
export default NextAuth(authOptions)
When I try to execute a slash command it crashes with an 404 error.
I already tried to delete all commands but it didn't work.
Here's the code I'm using
const commands = [
{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Reloading slash commands');
await rest.put(
Routes.applicationGuildCommands("client_id", "server_id"),
{ body: commands },
);
console.log("Reloaded slash commands");
} catch (error) {
console.error(error);
}
})();
Here's the error
node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Unknown application command
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildApplicationCommandManager.fetch (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:93:23)
at async Client.<anonymous> (/home/container/index.js:101:17) {
method: 'get',
path: '/applications/client_id/guilds/guild_id/commands/command_id',
code: 10063,
httpStatus: 404,
requestData: { json: undefined, files: [] }
}
if you want to register your Slash Commands with the moderately recent Discord.js Rest library you have to use the builder library as well. You are also not passing JSON to the body you are passing an Array of Objects.
From Discord.js Guide on Making Slash Commands
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
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);
I recently started working on discord ban bot with 3 main features:
Export IDs of all banned users in current Server/Guild.
Import IDs of banned users into current guild
Transfer ban list from current server to target server. (Under development)
None of the slash commands are working even though the logic is seemingly correct.
I'm following the discordjs guide & managed to make a Time Tag generator bot & this is my 2nd bot project. I admit I'm not familier with Javascript but the guide is very helpful nonetheless
Here is the export-ban-list code:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
function new_paste(serverName, results) {
const outputFile = `${serverName}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return data;
}
else {
return 'There was some unexpected error.';
}
});
}
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
const fe = new_paste(interaction.serverName, results);
return interaction.editReply(fe);
},
};
This command basically calculates the number of users banned, makes an array & exports it to pastebin.
The issue is, the bot code reaches till calculation part, but when it comes to making the list, console throws me errors:
Found 13 bans. Exporting...
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async InteractionWebhook.editMessage (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\Webhook.js:311:15)
at async CommandInteraction.editReply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:137:21)
at async Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:41:3) {
method: 'patch',
path: '/webhooks/897454611370213436/aW50ZXJhY3Rpb246ODk4ODkyNzI0NTcxMzczNjA5OmtPeGtqelQ5eUFhMnNqVzc1Q3BpMWtQZUZRdVhveGQxaHFheFJCdVFoUWNxNUk5TVpGbThEQjdWcDdyaHZyaUJPeUpsRWFlbUp0WnVLYjB5V0RtYmJCSmlNU2wwUVlka1hYMHg0bHRJbzlHelVwRmJ6VUpRaXF2YktaVDN1ZlVp/messages/#original',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89
if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
^
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
at CommandInteraction.reply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89:46)
at Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:45:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
Thanks to Jim I used the console.log() to check what was going on.
And indeed the data from function inside new_paste() wasn't being returned to fe.
(I had messed up the return scopes basically)
Here is the final code after fixes & scope resolutions
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
console.log(results);
const outputFile = `${interaction.guild.name}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return interaction.editReply(data);
}
else {
return interaction.editReply('There was some unexpected error.');
}
});
},
};
And finally I get the proper pastebin url as output.
Code hosted here
I think your npm package better-pastebin has an error. I am not familiar with that npm package, so I can’t determine whether it has an error for you, but I think if you change the npm package, the error will not appear.
I'm getting a missing access error when trying to add slash commands to my guild. I already kicked the bot, deleted the bot and changed the intents.
My intent number is 32265
This is my code for adding it the commands:
const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
const arrayOfSlashCommands = [];
commandFiles.map((value) => {
const file = require(value);
const splitted = value.split("/");
const directory = splitted[splitted.length - 2];
if (file.name) {
const properties = { directory, ...file };
client.commands.set(file.name, properties);
arrayOfSlashCommands.push(file);
}
});
client.on("ready", () => {
client.guilds.cache.get("783606158669381663").commands.set(arrayOfSlashCommands);
});
But I'm getting this error:
E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async GuildApplicationCommandManager.set (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\managers\ApplicationCommandManager.js:146:18) {
method: 'put',
path: '/applications/893555323200237599/guilds/783606158669381663/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: [
{
name: 'search',
description: 'Search',
type: undefined,
options: undefined,
default_permission: undefined
}
],
files: []
}
}
The solution was to invite the bot using:
So basically, I am trying to fetch embed from 1 channel and then send it to another channel but it's giving an error saying something about empty message.
Full Error:
Received 1 messages
/home/bot/node_modules/discord.js/src/rest/RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/bot/node_modules/discord.js/src/rest/RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/bot/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async TextChannel.send (/home/bot/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:171:15) {
method: 'post',
path: '/channels/874619472902774845/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
Here is my bot script:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });;
client.on('ready', () => {
const channel1 = client.channels.cache.get("791100523246911499");
const logchannel1 = client.channels.cache.get("874619472902774845");
channel1.messages.fetch({ limit: 1 }).then(messages => {
console.log(`Received ${messages.size} messages`);
//Iterate through the messages here with the variable "messages".
messages.forEach(message => {
logchannel1.send(message.embeds);
})
})
I hope someone knowledgeable in discord.js can help me out with this dilemma.
Thanks for reading
Regards, Infamous.
This part is incorrect
messages.forEach(message => {
logchannel1.send(message.embeds);
})
You have to specify they are embeds
messages.forEach(message => {
logchannel1.send('optional content', {embeds: [...message.embeds]});
})