Banned and kicked logs - javascript

I made a ban and kick script and it's working, but when a user gets a ban, the bot sends a ban and a kick message (even if the user gets a ban). I want it to send only the ban message when the user receives the ban, and the kick message only when the user receives a kick.
client.on(Events.GuildBanRemove, async (ban) => {
const fetchedLogs = await ban.guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.MemberBanRemove,
});
const unbanLog = fetchedLogs.entries.first();
const { executor, target } = unbanLog;
if (target.id === ban.user.id) {
const channel2 = client.channels.cache.get("1026979529387950132");
const embed2 = new Discord.EmbedBuilder()
.setColor("#10fee4")
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setTitle(`Log | Usuario Desbanido.`)
.setDescription(`**Informações do usuario:**\n > Membro:${ban.user}\n > ID:\`${ban.user.id}\`\n\n**Informações do unban**:\n > Desbanido por: ${executor}\n> ID:\`${executor.id}\``)
.setFooter({ text: `© ${client.user.username} 2023` })
.setTimestamp(new Date());
channel2.send({ embeds: [embed2] });
}
});
client.on(Events.GuildMemberRemove, async (member) => {
const fetchedLogs2 = await member.guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.MemberKick,
});
const kickLog = fetchedLogs2.entries.first();
const { executor, target } = kickLog;
if (target.id === member.id) {
const channel3 = client.channels.cache.get("1026979529387950132");
const embed3 = new Discord.EmbedBuilder()
.setColor("#10fee4")
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setTitle(`Log | Usuario Expulso.`)
.setDescription(`**Informações do usuario:**\n > Membro:${member.user}\n > ID:\`${member.user.id}\`\n\n**Informações da expulsão:**\n > Expulso por: ${executor}\n> ID:\`${executor.id}\``)
.setFooter({ text: `© ${client.user.username} 2023` })
.setTimestamp(new Date());
channel3.send({ embeds: [embed3] });
}
});

Related

Discord.js: TypeError: Cannot read properties of undefined (reading 'hello')

