Discord.js channelUpdate event, ignore certain channels - discord.js

Hello Stackoverflow community. I'm quite curious, regarding the channelUpdate event in Discord.js, is it possible to ignore some channels but log the rest?
bot.on("channelUpdate", async (oldChannel, newChannel) => {
// Get stat channel IDs
let totalUsers = oldChannel.guild.channels.get('667335552558956554');
let onlineUsers = oldChannel.guild.channels.get('667335645894541331');
let totalBots = oldChannel.guild.channels.get('667337560179343374');
//Leave the stat channels alone, or too much logging will happen
//.parent.id === '667335310350352394';
if (totalUsers || onlineUsers || totalBots) return;
let oldCategory = oldChannel.parent;
let newCategory = newChannel.parent;
let guildsChannel = newChannel.guild;
if (!newCategory) newCategory = "None";
if (!guildsChannel || !guildsChannel.available) return;
let types = {
"text" : "Text channel",
"voice" : "Voice channel",
"null" : "None"
};
const logchannel = channel.guild.channels.find(channel => channel.name === "server-logs")
if (!logchannel) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('VIEW_CHANNEL')) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('SEND_MESSAGES')) return;
if (oldChannel.name !== newChannel.name) {
let channelNameUpdateEmbed = new Discord.RichEmbed()
.setColor("#ffc500")
.setDescription("Channel name updated.")
.addField("Old channel name", `\`${oldChannel.name}\``, true)
.addBlankField(true)
.addField("New channel name", `\`${newChannel.name}\``, true)
.addField("Channel type", `${types[newChannel.type]}`, true)
.addBlankField(true)
.addField("Channel category", `${newCategory}`, true)
.setFooter(`Channel ID: ${newChannel.id} 🔥`)
.setTimestamp()
logchannel.send(channelNameUpdateEmbed).catch()
}
});
Those marked as so called "Stat channels", is it possible to ignore those? Else log channels will get flooded every time a member goes online or offline
Thanks in advance!

Sure, you can create ingoreChannel arr and check if channel in ignore arr.
Like this:
bot.on('channelUpdate', async (oldChannel, newChannel) => {
const ignoreChannels = ['667335552558956554', '667335645894541331', '667337560179343374'];
// Get stat channel IDs
if (ignoreChannels.includes(oldChannel.id)) return;
//Leave the stat channels alone, or too much logging will happen
//.parent.id === '667335310350352394';
let oldCategory = oldChannel.parent;
let newCategory = newChannel.parent;
let guildsChannel = newChannel.guild;
if (!newCategory) newCategory = 'None';
if (!guildsChannel || !guildsChannel.available) return;
let types = {
text: 'Text channel',
voice: 'Voice channel',
null: 'None',
};
const logchannel = channel.guild.channels.find(channel => channel.name === 'server-logs');
if (!logchannel) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('VIEW_CHANNEL')) return;
if (!logchannel.permissionsFor(oldChannel.guild.me).has('SEND_MESSAGES')) return;
if (oldChannel.name !== newChannel.name) {
let channelNameUpdateEmbed = new Discord.RichEmbed()
.setColor('#ffc500')
.setDescription('Channel name updated.')
.addField('Old channel name', `\`${oldChannel.name}\``, true)
.addBlankField(true)
.addField('New channel name', `\`${newChannel.name}\``, true)
.addField('Channel type', `${types[newChannel.type]}`, true)
.addBlankField(true)
.addField('Channel category', `${newCategory}`, true)
.setFooter(`Channel ID: ${newChannel.id} 🔥`)
.setTimestamp();
logchannel.send(channelNameUpdateEmbed).catch();
}
});

Related

discord.js v12 | TypeError: Cannot read property 'send' of undefined

Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.

What's the prefix for mute

