Discord JS - DiscordAPIError: Missing Access - javascript

So i follow worn off keys tutorial to discord bot and i don't know what the problem is, here is the error
/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async GuildApplicationCommandManager.create (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:117:18) {
method: 'post',
path: '/applications/901999677011005472/guilds/905266476573950023/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: {
name: 'ping',
description: 'Bot uptime/latency checker.',
type: undefined,
options: undefined,
default_permission: undefined
},
files: []
}
}
I also try looking at my code but I didn't see something wrong.
This is my code, I really think something is wrong in the code.
const DiscordJS = require('discord.js')
const { Intents } = require('discord.js')
const dotenv = require('dotenv')
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
client.on('ready', () => {
console.log("The bot is online")
// Carlos: 883425101389914152
const guildId = '905266476573950023'
const guild = client.guilds.cache.get(guildId)
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application.commands
}
commands.create({
name: 'ping',
description: 'Bot uptime/latency checker.',
})
commands.create({
name: 'add',
description: 'Adds two numbers given by user.',
options: [
{
name: 'number1',
description: 'The first number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
{
name: 'number2',
description: 'The second number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
]
})
})
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) {
return
}
const { commandName, Options } = interaction
if (commandName === 'ping') {
interaction.reply({
content: 'Pong! **60ms**',
// If anyone can see = True, Only command user can see = False
ephemeral: true,
})
} else if (commandName === 'add') {
interaction.reply({
content: 'The sum is ${number1 + number2}'
})
}
})
client.login(process.env.KEY)

For anyone that having the same problem. I fix this by simply going to bot developer portal then go to OAuth2 > URL generator. And for the scope select both "bot" and "applications.commands". Then scroll down choose whatever permission your bot need copy the URL.

You did not select the right permissions when creating bot login link for your discord server.
Goto developers / oauth again, click bot and select all the required permissions that you're using in this bot.
Then copy the link generated and use it to login with your bot into your server.

don't forget to change this:
content: 'The sum is ${number1 + number2}'
to this:
content: `The sum is ${number1 + number2}`

Related

Discord.js sending embed in dm using a / command