I am creating a Discord command handler using discord.js version 14.4.0 but I keep getting this error, here is my code:
const settings = require(`${process.cwd()}/config/settings.json`);
const ee = require(`${process.cwd()}/config/embed.json`);
const colors = require("colors");
const Discord = require("discord.js");
module.exports = {
name: "hello",
description: "say hello!",
cooldown: settings.cooldown,
memberpermissions: [],
requiredroles: [],
alloweduserids: [],
type: Discord.ApplicationCommandType.ChatInput,
options: [],
run: async (client, interaction) => {
try {
interaction.reply({ content: `${client.word.hello}` });
} catch (error) {
console.log(colors.red(error));
let somethingWrong = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| Something wrong!")
.setDescription(`❌| Sorry, I failed setting up...!`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [somethingWrong], ephemeral: true });
}
}
};
The error I get when running that command:
interaction.reply({ content: `${client.word.hello}` });
and this my index.js file:
const lang_db = require("./dataBases/db");
const dotenv = require("dotenv"); dotenv.config();
const colors = require("colors");
const fs = require("fs");
const Discord = require("discord.js");
const client = new Discord.Client({
intents: [32767],
partials: [
Discord.Partials.GuildScheduledEvent,
Discord.Partials.ThreadMember,
Discord.Partials.GuildMember,
Discord.Partials.Reaction,
Discord.Partials.Channel,
Discord.Partials.Message,
Discord.Partials.User,
],
});
client.slashCommands = new Discord.Collection();
module.exports = client;
fs.readdirSync("./handlers").forEach((handler) => {
require(`./handlers/${handler}`)(client);
});
client.on("interactionCreate", async (interaction) => {
let lang = await lang_db.get(`language_${interaction.guild.id}`);
if(lang == null) {
lang = "en";
} else if(lang == "ar") {
lang = "ar"
}
let word = require(`./languages/${lang}.json`);
client.word = word;
});
client.login(process.env.TOKEN).catch((error) => {
console.log(colors.red(error));
});
TypeError: Cannot read properties of undefined (reading 'hello')
handlers/slashCommand.js
const colors = require("colors");
const fs = require("fs");
const AsciiTable = require("ascii-table");
const table = new AsciiTable().setHeading("Slash Commands", "Stats").setBorder("|", "=", "0", "0");
const { Routes } = require("discord-api-types/v9");
const { REST } = require("#discordjs/rest");
const Discord = require("discord.js");
const APPLICATION_ID = process.env.APPLICATION_ID;
const TOKEN = process.env.TOKEN;
const rest = new REST({ version: "10" }).setToken(TOKEN);
module.exports = (client) => {
const slashCommands = [];
fs.readdirSync("./slashCommands/").forEach(async (dir) => {
const files = fs.readdirSync(`./slashCommands/${dir}/`).filter((file) => file.endsWith(".js"));
for (const file of files) {
const slashCommand = require(`../slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
type: slashCommand.type,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? Discord.PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null,
});
if (slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split(".js")[0], "✅");
} else {
table.addRow(file.split(".js")[0], "⛔");
}
}
});
console.log(colors.green(table.toString()));
(async () => {
try {
const data = await rest.put(process.env.GUILD_ID ? Routes.applicationGuildCommands(APPLICATION_ID, process.env.GUILD_ID) : Routes.applicationCommands(APPLICATION_ID), { body: slashCommands });
console.log(colors.green(`Started refreshing ${slashCommands.length} application (/) commands.`));
console.log(colors.green(`Successfully reloaded ${data.length} application (/) commands.`));
} catch (error) {
console.log(colors.red(error));
}
})();
};
events/guid/interactionCreate.js
const ee = require(`${process.cwd()}/config/embed.json`);
const colors = require("colors");
const ms = require("ms");
const Discord = require("discord.js");
const client = require("../..");
const delay = new Discord.Collection();
client.on("interactionCreate", async (interaction) => {
const slashCommand = client.slashCommands.get(interaction.commandName);
if (interaction.type == 4) {
if (slashCommand.autocomplete) {
const choices = [];
await slashCommand.autocomplete(interaction, choices);
}
}
if (!interaction.type == 2) return;
if (!slashCommand)
return client.slashCommands.delete(interaction.commandName);
try {
if (slashCommand.cooldown) {
if (delay.has(`${slashCommand.name}-${interaction.user.id}`)) {
let time = ms(delay.get(`${slashCommand.name}-${interaction.user.id}`) - Date.now(), { long: true }).includes("ms") ? "0 second" : ms(delay.get(`${slashCommand.name}-${interaction.user.id}`) - Date.now(), { long: true });
let timeLeft = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| Please wait **${time}** before reusing the \`${slashCommand.name}\` command!`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [timeLeft], ephemeral: true });
}
}
if (slashCommand.memberpermissions && slashCommand.memberpermissions.length > 0 && !interaction.member.permissions.has(slashCommand.memberpermissions)) {
let memberPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need these Permission(s): \`${slashCommand.memberpermissions}\``)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [memberPerms], ephemeral: true });
}
if (slashCommand.requiredroles && slashCommand.requiredroles.length > 0 && interaction.member.roles.cache.size > 0 && !interaction.member.roles.cache.some(r => slashCommand.requiredroles.includes(r.id))) {
let rolesPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need to have one of the Following Roles: <#&${slashCommand.requiredroles}>`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [rolesPerms], ephemeral: true });
}
if (slashCommand.alloweduserids && slashCommand.alloweduserids.length > 0 && !slashCommand.alloweduserids.includes(interaction.member.id)) {
let userPerms = new Discord.EmbedBuilder()
.setColor(ee.colors.Red)
.setTitle("❌| You are not allowed to run this command!")
.setDescription(`❌| You need to be one of the Following Users: <#!${slashCommand.alloweduserids}>`)
.setFooter({ text: `${interaction.guild.name}`, iconURL: interaction.guild.iconURL() })
return interaction.reply({ embeds: [userPerms], ephemeral: true });
}
await slashCommand.run(client, interaction);
delay.set(`${slashCommand.name}-${interaction.user.id}`, Date.now() + slashCommand.cooldown * 1000);
setTimeout(() => {
delay.delete(`${slashCommand.name}-${interaction.user.id}`);
}, slashCommand.cooldown * 1000);
} catch (error) {
console.log(colors.red(error));
}
});
I don't know why this is happening, please could someone help me?