Problems with my bot. Can't get mute to work. Help? Can't find any prefix and don't know where to add it or how to format it. I linked most of code below. Anti-spam and kick/ban works. New to coding to any help would be nice. Tips how set a general prefix for all code foward? Role is named mute and bot has all premissons it shall need to kick
const fs = require('fs');
module.exports = class mute {
constructor(){
this.name = 'mute',
this.alias = ['tempmute'],
this.usage = 'mute';
}
run(bot, message, args){
let member = message.mentions.members.first();
var command = args[0];
var mentioned = args[1];
var days = parseInt(args[3]);
var hours = parseInt(args[4]);
var seconds = parseInt(args[5]);
if (message.member.hasPermission('MANAGE_ROLES')) {
let muterole = message.guild.roles.find(role => role.name === "Muted");
if (!message.guild) {
if (message.guild.id === '505872328538718233') {
let memberrole = message.guild.roles.find("name", "Member");
member.removeRole(memberrole);
}}
let usermsg = new Discord.RichEmbed();
usermsg.setTitle('You have been Muted.');
usermsg.setColor('76b3fc');
usermsg.setFooter('Please do not attempt to bypass');
usermsg.addField('Muted by:',
`<#${message.author.id}>`);
let mutedmsg = new Discord.RichEmbed();
mutedmsg.setTitle('User has been Muted Successfully');
mutedmsg.setColor('76b3fc');
mutedmsg.setDescription(`User muted: ${mentioned}\nMuted by: <#${message.author.id}>\nReason: ${input}`);
mutedmsg.setFooter('This mute has been logged.');
if (message.content === `${command}`) {
return message.channel.send('You did not provide a member to mute.');
}
if (message.content === `${command} ${mentioned}`) {
return message.channel.send('Please input a reason for the mute.');
}
if (message.guild.roles.find(role => role.name)) {
message.member.addRole(muterole);
if (message.content.includes (`${days}d`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${hours} Seconds`);
}, `${args[2]} * 86400`);
}
if (message.content.includes (`${hours}h`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${hours} Seconds`);
}, `${args[3]} * 3600`);
}
if (message.content.includes (`${seconds}s`)) {
message.channel.send(mutedmsg);
setTimeout(() => {
member.removeRole(muterole);
usermsg.addField('Punishment Time:',
`${seconds} Seconds`);
}, `${args[4]} * 1000`);
}
if (message.content === `${command} ${mentioned} ${input}`) {
message.member.addRole(muterole);
usermsg.addField('Muted for',
`${input}`);
usermsg.addField('Punishment Time:',
'Permenant');
message.channel.send(mutedmsg);
}
if (message.member.id === `${message.author.id}`) {
return;
}
if (message.author.id === `${mentioned}`) {
return message.member.send(usermsg);
}
message.channel.send(mutedmsg);
console.log('===========================');
console.log(`Member Muted: ${mentioned}`);
console.log(`Muted by: ${message.author.tag}`);
console.log(`Reason: ${input}`);
console.log('===========================');
} else {
message.channel.send('You do not have a `Muted` Role, This command won\'t work.');
}
} else {
message.reply('You do not have permission to do this.');
}
let jsonlogs = JSON.parse(fs.writeFileSync("./storages/mutelogs.json"));
if (!jsonlogs[message.guild.id]){
jsonlogs[message.guild.id] = {
mutedby: `${message.author.tag}`,
user: `${mentioned}`,
reason: `${input}`,
days: `${days}`,
hours: `${hours}`,
seconds: `${seconds}`,
};
}
}
};
You seem to have a lot, and I mean A LOT of outdated methods from Discord.js v11.
I'd highly recommend installing the newest version of DJS and reading all of the v12 changes that can be found here:
https://github.com/discordjs/discord.js/releases/tag/12.0.0
Some examples:
Discord.RichEmbed() no longer exists -> Use Discord.MessageEmbed()
.addRole() no longer exists -> Use message.member.roles.add()
.removeRole() no longer exists -> Use message.member.roles.remove()

SlowMode for one person is possible ? discord.js

I would like to know if it is possible to do some sort of "SlowMode" for a specific person on Discord.
The reason is that I have a "spammer" friend, and I would like to calm him down with a command that might slow him down when he speaks for "x" secondes.
So I would like to know if this is possible? and if yes, how?
Thank you for your kindness =) (and sorry for this english i use GoogleTraductor)
Here's how I'd do that.
let ratelimits = [];
client.on("message", (msg) => {
// APPLYING RATELIMITS
const appliedRatelimit = ratelimits.find(
(value) =>
value.user === msg.author.id && value.channel === msg.channel.id
);
if (appliedRatelimit) {
// Can they post the message?
const canPostMessage =
msg.createdAt.getTime() - appliedRatelimit.ratelimit >=
appliedRatelimit.lastMessage;
// They can
if (canPostMessage)
return (ratelimits[
ratelimits.indexOf(appliedRatelimit)
].lastMessage = msg.createdAt.getTime());
// They can't
msg.delete({ reason: "Enforcing ratelimit." });
}
// SET RATELIMIT
if (msg.content === "!ratelimit") {
// Checking it's you
if (msg.author.id !== "your id") return msg.reply("You can't do that.");
// You can change these values in function of the received message
const targetedUserId = "whatever id you want";
const targetedChannelId = msg.channel.id;
const msRateLimit = 2000; // 2 seconds
// Delete existant ratelimit if any for this user on this channel
ratelimits = ratelimits.filter(
(value) =>
!(
value.user === targetedUserId &&
value.channel === targetedChannelId
)
);
// Add ratelimit
ratelimits.push({
user: targetedUserId,
channel: targetedChannelId,
ratelimit: msRateLimit,
lastMessage: 0,
});
}
// CLEAR RATELIMITS
if (msg.content === "!clearRatelimits") {
// Checking it's you
if (msg.author.id !== "your id") return msg.reply("You can't do that.");
// Clearing all ratelimits
ratelimits = [];
}
});

guild.icon & guild.iconURL() not working in embed thumbnail