My code is simple, it should send a dm embed at the person choose by the user using the command (it is a test for a ban command but it is easier to no ban my alt to after dean him and rejoin with him).
There is my code :
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('Send a private message to a selected user')
.addUserOption(option =>
option
.setName('target')
.setDescription('The member to send the message to')
.setRequired(true))
.addStringOption(option =>
option
.setName('reason')
.setDescription('The reason for sending the message'))
.setDMPermission(false),
async execute(interaction) {
const target = interaction.options.getUser('target');
if (!target) return interaction.reply({ content: "You must provide a target user with the 'target' option.", ephemeral: true });
const reason = interaction.options.getString('reason') || 'No reason provided';
const owner = await interaction.guild.fetchOwner();
if (!owner) return interaction.reply({ content: "I couldn't fetch the guild owner.", ephemeral: true });
if (target.user === interaction.client.user) return interaction.reply({ content: "I can't send a message to myself.", ephemeral: true });
const banEmbed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('Hello! 😃')
.setAuthor({ name: `request by ${interaction.user.username}`, iconURL: interaction.guild.iconURL({ format: 'png', dynamic: true }) })
.setDescription(`You have been banned from ${interaction.guild}.`)
.addFields(
{ name: '\u200B', value: `If you think there's an error, please contact ${owner.user.username}#${owner.user.discriminator}.` },
{ name: '\u200B', value: `Reason: ${reason}` },
)
.setTimestamp()
.setFooter({ text: 'Have a good day !' });
try {
await target.send({ content: "hello", embed: banEmbed });
interaction.reply({ content: "The message has been sent successfully.", ephemeral: true });
} catch (error) {
console.error(error);
interaction.reply({ content: "I couldn't send the message to the target user.", ephemeral: true });
}
},
};
The code is working only if I add content not embedded, in that case it won't send the embed and if I don't put the content, it will just send the error :
DiscordAPIError[50006]: Cannot send an empty message
at SequentialHandler.runRequest (/Users/theophile/Desktop/test bot copie/node_modules/#discordjs/rest/dist/index.js:667:15)
at processTicksAndRejections (/Users/theophile/Desktop/test bot copie/lib/internal/process/task_queues.js:96:5)
at async SequentialHandler.queueRequest (/Users/theophile/Desktop/test bot copie/node_modules/#discordjs/rest/dist/index.js:464:14)
at async REST.request (/Users/theophile/Desktop/test bot copie/node_modules/#discordjs/rest/dist/index.js:910:22)
at async DMChannel.send (/Users/theophile/Desktop/test bot copie/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:176:15)
at async Object.execute (/Users/theophile/Desktop/test bot copie/commands/test.js:41:7)
at async Client.<anonymous> (/Users/theophile/Desktop/test bot copie/index.js:71:3) {requestBody: {…}, rawError: {…}, code: 50006, status: 400, method: 'POST', …}

Editing channel permissions using discord.js v14

I have got my options in a const value channel and reason and i am trying to edit the channels permission to lock the channel. Here is my current code for this command.
const { SlashCommandBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("lock")
.setDescription("Locks the channel u specify.")
.addChannelOption((option) =>
option
.setName("channel")
.setDescription("The channel u want to lock.")
.setRequired(true)
)
.addStringOption((option) =>
option
.setName("reason")
.setDescription("The reason why the channel was locked.")
.setRequired(true)
),
async execute(interaction, client) {
const channel = interaction.options.getChannel("channel");
let reason = interaction.options.getString("reason");
channel.permissionOverwrites.edit(interaction.guild.roles.everyone.id, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false,
READ_MESSAGE_HISTORY: true,
ATTACH_FILES: false
});
await interaction.reply({
content: `Locked channel ${channel} for the reason ${reason}`
});
},
};
But i am getting an error at line 23 where channel.permissionOverwrites.edit is.
ERROR:
C:\Users\Robin\Documents\Bobbie\node_modules\discord.js\src\util\BitField.js:168
throw new RangeError(ErrorCodes.BitFieldInvalid, bit);
^
at PermissionOverwriteManager.upsert (C:\Users\Robin\Documents\Bobbie\node_modules\discord.js\src\managers\PermissionOverwriteManager.js:100:50)
at PermissionOverwriteManager.edit (C:\Users\Robin\Documents\Bobbie\node_modules\discord.js\src\managers\PermissionOverwriteManager.js:145:17)
at Object.execute (C:\Users\Robin\Documents\Bobbie\src\commands\moderation\lock.js:23:38)
at Object.execute (C:\Users\Robin\Documents\Bobbie\src\events\client\interactionCreate.js:11:31) at Client.<anonymous> (C:\Users\Robin\Documents\Bobbie\src\functions\handlers\handleEvents.js:21:23)
at Client.emit (node:events:527:28) at InteractionCreateAction.handle (C:\Users\Robin\Documents\Bobbie\node_modules\discord.js\src\client\actions\InteractionCreate.js:81:12) { code: 'BitFieldInvalid'
}
[nodemon] app crashed - waiting for file changes before starting...
I have found the answer to this issue. The new discord.js update v14 now uses the PermissionsBitField.Flags.
So the fixed code is
channel.permissionOverwrites.set([
{
id: interaction.guild.id,
deny: [PermissionsBitField.Flags.SendMessages],
}, {
id: interaction.guild.id,
allow: [PermissionsBitField.Flags.ViewChannel],
}, {
id: interaction.guild.id,
allow: [PermissionsBitField.Flags.ReadMessageHistory]
}, {
id: interaction.guild.id,
deny: [PermissionsBitField.Flags.CreatePublicThreads]
}, {
id: interaction.guild.id,
deny: [PermissionsBitField.Flags.CreatePrivateThreads]
}
]);

I created a bot which have 3 commands. Invalid Form Body parent_id: Value "" is not snowflake

[Shopify Sales Tracker/16:28:9]: [ERROR] ➜ uncaughtException => DiscordAPIError: Invalid Form Body
parent_id: Value "" is not snowflake.
at RequestHandler.execute (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async TextChannel.edit (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\structures\GuildChannel.js:336:21)
at async Object.module.exports.run (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\src\client\commands\shopify\addshop.js:16:4)
at async Object.module.exports.run (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\src\client\events\messageCreate.js:29:3)
module.exports.run = async (app, client, message, args) => {
const shop_url = args[0];
if (!app.shopify.config.shops.includes(shop_url)) {
const server = message.guild;
var webhook;
if (!app.shopify.config.webhooks[shop_url]) {
const channel_name = app.config.discord.shop_channel_name(shop_url);
const channel = await server.channels.create(channel_name, {
type: 'text',
});
await channel.setParent(app.config.discord.products_category);
webhook = await channel.createWebhook(shop_url);
}
await app.utils.shopify.addNewShopToConfig(
shop_url,
webhook ? webhook.url : undefined
);
const embed = app.utils.discord.createEmbed('info', {
title: `Shop hinzugefügt [${shop_url}]`,
description: `\`\`${shop_url}\`\` wurde erfolgreich zur Datenbank hinzugefügt.`,
});
await app.utils.shopify.loadProducts();
return await message.channel.send({ embeds: [embed] });
} else {
const embed = app.utils.discord.createEmbed('error', {
description: 'Du hast diesen Shop bereits hinzugefügt',
});
return await message.channel.send({ embeds: [embed] });
}
};
module.exports.conf = {
name: 'addshop',
description: 'Füge einen Shop in die db hinzu',
category: 'Shopify',
owner: false,
premium: false,
admin: false,
guild: true,
dm: false,
disabled: false,
usage: ['addshop <url>'],
example: ['addshop hoopsport.de'],
aliases: ["add"],
minArgs: 0,
maxArgs: 0,
};
The problem is here
await channel.setParent(app.config.discord.products_category);
I see you use this github repo. So look what's on the src folder, config subfolder and discord.js file :
products_category: '', // create a category in your server and put its id inside here
Just create a category channel and copy it's id and paste it here and restart your bot.

Discord.js v13 ReferenceError: member is not defined | in a kick command

So basically I was updating this bot to Discord.js v13 a few months ago and now that I got back to this (I got busy with other things), I can't seem to figure out what went wrong with this Kick command.
The Error
ReferenceError: member is not defined
at Object.run (C:\Users\Admin\OneDrive\Desktop\mybots\testbot\src\Commands\Moderation\Kick.js:49:30)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async run (C:\Users\Admin\OneDrive\Desktop\mybots\testbot\src\Events\InteractionCreate.js:32:11)
kick.js | The kick command src
const { confirm } = require('../../Structures/Utils');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'kick',
description: 'Kick a member.',
category: 'Moderation',
options: [
{
name: 'user',
description: 'Mention a user',
required: true,
type: 'USER'
},
{
name: 'reason',
description: 'Specify reason for kick',
required: true,
type: 'STRING'
}
],
permissions: 'KICK_MEMBERS',
async run({ interaction, bot }) {
const user = interaction.options.getMember('user');
const reason = interaction.options.getString('reason');
if (!user.kickable)
return interaction.reply({
embeds: [new MessageEmbed().setColor('RED').setDescription(`I don't have permissions to kick ${user}.`)]
});
if (user.id === interaction.user.id)
return interaction.reply({
embeds: [new MessageEmbed().setColor('RED').setDescription(`You cannot kick yourself.`)]
});
const confirmation = await confirm(
interaction,
new MessageEmbed()
.setTitle('Pending Conformation')
.setColor('ORANGE')
.setDescription(`Are you sure you want to kick ${user} for reason: \`${reason}\`?`)
.setFooter({ text: 'You have 60 seconds.' })
);
if (confirmation.proceed) {
const embed = new MessageEmbed()
.setColor('ORANGE')
.setDescription(`**${member.user.tag}** was kicked for \`${reason}\`.`);
try {
await user.send({
embeds: [
new MessageEmbed()
.setTitle('You were kicked')
.setColor('ORANGE')
.addField('Reason', reason, false)
.addField('Guild', interaction.guild.name, false)
.addField('Date', time(new Date(), 'F'), false)
]
});
} catch (err) {
embed.setFooter({
text: `I was not able to DM inform them`
});
}
await confirmation.i.update({
embeds: [embed],
components: []
});
await user.kick({ reason });
}
const embed = new MessageEmbed()
.setTitle('Process Cancelled')
.setColor('ORANGE')
.setDescription(`${user} was not kicked.`);
if (confirmation.reason) embed.setFooter({ text: confirmation.reason });
await confirmation.i.update({
embeds: [embed],
components: []
});
}
};
InteractionCreate.js | Another file that showed up in the error
const { MessageEmbed } = require('discord.js');
module.exports = {
event: 'interactionCreate',
async run(bot, interaction) {
if (!interaction.isCommand()) return;
const command = bot.commands.get(interaction.commandName);
if (!command) return;
if (command.permission && !interaction.member.permissions.has(command.permission)) {
return await interaction.reply({
embeds: [
new MessageEmbed()
.setColor('RED')
.setDescription(`You require the \`${command.permission}\` to run this command.`)
]
});
} else {
// If command's category is `NSFW` and if interaction.channel.nsfw is false, inform them to use the command in nsfw enabled channel.
if (command.category === 'NSFW' && !interaction.channel.nsfw) {
await interaction[interaction.deferred ? 'editReply' : interaction.replied ? 'followUp' : 'reply']({
embeds: [
new MessageEmbed()
.setColor('RED')
.setDescription('You can use this command in Age-Restricted/NSFW enabled channels only.')
.setImage('https://i.imgur.com/oe4iK5i.gif')
],
ephemeral: true
});
} else {
try {
await command.run({ interaction, bot, options: interaction.options, guild: interaction.guild });
} catch (err) {
console.log(err);
await interaction[interaction.deferred ? 'editReply' : interaction.replied ? 'followUp' : 'reply']({
embeds: [new MessageEmbed().setColor('RED').setDescription(err.message || 'Unexpected error')]
});
}
}
}
}
};
Thanks a lot in advance!
In line 49 of your Kick.js file you're using member.user.tag but you did not define member. Add this:
const user = interaction.options.getMember('user');
const member = interaction.guild.members.cache.get(user.id);
And in line 72, you're trying to ban the user instead of the guild member.
Change this:
await user.kick({ reason });
To this:
await member.kick({ reason });

TypeError: Cannot read property 'setPresence' of null discord.js v13

I have a little problem. I'm doing the event ready, with an event handler, but I come across this error:
client.user.setPresence({
^
TypeError: Cannot read property 'setPresence' of null
I don't really know what I'm doing wrong, here is the code:
const mongo = require('../../mongo');
const mongoose = require('mongoose');
const messageCount = require('../../message-counter')
const Discord = require('discord.js')
module.exports = async (Discord, client) => {
let serverIn = client.guilds.cache.size;
console.log('[INFO] Doose is online');
client.user.setPresence({
status: "dnd",
activity: {
name: `${serverIn} servers! | BETA | d.help`,
type: "WATCHING"
}
});
console.log('[INFO] Connected to MongoDB')
messageCount(client)
};
MUST READ: Extra Info
Using discord.js V13
Presence can be set via the options parameter in the Discord.Client(options) constructor like so:
const client = new Client({
presence: {
status: 'online',
afk: false,
activities: [{
name: ...,
type: ...,
}],
},
intents: [...],
partials: [...],
});
This should help !!
client.on('ready', () => {
client.user.setActivity(`!help || ${client.guilds.cache.size} Servers `, { type: "LISTENING" })
console.log(`Logged in as ${client.user.tag}`);
})
and for the other , you can use something like this ⬇️
client.user.setPresence({
status: "idle"
})

Categories

Resources