Discord Embed Command Cooldown

im trying to create a cooldown for my status command, because they spam a lot on the server the status command and i want a cooldown like 5m and that send a message like, "you need to wait 5m more to use this command im really newbie to javascript, so if anyone can help me
Here its my entire command:
const Discord = require("discord.js");
const yaml = require("js-yaml");
const supportbot = yaml.load(
fs.readFileSync("./Configs/supportbot.yml", "utf8")
);
const cmdconfig = yaml.load(fs.readFileSync("./Configs/commands.yml", "utf8"));
const Command = require("../Structures/Command.js");
const { timeStamp } = require("console");
var request = require('request');
const Gamedig = require('gamedig');
let state = null;
setInterval(() => {
Gamedig.query({
type: 'minecraft',
host: 'mc.latinplay.net',
port: '25565'
})
.then((updatedState) => {
state = updatedState;
players = state.players.length;
}).catch((error) => {
console.log("Server is offline");
});
}, 6000);
module.exports = new Command({
name: cmdconfig.EstadoCommand,
description: cmdconfig.EstadoCommandDesc,
async run(interaction) {
const LatinEstado = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('𝐋𝐚𝐭𝐢𝐧𝐏𝐥𝐚𝐲 𝐍𝐞𝐭𝐰𝐨𝐫𝐤 **Estado del Servidor**')
.setURL("https://store.latinplay.net/")
.addField('**Jugadores en linea:**', `${players || "0"}`)
.addField('**Estado Actual:**', "**En Linea💚**", true)
.setThumbnail('https://media0.giphy.com/media/5RQ6coK6GVXGfPPq69/giphy.gif?cid=790b76115867f0dba05d9cf2aceb80efed5b0e494387e3b2&rid=giphy.gif&ct=g')
.setFooter({ text: 'LatinBot | Version 1.0 ', iconURL: 'https://cdn.discordapp.com/attachments/953043417234026547/988805760458821642/Diseno_sin_titulo.png' });
interaction.reply({
embeds: [LatinEstado],
});
}
},
);```
Just store last command run time in a map.
const cooldown={}; // Add this
...
module.exports = new Command({
name: cmdconfig.EstadoCommand,
description: cmdconfig.EstadoCommandDesc,
async run(interaction) {
//
if (interaction.user.id in cooldown && cooldown[interaction.user.id] - Date.now() > 0) // in cool down
return interaction.reply("In cooldown! Please wait 5 min!");
cooldown[interaction.user.id] = Date.now() + 300000; // 5 min in ms.
//
const LatinEstado = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('𝐋𝐚𝐭𝐢𝐧𝐏𝐥𝐚𝐲 𝐍𝐞𝐭𝐰𝐨𝐫𝐤 **Estado del Servidor**')
.setURL("https://store.latinplay.net/")
.addField('**Jugadores en linea:**', `${players || "0"}`)
.addField('**Estado Actual:**', "**En Linea💚**", true)
.setThumbnail('https://media0.giphy.com/media/5RQ6coK6GVXGfPPq69/giphy.gif?cid=790b76115867f0dba05d9cf2aceb80efed5b0e494387e3b2&rid=giphy.gif&ct=g')
.setFooter({
text: 'LatinBot | Version 1.0 ',
iconURL: 'https://cdn.discordapp.com/attachments/953043417234026547/988805760458821642/Diseno_sin_titulo.png'
});
interaction.reply({
embeds: [LatinEstado],
});
}
});

Discord.js V13 player.getQueue() returns undefined even tho a queue exists

I'm creating a discord bot with queue system. A queue is created in play.js file. The queue is then fetched in skip.js using player.getQueue() method to be able to skip songs. However, it returns undefined meaning no queue was found.
I know for a fact a queue exist because I logged it in the console but somehow this methode can't find it.
play.js Code :
const { SlashCommandBuilder } = require('#discordjs/builders');
const { Player, QueryType } = require('discord-player');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('plays music')
.addStringOption(option => option
.setName("song")
.setDescription("what to play")
.setRequired(true)),
async execute(interaction, Discord) {
const voice_channel = interaction.member.voice.channel;
const bot_channel = interaction.guild.me.voice.channel;
if (!voice_channel) {
await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setDescription('You need to be in a voice channel to play music!')],
ephemeral: true
});
}
if (bot_channel && bot_channel.id != voice_channel.id) {
await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setDescription(`I'm already connected on ${bot_channel.toString()}`)],
ephemeral: true
});
}
const song = interaction.options.getString("song");
const player = new Player(interaction.client);
const searchResult = await player.search(song, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
}).catch(() => { });
if (!searchResult || !searchResult.tracks.length) {
return interaction.reply({ content: 'No music found!', ephemeral: true });
}
const queue = player.createQueue(interaction.guild);
queue.options.initialVolume = 50;
queue.options.leaveOnEmptyCooldown = 5000;
try {
if (!queue.connection) await queue.connect(voice_channel);
} catch {
void player.deleteQueue(interaction.guildId);
return void interaction.reply({ content: "Could not join your voice channel!", ephemeral: true });
}
searchResult.playlist ? queue.addTracks(searchResult.tracks) : queue.addTrack(searchResult.tracks[0]);
if (!queue.playing) {
await queue.play().then(queue.playing = true);
// console.log(queue);
}
const row = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('pause')
.setLabel('⏸')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('resume')
.setLabel('▶')
.setStyle('PRIMARY'),
);
const play_embed = await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setTitle(`${queue.nowPlaying().title}`)
.setURL(`${queue.nowPlaying().url}`)
.setThumbnail(`${queue.nowPlaying().thumbnail}`)
.setAuthor({ name: ` | Now Playing`, iconURL: `https://imgur.com/krzRxsN.png` })
.addField('Duration :', `\`${queue.nowPlaying().duration}\``, true)
.addField('Author :', `\`${queue.nowPlaying().author}\``, true)
.setTimestamp()
.setFooter({ text: `Requested By ${interaction.user.username}`, iconURL: `${interaction.user.displayAvatarURL()}` })
],
// components: [row]
});
}
}
skip.js Code :
const { SlashCommandBuilder } = require('#discordjs/builders');
const { Player, QueryType } = require('discord-player');
module.exports = {
data: new SlashCommandBuilder()
.setName('skip')
.setDescription('skips to the next music in queue'),
async execute(interaction, Discord) {
await interaction.deferReply();
const player = new Player(interaction.client);
console.log(player.queues);
const queue = player.getQueue(interaction.guildId);
// console.log(queue);
if (!queue || !queue.playing) return void interaction.followUp({ content: "❌ | No music is being played!" });
const currentTrack = queue.current;
const success = queue.skip();
return void interaction.followUp({
content: success ? `✅ | Skipped **${currentTrack}**!` : "❌ | Something went wrong!"
});
}
}
In index.js ,
client.player = new Player(client);
In execute function, pass client as an argument.
execute({interaction, client})
In skip.js, While getting the queue, Try this--
const queue = await client.player.getQueue(interaction.guildId)