I want to set guild icon as the thumbnail of embed but neither guild.icon nor guild.iconURL() work
bot.on('message', message => {
if(message.author.bot) return;
if(message.channel.name === 'verify') {
if(message.content === '!verify') {
message.delete()
let dm = message.author;
let server = message.guild.name;
let servericon = message.guild.iconURL();
console.log(servericon)
let attachment = new Discord.MessageAttachment(this.choose , 'chosen.png')
let embed = new Discord.MessageEmbed()
.setTitle(`**Welcome to ${server}**\n\nCaptcha`)
.setDescription("Please complete the captcha given below to gain access to the server.\n**Note:** This is case sensitive")
.setAuthor('Mr.Verifier', "https://i.ibb.co/nckjDjG/hmm.png")
.setThumbnail(servericon)
.addField(
{ name: '**Why all this?**', value: 'This is to protect the servers from\nmalicious raids of automated bots'}
)
.setImage(`attachment://chosen.png`)
dm.send(embed)
}else{
message.delete();
}
};
})
You need to use guild.iconURL().

How to ban and kick a GuildMember

Well, I followed "The Source Code" "discord.js" tutorial, (even copy-pasted his code from GitHub) but the ban and kick commands he's shown don't work, I assume they got broken by a recent update. It sends the embed to the incidents channel but doesn't actually ban the player. Also, if you have any suggestions for me to change things, please suggest!
if (cmd === `${prefix}ban`) {
let bUser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if (!bUser) return message.channel.send("Can't find user!");
let bReason = args.join(" ").slice(22);
if (!message.member.hasPermission("MANAGE_MEMBERS")) return message.channel.send("No can do pal!");
if (bUser.hasPermission("MANAGE_MESSAGES")) return message.channel.send("That person can't be banned!");
let banEmbed = new Discord.RichEmbed()
.setDescription("Ban Management")
.setColor("#bc0000")
.addField("Banned User", `${bUser} with ID ${bUser.id}`)
.addField("Banned By", `<#${message.author.id}> with ID ${message.author.id}`)
.addField("Banned In", message.channel)
.addField("Time", message.createdAt)
.addField("Reason", bReason);
let incidentchannel = message.guild.channels.find(`name`, "incidents");
if (!incidentchannel) return message.channel.send("Can't find incidents channel.");
message.guild.member(bUser).ban(bReason);
message.delete().catch(O_o => {});
incidentchannel.send(banEmbed);
return;
}
message.guild.member(bUser).ban(bReason);
This will not ban the member. The message has a member property so you don't need to use message.guild.member you can just easily use message.member.
So it should look like this:
if (cmd === `${prefix}ban`) {
let bUser = message.guild.member(message.mentions.members.first() || message.guild.members.get(args[0]));
if (!bUser) return message.channel.send("Can't find user!");
let bReason = args.join(" ").slice(22);
if (!message.member.hasPermission("MANAGE_MEMBERS")) return message.channel.send("No can do pal!");
if (bUser.hasPermission("MANAGE_MESSAGES")) return message.channel.send("That person can't be banned!");
let banEmbed = new Discord.RichEmbed()
.setDescription("Ban Management")
.setColor("#bc0000")
.addField("Banned User", `${bUser.user.tag} with ID ${bUser.id}`)
.addField("Banned By", `<#${message.author.id}> with ID ${message.author.id}`)
.addField("Banned In", message.channel.name)
.addField("Time", message.createdAt)
.addField("Reason", bReason);
let incidentchannel = message.guild.channels.find(`name`, "incidents");
if (!incidentchannel) return message.channel.send("Can't find incidents channel.");
message.guild.member(bUser).ban({
reason: bReason
});
message.delete();
incidentchannel.send({
embed: banEmbed
});
return;
}
I changed a lot because a lot was outdated and could not work. It could be that I haven't seen one or the other mistake.
Let me know if it worked! :)
Best regards,
Monkeyyy11
This seems awfully complicated, I hope my command can make things a bit easier!
bot.on('message', message => {
const arguments = message.content.slice(prefix.length).trim().split(/ +/g);
const commandName = arguments.shift().toLowerCase();
if (message.content.startsWith(prefix) && commandName == "kick") {
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send("Permissions invalid");
const userKick = message.mentions.users.first();
if (userKick) {
var member = message.guild.member(userKick);
if (member) {
member.kick({
reason: `This person was kicked using a bot's moderation system. We are so sorry if this caused problems.`
}).then(() => {
message.reply(`A user been kicked.`)
})
} else {
message.reply(`User not found`);
}
} else {
message.reply(`Please enter a name`)
}}})
bot.on('message', message => {
const arguments = message.content.slice(prefix.length).trim().split(/ +/g);
const commandName = arguments.shift().toLowerCase();
if (message.content.startsWith(prefix) && commandName == "ban") {
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Permissions invalid");
const userBan = message.mentions.users.first();
if (userBan) {
var member = message.guild.member(userBan);
if (member) {
member.ban({
reason: `This person was banned using a bot's moderation system. We are so sorry if this caused problems.`
}).then(() => {
message.reply(`a user has been banned!`)
})
} else {
message.reply(`User not found`);
}
} else {
message.reply(`Please enter a name`)
}}})
If you use discord.js v12 or higher, then RichEmbed is now deprecated. Instead, use MessageEmbed

Resources