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', …}
Related
I'm trying to make my bot type a message upon joining a guild, but it doesn't seem to work.
What I've tried: (among some other variations)
const { PermissionsBitField } = require('discord.js');
module.exports = async (client, guild) =>{
const channel = guild.channels.cache.find(channel => channel.type === 0 && channel.permissionsFor(guild.members.me).has(PermissionsBitField.Flags.SendMessages))
channel.send("Thank you for inviting me!")
}
const { PermissionsBitField } = require('discord.js');
module.exports = async (client, guild) =>{
const channel = guild.channels.cache.find(channel => channel.type === 0 && guild.members.me.permissionsIn(channel).has(PermissionsBitField.Flags.SendMessages))
channel.send("Thank you for inviting me!")
}
For some reason it still tries to send in a channel where the bot doesn't have permission to send messages in.
throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:659:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:458:14)
at async REST.request (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:902:22)
at async TextChannel.send (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:175:15) {
requestBody: {
files: [],
json: {
content: 'Thank you for inviting me!',
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,
thread_name: undefined
}
},
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'POST',
url: 'https://discord.com/api/v10/channels/1007005313968390306/messages'
}
Turns out adding
&&channel.permissionsFor(guild.members.me).has(PermissionsBitField.Flags.ViewChannel) has solved my problem.
[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.
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 });
When I try to run my command, instead of the errors I specified, I get the errors from the console and the result is: Failed to ban the user and the console says DiscordAPIError: Interaction has already been acknowledged. and/or missing permissions. But if I try to ban myself with an account that has no rights, I get banned myself. So if I do tryfyfu /ban user: #tryfyfu with my acc (the account without rights) I can still ban myself but the bot should actually say: "❌ | You can't ban a user from the guild!" answer and so it is with the other functions like invalid memberor ❌ | You can't ban yourself and so on Here's the code. Would be nice if someone could help me.
const {
Client,
CommandInteraction,
Message,
MessageEmbed,
MessageActionRow,
MessageButton
} = require('discord.js');
module.exports = {
name: 'ban',
description: 'Ban a user',
options: [
{
name: "user",
description: "Choose the user to ban.",
type: "USER",
required: true
},
{
name: "reason",
description: "reason for punishment",
type: "STRING",
required: false
}
],
run: async (client, interaction, options) => {
const member = interaction.options.getMember("user")
const reason = interaction.options.getString("reason") || "No reason given"
if(!interaction.member.permissions.has("BAN_MEMBERS")) {
const buttons = new MessageActionRow()
.addComponents(new MessageButton()
.setLabel("Permissions")
.setEmoji("⚙️")
.setStyle("LINK")
.setURL("https://discord.com/developers/docs/topics/permissions"))
const embed = new MessageEmbed()
.setColor("RED")
.setDescription("❌ | You can't ban a user from the guild!")
interaction.reply({
embeds: [embed],
components: [buttons],
ephemeral: true
})
}
if(member === interaction.member) {
const embed = new MessageEmbed()
.setColor("RED")
.setDescription("❌ | You can't ban yourself")
interaction.reply({
embeds: [embed]
})
}
if (!member) {
const embed = new MessageEmbed()
.setColor("RED")
.setDescription("❌ | Invalid Member")
interaction.reply({
embeds: [embed],
ephemeral: true
})
}
try {
await interaction.guild.bans.create(member, {
reason
})
const embed = new MessageEmbed()
.setColor("GREEN")
.setDescription(`✅ | ${member.user.tag} was banned for: ${reason}`)
return interaction.reply({
embeds: [embed]
})
}
catch(err){
if (err){
console.error(err)
const embed = new MessageEmbed()
.setColor("RED")
.setDescription(`❌ | Failed to ban ${member.user.tag}`)
return interaction.reply({
embeds: [embed]
})
}
}
}
}
Changed two things below (different method of banning and corrected one mistake). They are notated below.
const {
MessageEmbed,
MessageActionRow,
MessageButton
} = require('discord.js');
module.exports = {
name: 'ban',
description: 'Ban a user',
options: [{
name: "user",
description: "Choose the user to ban.",
type: "USER",
required: true
},
{
name: "reason",
description: "reason for punishment",
type: "STRING",
required: false
}
],
run: async (client, interaction, options) => {
const member = interaction.options.getUser("user")
// .getMember is not a valid function as the type specified above is "USER"
const reason = interaction.options.getString("reason") || "No reason given"
if (!interaction.member.permissions.has("BAN_MEMBERS")) {
const buttons = new MessageActionRow()
.addComponents(new MessageButton()
.setLabel("Permissions")
.setEmoji("⚙️")
.setStyle("LINK")
.setURL("https://discord.com/developers/docs/topics/permissions"))
const embed = new MessageEmbed()
.setColor("RED")
.setDescription("❌ | You can't ban a user from the guild!")
return interaction.reply({
embeds: [embed],
components: [buttons],
ephemeral: true
})
}
if (member === interaction.member) {
const embed = new MessageEmbed()
.setColor("RED")
.setDescription("❌ | You can't ban yourself")
return interaction.reply({
embeds: [embed]
})
}
if (!member) {
const embed = new MessageEmbed()
.setColor("RED")
.setDescription("❌ | Invalid Member")
return interaction.reply({
embeds: [embed],
ephemeral: true
})
}
// changed up the part below
try {
const embed = new MessageEmbed()
.setColor("GREEN")
.setDescription(`✅ | ${member.user.tag} was banned for: ${reason}`)
interaction.reply({
embeds: [embed]
})
return member.ban({
reason: reason
})
} catch (err) {
if (err) {
console.error(err)
const embed = new MessageEmbed()
.setColor("RED")
.setDescription(`❌ | Failed to ban ${member.user.tag}`)
return interaction.reply({
embeds: [embed]
})
}
}
}
}
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}`