How to add reactions to an embed message

const { Client, Message, MessageEmbed, Intents } = require("discord.js");
module.exports = {
name: "sbfeedback",
/**
* #parom {Client} client
* #parom {Message} message
* #parom {String[]} args
*/
async execute(client, message, args) {
const questions = [
"What feedback would you like to give?",
"Anything else you would like to add?"
];
let collectCounter = 0;
let endCounter = 0;
const filter = (m) => m.author.id === message.author.id;
const appStart = await message.author.send(questions[collectCounter++]);
const channel = appStart.channel;
const collector = channel.createMessageCollector(filter);
message.delete({timeout: 100})
collector.on("collect", () => {
if (collectCounter < questions.length) {
channel.send(questions[collectCounter++]);
} else {
channel.send("Thank you for your feedback! If you would like to suggest anything else please do so with `-sbfeedback`.");
collector.stop("fulfilled");
}
});
const appsChannel = client.channels.cache.get("886099865094983691");
collector.on("end", (collected, reason) =>{
if (reason === "fulfilled") {
let index = 1;
const mappedResponses = collected
.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join("\n\n");
appsChannel.send(
new MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true}))
.setTitle("!")
.setDescription(mappedResponses)
.setColor(`RANDOM`)
.setTimestamp()
);
message.react('👍').then(() => message.react('👎'));
}
});
},
appsChannel.send returns a Promise and once it's resolved, you can grab the sent message, so you can add your reactions:
collector.on('end', (collected, reason) => {
if (reason === 'fulfilled') {
let index = 1;
const mappedResponses = collected
.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join('\n\n');
appsChannel
.send(
new MessageEmbed()
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: true }),
)
.setTitle('!')
.setDescription(mappedResponses)
.setColor(`RANDOM`)
.setTimestamp(),
)
.then((sent) => {
sent.react('👍');
sent.react('👎');
});
}
});

