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]
})
}
}
}
}
Related
MissingSchemaError: Schema hasn't been registered for model "undefined".
Use mongoose.model(name, schema)
at Mongoose.model (C:\Users\Brody Hedges\Desktop\DOC Utility\node_modules\mongoose\lib\index.js:551:13)
at Object. (C:\Users\Brody Hedges\Desktop\DOC Utility\src\Schemas.js\stickySchema.js:12:18)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)
at Module.load (node:internal/modules/cjs/loader:1089:32)
at Module._load (node:internal/modules/cjs/loader:930:12)
at Module.require (node:internal/modules/cjs/loader:1113:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object. (C:\Users\Brody Hedges\Desktop\DOC Utility\src\commands\tools\stick.js:3:22)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
DOC Utility\src\Schemas.js\stickySchema.js
const { model, Schema } = require("mongoose");
let stickySchema = new Schema({
Message: { type: String },
ChannelID: { type: String },
LastMessage: { type: String },
LastMessageID: { type: String },
MaxCount: { type: Number, default: 6 },
CurrentCount: { type: Number, default: 0 }
})
module.exports = model("stickSchema". stickySchema);
DOC Utility\src\commands\tools\stick.js
const mongoose = require(`mongoose`);
const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, messageLink } = require('discord.js');
const stickySchema = require('../../Schemas.js/stickySchema');
module.exports = {
data: new SlashCommandBuilder()
.setName("stick")
.setDescription("Makes a sticky message.")
.addStringOption(option => option.setName('message').setDescription('The message you want to stick in chat.').setRequired(true))
.addNumberOption(option => option.setName('count').setDescription('How frequently you want the sticky message to be sent.').setRequired(false))
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
.setDMPermission(false),
async execute(interaction) {
let string = interaction.otpions.getString('message');
let amount = interaction.otpions.getNumber('count') || 6;
const embed = new EmbedBuilder()
.setColor("Blue")
.setDescription(string)
.setFooter({ text: "This is a sticky message"} )
stickySchema.findOne({ ChannelID: interaction.channel.ID}, async (err, data) => {
if (err) throw err;
if (!data) {
let msg = await interaction.channel.send({ embeds: [embed] });
stickySchema.create({
ChannelID: interaction.channel.id,
Message: string,
MaxCount: amount,
LastMessageID: msg.id,
})
return await interaction.reply({ content: "The sticky message has been setup", ephemeral: true});
} else {
await interaction.reply({ content: "You already have a sticky message setup within this channel.", ephemeral: true})
}
})
}
}
Ignore how shitty my code is, I just got back into doing JavaScript. Anyway, if you need any other code please DM me.
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', …}
[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 });
I am currently having a problem about my signup command and when searched about the error I am having which is:
MongoServerError: E11000 duplicate key error collection: ShinDB.users index: username_1 dup key: { username: "Shin" }
they always say to drop the collection which I don't want.
what i want is for example i wrote '>signup Shin thisisatest#1234' and if the 'Shin' username is already in the username database it will NOT send the 'MongoServerError' in the console but instead it will send an error 'That username already exist' in the channel which the user send it to.
Signup Command:
var strongRegex = new RegExp("^(?=.{14,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{10,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{8,}).*", "g");
var specialChar = /[`!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
const User = require('../../Database/models/user')
module.exports = {
name: "signup",
description: "Signup for an Economy Account",
usage: ">signup",
aliases: [],
run: async (client, message, args) => {
//message is inguild
if (message.inGuild()) {
return message.reply({ content: `This command can only be used in <#${client.user.id}> DM.\n\`\`Usage: >signup <username> <password>\`\`\n\`\`Note: Your Economy Account is Safe\`\`` })
}
//message is in DM
if (message.channel.type === 'DM') {
// USERNAME
const userargs = args[0]
const pass = args[1]
if (!userargs) {
return message.reply({ content: '**Please provide a username for your Economy Account!\n``Correct Usage: >signup <username> <password>``**' })
}
const userToLow = userargs.toLowerCase()
const user = userToLow.charAt(0).toUpperCase() + userToLow.substring(1, userToLow.length)
if (user.length < 3) return message.reply({ content: '**[__Too Short__]** **Your Username must have atleast 3 Characters**' })
if (user.length > 7) return message.reply({ content: '**[__Too Long__]** **You Username must only have 7 Characters**' })
if (specialChar.test(user)) {
return message.reply({ content: '**Username\'s must not have any Special Characters**' })
}
// PASSWORD
let str
let med
let weak
if (strongRegex.test(pass)) {
str = 'Strong'
}
if (mediumRegex.test(pass)) {
med = 'Medium'
}
if (!strongRegex.test(pass) && !mediumRegex.test(pass)) {
weak = 'Weak'
}
if (!pass) return message.reply({ content: '**Please provide a password for your Economy Account!**' })
if (pass.length < 8) return message.reply({ content: '**[__Too Short__]** **Your Password must have atleast 8 Characters**' })
// CREATING THE ACCOUNT
User.findOne({ createdBy: message.author.id }, async (err, data) => {
if (data) {
return message.reply({ content: `**You already have made an Account and the Username of the Account that you made is: \`\`${data.username}\`\`\n\`\`Note: if you forget your password you can just run the command >recoveraccount\`\`**` })
} else if (err) {
return message.reply({ content: 'That username already exist' })
} else {
new User({
loggedInOn: "0",
createdBy: message.author.id,
isLoggedIn: false,
username: user,
password: pass,
}).save()
return message.reply({ content: 'You have successfuly made an Economy Account!'})
}
})
}
}
}
User Schema/Model:
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
loggedInOn: String,
createdBy: String,
isLoggedIn: Boolean,
username: {
type: String,
unique: true
},
password: String
})
module.exports = mongoose.model('Users', userSchema)
Full Error:
return callback(new error_1.MongoServerError(res.writeErrors[0]));
^
MongoServerError: E11000 duplicate key error collection: ShinDB.users index: username_1 dup key: { username: "Shin" }
at C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\operations\insert.js:53:33
at C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection_pool.js:273:25
at handleOperationResult (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\sdam\server.js:327:20)
at Connection.onMessage (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:215:9)
at MessageStream.<anonymous> (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:63:60)
at MessageStream.emit (node:events:527:28)
at processIncomingData (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10) {
index: 0,
code: 11000,
keyPattern: { username: 1 },
keyValue: { username: 'Shin' },
[Symbol(errorLabels)]: Set(0) {}
}
My Database Current Collections:
Collections Picture
i hope i have explained it very well, any help would be really appreciated. thanks.
To fix your bot instance shutting down use the following:
client.on('error', (error) => {
console.error(error)
// You can also put your "error message" create here
})
Along with that. Whatever you're doing with your MongoDB code is very "jank". The following will likely fix it.
User.findOne({ createdBy: message.author.id }).then((data) => {
if (data) {
return message.reply({
content: `**You already have made an Account and the Username of the Account that you made is: \`\`${data.username}\`\`\n\`\`Note: if you forget your password you can just run the command >recoveraccount\`\`**`,
});
} else if (!data) {
User.findOne({ username: user }).then((findUsername) => {
if (findUsername) {
return message.reply('There is already an account with that username!')
} else {
new User({
loggedInOn: '0',
createdBy: message.author.id,
isLoggedIn: false,
username: user,
password: pass,
}).save();
return message.reply({ content: 'You have successfuly made an Economy Account!' });
}
});
}
});
Let me know if you have any questions