Why is my kick command only giving errors? - javascript

Wassup people. I am working on some admin commands. At this moment it's going to be a kick command. But it's only giving errors. If you remove a line or change anything, it will infect the code in another place.
That's what I am struggling with.
Here's my code:
const { Client, Intents } = require("discord.js");
const discord = require("discord.js");
const { MessageEmbed, Collection, Permissions } = require("discord.js");
module.exports = {
name: "kick",
description: "Kicks a specific member",
admin: true,
usage: "[Target] [Reason] [Messages]",
options: [
{
name: "Target",
description: "Provide A User To Kick.",
type: "USER",
required: true,
},
{
name: "Reason",
description: "Provide A Reason For The Kick.",
type: "STRING",
required: true,
},
],
async execute(message, args, client) {
const target = message.mentions.members.first();
const reason = args.slice(1, args.length - 1).join(" ");
console.log("Target: ");
const embed = new MessageEmbed().setTitle("There seems to be a error to execute this command").setColor("RED").setDescription("Are you sure you got the right permission? And are you providing a reason?");
if (!message.member.permissions.has(Permissions.FLAGS.KICK_MEMBERS))
return message.reply({ embeds: [embed] }).catch((err) => {
console.log(err);
});
if (target.id === message.member.id)
return message.reply({
embeds: [new MessageEmbed().setTitle("There seems to be a error to execute this command").setColor("RED").setDescription("Why would you kick yourself?")],
ephemeral: true,
});
if (target.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) {
return message.reply({
embeds: [new MessageEmbed().setColor("RED").setDescription("You can't kick this person.")],
});
}
const DMEmbed = new MessageEmbed().setTitle(`You've Been Kicked From ${message.guild.name}`).setColor("RED").setTimestamp().addFields(
{
name: "Reason:",
value: reason,
},
{
name: "Kicked By:",
value: message.member.user.toString(),
}
);
await target
.send({
embeds: [DMEmbed],
})
.catch((err) => {
console.log(err);
});
},
};

From what I can see, it is most likely the reason field being empty.
You can change it to this to ensure there is a fallback!
{
name: "Reason:",
value: reason.replace(/\s/g, '') == "" ? "Not Provided" : reason,
},

Related

Making a discord bot and getting 0.name[BASE_TYPE_REQUIRED]: This field is required error

Main bot file
const {
Client,
GatewayIntentBits,
Routes,
EmbedBuilder,
ActivityType,
} = require('discord.js');
const { token, clientId, guildId } = require('../config.json');
const { REST } = require('#discordjs/rest');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildBans,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const { UrlCommand } = require('../Commands/UrlCommand.json');
client.on('ready', (client) => {
console.log(`${client.user.username}#${client.user.discriminator} running`);
client.user.setPresence({
activities: [{ name: 'connections', type: ActivityType.Watching }],
});
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'url') {
console.log(`called ${interaction.commandName} command`);
const urlEmbed = new EmbedBuilder()
.setColor('0x0099FF')
.setTitle('LEPSES')
.setURL('https://lepses.com')
.setAuthor({
name: 'LEPSES Bot',
// TODO: replace icon
iconURL:
'https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Latin_capital_letter_L_with_descender.svg/497px-Latin_capital_letter_L_with_descender.svg.png',
})
.setDescription('You choose, we connect!')
.addFields(
// TODO : add more data in the fields
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
{
name: 'Inline field title',
value: 'Some value here',
inline: true,
},
{
name: 'Inline field title',
value: 'Some value here',
inline: true,
}
);
await interaction.reply({ embeds: [urlEmbed] });
}
if (interaction.commandName === 'clear') {
if (interaction.options.get('amount') >= 5000) {
interaction.reply('You cannot delete more than 5000 messages');
} else {
try {
const amount = interaction.options.getInteger('amount');
const Channel = interaction.channel;
if (amount) {
Channel.bulkDelete(amount, true);
await interaction.reply(`${amount} messages purged`);
} else {
Channel.bulkDelete(50, true);
await interaction.reply(`50 messages purged`);
}
} catch (err) {
console.log(err.message);
}
}
}
});
const rest = new REST({ version: '10' }).setToken(token);
async function main() {
// const commands = [];
const commands = [UrlCommand];
try {
console.log(
`Started refresing application ${commands.length} commands`
);
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: commands,
});
client.login(token);
} catch (error) {
console.log('ERROR=================================================');
console.log(error.message);
console.log('ERROR=================================================');
}
}
main();
URL Command in json file
{
"name": "url",
"description": "Visit us now!!"
}
Url command was in the main file earlier but now I'm moving older commands to external files to make the code smaller and easier to change in the future. But as soon as the code runs it shows BASE_TYPE_REQUIRED error. It runs normally if I declare commands as an empty array. What do I do?
You have to write the exported command in JavaScript as well. JSON is a storage file type. Try refering to discord.js command handling guide and see if it helps you.