Problem with sending text from yaml Discord.js

i have a problem sending text from yaml. Saving text works but sending does not. Here's the code:
const { Message, MessageEmbed } = require("discord.js")
const { channel } = require('./kanal')
const db = require('quick.db')
module.exports = {
name: "reklama",
guildOnly: true,
description:
"Change guild prefix. If no arguments are passed it will display actuall guild prefix.",
usage: "[prefix]",
run(msg, args, guild) {
if (!guild) {
const guld = new MessageEmbed()
.setTitle("Błąd!")
.setColor("RED")
.setDescription("Tą komende można tylko wykonać na serwerze!")
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(`${msg.author.tag} (${msg.author.id})`, `${msg.author.displayAvatarURL({dynamic: true})}`)
msg.channel.send(guild)
}
const { settings } = client
const prefixArg = args[0]
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null })
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama
let Kanal = client.settings.get(guild.id).Kanał
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField("Treść reklamy:", Reklama)
.addField("Kanał do wysyłania reklam:", Kanal)
msg.channel.send(embed)
}
setInterval(() => {
Kanal.send(`${Reklama}`)
}, 1000)
},catch(e){
console.log(e)
}
}
Here is a part of command handler:
const args = msg.content.slice(length).trim().split(" ")
const cmdName = args.shift().toLowerCase()
const cmd =
client.commands.get(cmdName) ||
client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(cmdName),
)
try {
cmd.run(msg, args)
} catch (error) {
console.error(error)
}
})
}
The problem is that when I start the bot, it shows me such an error:
let Reklama = client.settings.get(guild.id).Reklama
^
TypeError: Cannot read property 'id' of undefined
The problem is you don't pass the guild variable to your run method. You call cmd.run(msg, args) but run accepts three parameters.
You can either pass the guild or get it from the msg like this:
module.exports = {
name: 'reklama',
guildOnly: true,
description:
'Change guild prefix. If no arguments are passed it will display actuall guild prefix.',
usage: '[prefix]',
run(msg, args) {
// destructure the guild the message was sent in
const { guild } = msg;
if (!guild) {
const embed = new MessageEmbed()
.setTitle('Błąd!')
.setColor('RED')
.setDescription('Tą komende można tylko wykonać na serwerze!')
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(
`${msg.author.tag} (${msg.author.id})`,
`${msg.author.displayAvatarURL({ dynamic: true })}`,
);
return msg.channel.send(embed);
}
const { settings } = client;
const prefixArg = args[0];
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null });
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama;
let Kanal = client.settings.get(guild.id).Kanał;
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField('Treść reklamy:', Reklama)
.addField('Kanał do wysyłania reklam:', Kanal);
msg.channel.send(embed);
}
setInterval(() => {
Kanal.send(`${Reklama}`);
}, 1000);
},
catch(e) {
console.log(e);
},
};

Categories