I'm working on something and I need to add ban logging, I tried something but it doesn't send anything.
Any help would be appreciated!
client.on('guildBanAdd', async (guild, user) => {
let Banch = await client.channels.cache.get('ID')
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_BAN_ADD',
});
const banLog = fetchedLogs.entries.first();
if (!banLog) return console.log(`${user.tag} was banned from ${guild.name} but no audit log could be found.`);
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `\n${username}`)
Banch.send(embed)
}
);
This should work
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildBanAdd', async (guild, user) => {
const banned = await guild.fetchAuditLogs({
type: 'MEMBER_BAN_ADD',
limit: 1
});
const channel = client.channels.cache.get('ID');
if(!channel) return console.log(`Channel was not found!`);
const userbanned = banned.entries.first();
const { executor, target } = userbanned; // get the user who banned the user and the user that got banned
if(target.id !== user.id) return console.log(`Invalid data in the audit logs!`); // check if the user that got banned in the Audit Logs is the user that is banned
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `${target.username}`);
channel.send(embed).catch(err => {
console.log(err);
});
});
Related
The following code just gives me an error message that the command is outdated when I try to use it in Discord, anyone know why?
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('purge')
.setDescription('Purge an amount of messages from a channel.')
.addIntegerOption((option) => {
return option
.setName('amount')
.setDescription('The amount of messages to purge.')
.setRequired(true)
}),
run: async (client, message, args) => {
const amount = args.amount;
if (amount > 100) {
return message.channel.send(`${message.author}, you can only purge up to 100 messages at a time.`);
}
const fetched = await message.channel.messages.fetch({ limit: amount });
message.channel.bulkDelete(fetched);
const embed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Purge')
.setDescription(`Purged ${amount} messages.`)
.setTimestamp();
message.channel.send(embed);
}
};
I'm kinda getting tired of this command just not working for some reason or another.
I am working on an advanced suggestion command and here's my code so far:
if (command === 'accept') {
try {
const suggestionchan = bot.channels.cache.get('840493081659834403');
const acceptreason = message.content.split(' ')[2];
if(!acceptreason) return message.lineReply("Please provide the reason!")
const messageid = message.content.split(' ')[1];
console.log(messageid)
if(!messageid) return message.lineReply("Please provide the message id of the suggestion!")
const suggestionData = suggestionchan.messages.fetch(messageid)
const suggestionembed = suggestionData.embeds[0];
const acceptembed = new Discord.MessageEmbed()
.setAuthor(suggestionembed.author.name, suggestionembed.author.iconURL)
.setTitle("Suggestion!")
.setDescription(suggestionembed.description)
.setColor("GREEN")
.addFields(
{ name: `Accepted by ${message.author.tag}`, value: `**Reason:**\n${acceptreason}`}
)
.setFooter("Bot made by Sɱαɾƚx Gαɱιɳɠ YT")
suggestionembed.edit(acceptembed)
message.delete();
const user = bot.users.cache.find( (u) => u.tag === suggestionembed.author.name);
user.send(acceptembed)
} catch (err) { console.log(err)
message.lineReply("That message ID is not a valid ID!")}
}
I am getting an error on the part suggestionembed = suggestionData.embeds[0];
The error is TypeError: Cannot read property '0' of undefined at Client.<anonymous>
suggestionchan.messages.fetch returns a promise, so you'll need to resolve it first. You can either use the .then() method or the await keyword (as below).
It's also a good idea to check if the fetched message have any embeds.
if (command === 'accept') {
try {
const suggestionChannel = bot.channels.cache.get('840493081659834403');
const acceptReason = message.content.split(' ')[2];
if (!acceptReason)
return message.lineReply('Please provide the reason!');
const messageId = message.content.split(' ')[1];
if (!messageId)
return message.lineReply('Please provide the message id of the suggestion!');
const suggestionData = await suggestionChannel.messages.fetch(messageId);
const suggestionEmbed = suggestionData.embeds[0];
if (!suggestionEmbed)
return message.lineReply(`The message with ID ${messageId} doesn't have any embeds!`);
const acceptEmbed = new Discord.MessageEmbed()
.setAuthor(suggestionEmbed.author.name, suggestionEmbed.author.iconURL)
.setTitle('Suggestion!')
.setDescription(suggestionEmbed.description)
.setColor('GREEN')
.addFields({
name: `Accepted by ${message.author.tag}`,
value: `**Reason:**\n${acceptReason}`,
})
.setFooter('Bot made by Sɱαɾƚx Gαɱιɳɠ YT');
suggestionData.edit(acceptEmbed);
message.delete();
const user = bot.users.cache.find(
(u) => u.tag === suggestionEmbed.author.name,
);
user.send(acceptEmbed);
} catch (err) {
console.log(err);
message.lineReply('That message ID is not a valid ID!');
}
}
This is my setuplogger.js file, and the bottom part is the code I have in my index.js. This code is supposed to create a webhook for the channel set as the logschannel, this webhook will send logs for every ban that happens in the guild. But the problem is that I keep getting the .createWebhook is not a function, I couldn't figure out how to fix this error so I just came here.
if (!message.member.hasPermission("ADMINISTRATOR")) {
return message.channel.send(`***Error:*** *You do not have* ***[ADMINISTRATOR]*** *permission.*`);
}
const logEnableDisable = args[0];
const logChannel = message.mentions.channels.first();
if (!logEnableDisable) {
return message.channel.send(`***Error:*** *${prefix}setuplogger <enable/disable> <channel>*`)
}
if (!logChannel) {
return message.channel.send(`***Error:*** *${prefix}setuplogger <enable/disable> <channel>*`)
}
if (logEnableDisable === 'enable') {
db.set(`${message.guild.id}_logChannel`, logChannel.id)
message.channel.send(`*Succesfully enabled logs to* ***${logChannel}.***`)
}
if (logEnableDisable === 'disable') {
const findLogchannel = db.get(`${message.guild.id}_logChannel`);
if (!findLogchannel) {
message.channel.send(`***Error:*** *Log channel has not been setup yet, use \`${prefix}setuplogger enable <channel>\`.*`)
} else {
db.delete(`${message.guild.id}_logChannel`, true)
message.channel.send(`*Succesfully removed logs from* ***${logChannel}.***`)
}
}
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
client.on("guildBanAdd", async (guild, user) => {
const channel = db.get(`${guild.id}_logChannel`);
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: "MEMBER_BAN_ADD",
});
const banLog = fetchedLogs.entries.first();
if(!banLog) return console.log("It doesn't work.")
const { executor, target } = banLog;
if (target.id === user.id) {
const embed = new Discord.MessageEmbed()
.setTitle('Ban')
.setDescription(`**User Banned**\fModerator: ${executor}\fUser: ${target.tag}`)
.setTimestamp()
.setColor(color);
channel.createWebhook('Logger', { avatar: 'https://cdn2.iconfinder.com/data/icons/basic-ui-elements-circle/512/notepad_note_wrrte_pencil-512.png' }).then(webhook => { webhook.send(embed) });
}
});
It seems you're saving the channel's ID in the database (logChannel.id) and later, you're trying to call the createWebhook method on a string, not the channel. If you call a non-existing method on a string you'll receive an error; "channel.createWebhook is not a function":
const channel = '86924931458913231434'
const webhook = channel.createWebhook('Logger')
To solve this, you need to fetch the channel first so you can use the createWebhook method:
client.on('guildBanAdd', async (guild, user) => {
const channelID = db.get(`${guild.id}_logChannel`);
if (!channelID) return console.log('No channel ID');
try {
const channel = await client.channels.fetch(channelID);
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_BAN_ADD',
});
const banLog = fetchedLogs.entries.first();
if (!banLog) return console.log("It doesn't work.");
const { executor, target } = banLog;
if (target.id === user.id) {
const embed = new Discord.MessageEmbed()
.setTitle('Ban')
.setDescription(
`**User Banned**\fModerator: ${executor}\fUser: ${target.tag}`,
)
.setTimestamp()
.setColor(color);
const webhook = await channel.createWebhook('Logger', {
avatar:
'https://cdn2.iconfinder.com/data/icons/basic-ui-elements-circle/512/notepad_note_wrrte_pencil-512.png',
});
webhook.send(embed);
}
} catch (error) {
console.log(error);
}
});
So i make a application system for a discord server and when testing it the bot worked fine till the questiosn for the application finished and it said application has been sent but it didnt send the application and i got a error saying
(node:11408) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
Here is my code The error is on appsChannel.send(applicationembed);
const { Client, Message, MessageEmbed } = require('discord.js')
module.exports = {
name: "apply",
/**
* #param {Client} client
* #param {Message} message
* #param {string[]} args
*/
run: async (client, message, args) => {
const questions = [
"What is your IGN currently?",
"What is your discord Name and Tag?",
"Why do you want to join the guild?",
"What games stats are you applying with?",
"Is there anything else you want to tell us?"
];
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);
collector.on("collect", () => {
if(collectCounter < questions.length) {
channel.send(questions[collectCounter++])
} else {
channel.send("You application has been sent!")
collector.stop("fulfilled")
}
})
const appsChannel = client.channels.cache.get('820355472635985991')
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');
const applicationembed = new MessageEmbed()
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: ture })
)
.setTitle('New Application!')
.setDescription(mappedResponses)
.setColor('RANDOM')
.setTimestamp()
appsChannel.send(applicationembed);
}
})
},
}
It's possible that the channel you're trying to get is not in the cache. It's always best to fetch rather than rely on the cache.
Change your appsChannel definition to this.
const appsChannel = await client.channels.cache.fetch('820355472635985991');
Can you try using await here?
const appsChannel = await client.channels.cache.get('820355472635985991')
Edit:
const applicationembed = await new MessageEmbed()
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: ture })
)
.setTitle('New Application!')
.setDescription(mappedResponses)
.setColor('RANDOM')
.setTimestamp()
await appsChannel.send(applicationembed);
For your async to work:
collector.on('end', async (collected, reason) => {
How can I make multi-word argumet. For example a reason for bans or mutes.If I use args[2], args[3], args[4], args[5]... so it's still limited and if nothing is written there, it will write "undefined". So if you knew how to do it, I would be very happy for the answer. :)
const { ReactionCollector } = require("discord.js");
module.exports = {
name: 'ban',
description: "Dočasně zabanuje člena.",
async execute(message, args, Discord, client, chalk, ms){
await message.channel.messages.fetch({limit: 1}).then(messages =>{
message.channel.bulkDelete(messages);
});
const channelId = client.channels.cache.get('802649418087530537');
const author = message.author;
const userName = message.mentions.users.first();
if(!message.member.permissions.has("BAN_MEMBERS")){
message.reply('Nemáš potřebné permisse!')
.then(msg => {
msg.delete({ timeout: 5000 })
});
return;
} else if(!args[1]){
message.reply('!ban <člen> <délka> (<důvod>)')
.then(msg => {
msg.delete({ timeout: 5000 })
});
console.log(chalk.red('[ERROR] Missing args[1]'));
return;
}
if(userName){
const userId = message.guild.members.cache.get(userName.id);
const botId = '799652033509457940';
userId.ban();
const banEmbed = new Discord.MessageEmbed()
.setColor('#a81919')
.setTitle('Ban')
.addFields(
{name:'Člen:', value:`${userId}`},
{name:'Udělil:', value:`${author}`},
{name:'Délka:', value:`${ms(ms(args[1]))}`},
{name:'Důvod:', value:`${args[2]}`},
)
.setTimestamp()
channelId.send(banEmbed)
setTimeout(function () {
message.guild.members.unban(userId);
const unbanEmbed = new Discord.MessageEmbed()
.setColor('#25a819')
.setTitle('Unban')
.addFields(
{name:'Člen:', value:`${userId}`},
{name:'Udělil:', value:`<#${botId}>`},
{name:'Důvod:', value:`Ban vypršel.`},
)
.setTimestamp()
channelId.send(unbanEmbed)
}, ms(args[1]));
console.log(chalk.green(`[INFO] /ban/ ${userId.user.username}, ${ms(ms(args[1]))}`));
}else{
message.channel.send('Nemůžeš zabanovat tohoto člena');
console.log(chalk.red(`[ERROR] /ban/ Can not find target`));
}
}
}
I am assuming that you have defined args correctly. Then you can simply use
args.join(" ");
to seperate each word with spaces.