Infraction Has Been Already Acknowledged - DiscordAPIError Problem

so I have been working on this help command for some time now. In the beginning, there was no such error, but now even after all the methods I came up with, weren't able to fix this error. I tried to remove the selectMenu after 60s to prevent old interactions to launch as well but it still doesn't seem to work properly. I have added my code to this as well, please do help me.
const { MessageSelectMenu, Collector } = require("discord.js");
module.exports = {
name: 'help',
description: "This is a help command!",
async execute(message, args, Discord, client){
let commandUser = message.author.id
let helpEmbed = new Discord.MessageEmbed()
.setColor('#EF4344')
.setAuthor('Builder BOT • Help-Command','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
.setDescription(`• My prefix is \`b!\`.\n • We recommend to give the BOT Administrator permission.\n • We recommend NOT to change the BOT-role's and channel's permission.\n • Type \`b!help <module>\` for further information regarding a specific module.\n • Type \`b!help <command>\` for further information regarding a specific command.`)
.addFields({
name: 'BOT-Modules:',
value: `• <:Hammer:960753810253414401>_Build-Module_\n • <:Gear:960764548195958834>_Config-Module_\n • <:Pencil:960962910463598615>_Action Log-Module_\n • <:Staff:960964396425814117>_Moderation-Module_\n • <:Misc:960964890460319855>_Misc-Module_\n • <:Rocket:960965476673019954>_Fun-Module_`,
inline: true
},{
name: 'BOT-Updates:',
value: '**Help command under-development**\n Use the command for more information.\n Eg- \`b!help\`',
inline: true
})
.setTimestamp()
.setFooter(`Author ID: ${message.author.id}`,`${message.author.displayAvatarURL()}`);
let helpSelectMenu = new Discord.MessageActionRow().addComponents([
new MessageSelectMenu()
.setCustomId('Help-SelectMenu')
.setPlaceholder('For more information, choose a module!')
.addOptions([
{
label: 'Build-Module',
value: 'Build_Option',
description: 'Build servers more easily than ever before!',
emoji: `<:Hammer:960753810253414401>`
},
{
label: 'Config-Module',
value: 'Config_Option',
description: 'Configure Builder BOT\'s settings!',
emoji: `<:Gear:960764548195958834>`
},
{
label: 'Action Log-Module',
value: 'Action Log_Option',
description: 'Keep track of everything that happens in the server!',
emoji: `<:Pencil:960962910463598615>`
},
{
label: 'Moderation-Module',
value: 'Moderation_Option',
description: 'Automate moderation and protect your server!',
emoji: `<:Staff:960964396425814117>`
},
{
label: 'Misc-Module',
value: 'Misc_Option',
description: 'Uncategorized amazing features!',
emoji: `<:Misc:960964890460319855>`
},
{
label: 'Fun-Module',
value: 'Fun_Option',
description: 'Engage members with interactive commands!',
emoji: `<:Rocket:960965476673019954>`
}
])
])
message.channel.send({ embeds: [helpEmbed], components: [helpSelectMenu] }).catch(() => {
if(message.channel.permissionsFor(client.user.id).has(['SEND_MESSAGES'])){
message.channel.send(`<#${message.author.id}>, I don't have the required permissions!`).then(msg => {
setTimeout(() => {msg.delete()}, 5000)
})
}else{
return;
};
}).then((msg) => {
setTimeout(() => {msg.edit({ embeds: [helpEmbed], components: []})}, 60000)
});
let underDevelopment = new Discord.MessageEmbed()
.setColor('#EF4344')
.setDescription('The BOT is currently under development process!')
.setTimestamp()
let helpDropdownfilter = (interaction) => (interaction.isSelectMenu() && interaction.user.id === message.author.id);
let helpDropdownCollector = message.channel.createMessageComponentCollector({
helpDropdownfilter,
max: 2,
time: 60000
});
helpDropdownCollector.on('collect', async (interaction) => {
console.log(interaction.values[0]);
if(commandUser === interaction.user.id){
if(interaction.values[0] === 'Build_Option'){
underDevelopment.setAuthor('Builder BOT • Build-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
if(interaction.values[0] === 'Config_Option'){
underDevelopment.setAuthor('Builder BOT • Config-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: []});
}
if(interaction.values[0] === 'Action Log_Option'){
underDevelopment.setAuthor('Builder BOT • Action Log-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
if(interaction.values[0] === 'Moderation_Option'){
underDevelopment.setAuthor('Builder BOT • Moderation-Work','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
if(interaction.values[0] === 'Misc_Option'){
underDevelopment.setAuthor('Builder BOT • Misc-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
if(interaction.values[0] === 'Fun_Option'){
underDevelopment.setAuthor('Builder BOT • Fun-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
}else{
await interaction.reply({ content: `<#${interaction.user.id}>, you do not have access to this interaction!`, ephemeral: true})
}
})
}
}
I see that you are using a lot of if conditions. I'd suggest using if and else if instead of using if multiple times. Also, try the following code;
const initial = await message.channel.send({ /** ... */ });
const filter = // ...
const collector = // ...
collector.on("collect", async(interaction) => {
if(interaction.values[0] === "something"){
if(initial.editable){
await initial.edit(/** ... */)
} else return;
} else if (interaction.values[0] === "anything"){
// ...
}
})
You're basically saving the first response of the bot, to later on edit the responses as they select options from the menu.

Export variable to other files discordjs

I changed my command handler and am no longer exporting anything from profileData (used to be command handler file). The file is checking for their profile and holding the data in profileData, or if they don't have on then create one for them. I want to export the profileData to be used in other files instead of querying in every single command. How can I achieve this. I have tried putting module.exports and exports.profileData = profileData all over the place and nothing works im just lost on how to do this. Any help would be appreciated.
profileData-
const profileModel = require("../../models/profileSchema");
module.exports = (client) => {
client.on("message", async (message) => {
const prefix = 's!'
if (!message.content.startsWith(prefix) || message.author.bot) return;
try {
const profileData = await profileModel.findOne({ userID: message.author.id });
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 10,
bank: 0,
});
profile.save();
}
} catch (err) {
console.log(err);
}
})
}
module.exports.config = {
displayName: 'Profile Data',
dbName: 'PROFILEDATA',
loadDBFirst: true
}
balance-
const { MessageEmbed } = require("discord.js");
const { profileData } = require("../../Features/client/profileData");
module.exports = {
name: "balance",
aliases: ["bal"],
category: "Economy",
cooldown: "20s",
permissions: ["ADMINISTRATOR"],
maxArgs: 0,
description: "Check your wallet and bank balance!",
execute: async ({ message, client }) => {
let balPlaceholder = "'s balance";
const BalEmbed = new MessageEmbed()
.setColor("#0bbffc")
.setAuthor("Saoul 2")
.setTitle(`${message.author.username}${balPlaceholder}`)
.addFields(
{ name: "💸 Wallet:", value: `${profileData.coins}`, inline: true },
{ name: "🏦 Bank:", value: `${profileData.bank}`, inline: true }
)
.setTimestamp()
.setFooter(
`Command Requested By ${message.author.tag}`,
client.user.displayAvatarURL()
);
message.channel.send(BalEmbed);
},
};
If I understand you correctly: you want to export the profileData, and if none can be found, create a new profile and use that. The following snippet might solve your problem.
const profileModel = require("../../models/profileSchema");
let data = getData(client);
exports.data = data;
async function getData(client) {
client.on("message", async(message) => {
const prefix = 's!'
if (!message.content.startsWith(prefix) || message.author.bot) return;
try {
const profileData = await profileModel.findOne({
userID: message.author.id
});
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 10,
bank: 0,
});
profile.save();
return profile;
} else {
return profileData;
}
} catch (err) {
console.log(err);
}
})
}
module.exports.config = {
displayName: 'Profile Data',
dbName: 'PROFILEDATA',
loadDBFirst: true
}
This is all I needed to get the function to run when a message is sent through the command handler.
module.exports = {
getData: async (message) => {
try {

Overwrite Permissions for all channels in a discord server

I'm trying to create a moderation discord bot with a mute command. The mute command works in the channel that you send the command in but it doesn't work in all of the other channels. I've tried to have it go over all channels using forEach() but that doesn't seem to work. I've looked through this and tried the other solutions but its still not working. Here is the code, I hope you can help.
const Discord = require("discord.js");
const ms = require('ms')
module.exports = {
name: "mute",
aliases: [],
category: "moderation",
run: async(bot, message, args) => {
let toMute = message.guild.member(message.mentions.users.first() || message.guild.members.cache.get(args[0]));
if(!toMute) return message.channel.send("Couldn't find the user.");
if(toMute.hasPermission("MANAGE_MESSAGES")) return message.reply("Can't mute them")
let muteRole = message.guild.roles.cache.find(muteRole => muteRole.name === "Muted");
//This is where the problem starts
if(!muteRole){
muteRole = await message.guild.roles.create({ data: { name: "Muted", color: 0x000000, permissions: [] } })
message.guild.channels.cache.each(async (channel) => {
await channel.overwritePermissions(muteRole, {
"SEND_MESSAGES": false,
"ADD_REACTIONS": false,
"TALK": false
});
});
}
let muteTime = args[1];
if(!muteTime) return message.reply("Please Specify a time.");
await(toMute.roles.add(muteRole));
const mEmbed = new Discord.MessageEmbed()
.setTitle("Muted")
.addFields({ name: "Member", value: toMute, inline: false },
{ name: "Time", value: muteTime })
.setTimestamp()
message.channel.send(mEmbed)
setTimeout(function() {
toMute.roles.remove(muteRole);
message.channel.send(`<#${toMute.id}> has been unmuted`);
}, ms(muteTime))
}
}
I changed the overwritePermissions() to updateOverwrite() and it seemed to work. Here is the code:
if(!muteRole){
muteRole = await message.guild.roles.create({
data: {
name: "Muted",
color: "#000000",
permissions: [],
},
});
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.updateOverwrite(muteRole, {
SEND_MESSAGES: false,
SPEAK: false,
ADD_REACTIONS: false
})
});
}
I also organized the code to make it easier to see.

How to make an if statement in javascript using sqlite

So i recently made this code with a warn command in discord js but there's a problem my if statement doesn't work like i wanted it to be and i wanted it to be if value doesn't exists return message.channel.send("This user has no records!"); Because i never tried using sqlite on javascript and i only know sqlite on c#
const con = require("../../sql.js");
con.all(`SELECT * FROM warnings WHERE username = ? AND userID = ?`, User.tag, User.id, (err, rows) => {
rows.forEach(r => {
if (!rows) {
message.channel.send("NO U");
}
else {
let moderator = (r.moderator);
let modID = (r.modID);
let reason = (r.reason);
let time = (r.time);
let Avatar = User.displayAvatarURL();
let Embed = new MessageEmbed()
.setTitle(`User warnings!`)
.setDescription(
`These is all the warnings which have been issued to ${User.tag}!`)
.setColor(`RED`)
.setThumbnail(Avatar)
.addFields({
name: "Moderator",
value: `${moderator}`,
inline: true
}, {
name: "Username",
value: `${User.tag}`,
inline: true
}, {
name: "Reason",
value: `${reason}`,
inline: true
}, {
name: "When was warned",
value: `${time}`,
inline: true,
});
message.channel.send(Embed).then(msg => {
msg.delete({
timeout: 15000
});
message.delete({
timeout: 3000
});
})
}
})
})
Move the if statement outside of the forEach loop.
Before:
rows.forEach(r => {
if (!rows) {
message.channel.send("NO U");
}
After:
if (rows.length === 0) {
return message.channel.send("NO U");
}
rows.forEach(r => {
As pointed out in other comments, change !rows to rows.length === 0 since the library returns an empty array when no rows are found.
I'd refactor things so there's a separate function that turns an user and the row from the database into a MessageEmbed.
That way it's easy to first try and map any warnings there are to messages, then look at whether any got generated, and if not, send out the other message.
Note that even empty arrays are truthy in JavaScript, so you'll need to check for .length.
const con = require("../../sql.js");
function warningRowToMessage(User, row) {
const { moderator, reason, time } = row;
return new MessageEmbed()
.setTitle(`User warnings!`)
.setDescription(`These is all the warnings which have been issued to ${User.tag}!`)
.setColor(`RED`)
.setThumbnail(User.displayAvatarURL())
.addFields(
{
name: "Moderator",
value: `${moderator}`,
inline: true,
},
{
name: "Username",
value: `${User.tag}`,
inline: true,
},
{
name: "Reason",
value: `${reason}`,
inline: true,
},
{
name: "When was warned",
value: `${time}`,
inline: true,
},
);
}
con.all(`SELECT * FROM warnings WHERE username = ? AND userID = ?`, User.tag, User.id, (err, rows) => {
const replyMessages = rows.map((r) => warningRowToMessage(User, r));
if (!replyMessages.length) {
message.channel.send("NO U");
return;
}
message.delete({
timeout: 3000,
});
replyMessages.forEach(async (replyMessage) => {
const msg = await message.channel.send(replyMessage);
msg.delete({
timeout: 15000,
});
});
});

Categories