I'm setting up server logs on my Discord bot on Discord.js v12.2.0 and I'm currently trying to set up role logging. I've rummaged around on the internet a bit and I can only find solutions for this on older versions of Discord.js, which obviously don't work on v12.2.0. I've set up the guildMemberUpdate event to log nickname changes, but I simply don't know how to do it for roles. It might just be super simple but I'm not sure how I would go about it.
Here's my code so far:
client.on('guildMemberUpdate', (oldMember, newMember) => {
if (!oldMember.nickname && newMember.nickname) {
const membernewnicklog = new Discord.MessageEmbed()
.setAuthor(`${newMember.user.tag}`, `${newMember.user.displayAvatarURL({ format: "png", dynamic: true })}`)
.setDescription(`**${newMember} nickname added**`)
.setFooter(`${newMember.user.username}'s ID: ${newMember.id}`)
.setTimestamp()
.setColor('#ffff00')
.addField("New nickname", newMember.nickname)
client.channels.cache.get('736996028787589201').send(membernewnicklog);
return;
}
if (oldMember.nickname && !newMember.nickname) {
const memberremovenicklog = new Discord.MessageEmbed()
.setAuthor(`${oldMember.user.tag}`, `${oldMember.user.displayAvatarURL({ format: "png", dynamic: true })}`)
.setDescription(`**${oldMember} nickname removed**`)
.setFooter(`${oldMember.user.username}'s ID: ${oldMember.id}`)
.setTimestamp()
.setColor('#f04747')
.addField("Old nickname", oldMember.nickname)
client.channels.cache.get('736996028787589201').send(memberremovenicklog);
return;
}
if (oldMember.nickname && newMember.nickname) {
const memberchangednicklog = new Discord.MessageEmbed()
.setAuthor(`${newMember.user.tag}`, `${newMember.user.displayAvatarURL({ format: "png", dynamic: true })}`)
.setDescription(`**${newMember} nickname changed**`)
.setFooter(`${newMember.user.username}'s ID: ${newMember.id}`)
.setTimestamp()
.setColor('#ff4500')
.addField("Before", oldMember.nickname)
.addField("After", newMember.nickname);
client.channels.cache.get('736996028787589201').send(memberchangednicklog);
return;
}
});
And here's what I'm going for: https://imgur.com/a/FRbTpGQ (an example from another bot)
Any help would be super appreciated. Thanks!
client.on("guildMemberUpdate", (oldMember, newMember) => {
// Old roles Collection is higher in size than the new one. A role has been removed.
if (oldMember.roles.cache.size > newMember.roles.cache.size) {
// Creating an embed message.
const Embed = new discord.MessageEmbed();
Embed.setColor("RED");
Embed.setAuthor(newMember.user.tag, newMember.user.avatarURL());
// Looping through the role and checking which role was removed.
oldMember.roles.cache.forEach(role => {
if (!newMember.roles.cache.has(role.id)) {
Embed.addField("Role Removed", role);
}
});
client.channels.cache.get("ChannelID").send(Embed);
} else if (oldMember.roles.cache.size < newMember.roles.cache.size) {
const Embed = new discord.MessageEmbed();
Embed.setColor("GREEN");
Embed.setAuthor(newMember.user.tag, newMember.user.avatarURL());
// Looping through the role and checking which role was added.
newMember.roles.cache.forEach(role => {
if (!oldMember.roles.cache.has(role.id)) {
Embed.addField("Role Added", role);
}
});
client.channels.cache.get("ChannelID").send(Embed);
}
});
Related
I can't understand why doesn't send the welcome message
Here's Code from index.js
client.on('guildMemberAdd', (member) => {
let chx = db.get(`welchannel_${member.guild.id}`);
if (chx === null) {
return;
}
client.channels.cache.get(chx).send(`Welcome to ${message.guild.name}`);
});
Here's Code From channel.js
module.exports = {
name: "channel",
description: "Help Command",
category: "Help",
execute(client, message, args, Discord) {
const db = require("quick.db")
let channel = message.mentions.channels.first() //mentioned channel
if(!channel) { //if channel is not mentioned
return message.channel.send("Please Mention the channel first")
}
db.set(`welchannel_${message.guild.id}`, channel.id)
const embed = new Discord.MessageEmbed()
.setColor('#b5b5b5')
.setTitle(`Channel set: ${channel.name} `)
message.channel.send({ embeds: [embed] });
}
}
EDIT: I found out the problem i didn't have a intent flag GUILD_MEMBERS
and also thanks UltraX that helped also
Basically, the reason is simple, you need to go to your dev portal then after choosing your bot/application just go to bot and you need to enable member intents Server Member Intent after that it should work, if it didn't just give it a 10 minute, then try again!
The best way to ensure you get a channel object within the event is to use the guild property off the emitted member.
client.on("guildMemberAdd", (member) => {
const { guild } = member;
let chx = db.get(`welchannel_${member.guild.id}`);
if(chx === null) {return}
const channel = guild.channels.cache.get(chx);
if (!channel) return;
channel.send(`Welcome to ${message.guild.name}`)
.catch(console.error);
})
You will need the Guild Member's intent enabled as stated in This Answer for the event to emit.
I try to create a very small ticket bot.
I would only like that when reacting a support channel opens and nothing else.
This is the code i am working with.
const ember = new Discord.MessageEmbed()
.setColor('#E40819')
.setTitle('⚠️SUPPORT')
.setDescription("Open a Ticket")
let msgEmbed6 = await message.channel.send(ember)
await msgEmbed6.react('⚠️')
The code inside the if statement will only run if the user reacts, I'm not sure what you mean by 'open a support channel'.
const reaction = msgEmbed6.awaitReactions((reaction, user) => user.id === message.author.id, { max: 1, timeout: TIME_IN_MILLISECONDS });
if (reaction.size > 0) {
// Creates a new text channel called 'Support'
const supportChannel = await message.guild.channels.create('Support', { type: 'text' });
// Stops #everyone from viewing the channel
await supportChannel.updateOverwrite(message.guild.id, { VIEW_CHANNEL: false });
// Allows the message author to send messages to the channel
await supportChannel.updateOverwrite(message.author, { SEND_MESSAGES: true, VIEW_CHANNEL: true });
}
I made a userinfo command which works on mentioning the user. Here is the code:
client.on('message', async message => {
if (message.content.startsWith('+ui')) {
const args = message.content.slice(4).trim().split(/ +/g);
const member = message.mentions.members.first();
const embed = new MessageEmbed()
.setTitle(`${member.displayName}'s Information`)
.setThumbnail(member.user.displayAvatarURL({
dynamic: true
}))
.addField('User', member, true)
.addField('Discriminator', `\`#${member.user.discriminator}\``, true)
.addField('ID', `\`${member.id}\``, true)
.addField('Status', statuses[member.presence.status], true)
.addField('Bot', `\`${member.user.bot}\``, true)
.addField('Color Role', member.roles.color || '`None`', true)
.addField('Highest Role', member.roles.highest, true)
.addField('Joined server on', `\`${moment(member.joinedAt).format('MMM DD YYYY')}\``, true)
.addField('Joined Discord on', `\`${moment(member.user.createdAt).format('MMM DD YYYY')}\``, true)
.setFooter(message.member.displayName, message.author.displayAvatarURL({
dynamic: true
}))
.setTimestamp()
.setColor(member.displayHexColor);
if (activities.length > 0) embed.setDescription(activities.join('\n'));
if (customStatus) embed.spliceFields(0, 0, {
name: 'Custom Status',
value: customStatus
});
if (userFlags.length > 0) embed.addField('Badges', userFlags.map(flag => flags[flag]).join('\n'));
message.channel.send(embed);
}
});
However, this only works when the message sent is +ui #User. However, if I want my own userinfo I need to use +ui #mention where I mention myself.
How can I make the bot send the message author's output when no mentions are given and userinfo if a user's id is given instead of mention.
Sorry for any kind of misunderstanding caused by the question. Thanks in advance
You can add a fallback value when message.mentions.members.first() gives you undefined.
const member = message.mentions.members.first() || message.member
How to give permissions to a specific channel by command? Sorry, I’m new at discord.js so any help would be appreciated.
const Discord = require('discord.js');
module.exports = {
name: 'addrole',
run: async (bot, message, args) => {
//!addrole #user RoleName
let rMember =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.cache.get(args[0]);
if (!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(' ').slice(22);
if (!role) return message.reply('Specify a role!');
let gRole = message.guild.roles.cache.find((r) => r.name === role);
if (!gRole) return message.reply("Couldn't find that role.");
if (rMember.roles.has(gRole.id));
await rMember.addRole(gRole.id);
try {
const oofas = new Discord.MessageEmbed()
.setTitle('something')
.setColor(`#000000`)
.setDescription(`Congrats, you have been given the role ${gRole.name}`);
await rMember.send(oofas);
} catch (e) {
message.channel.send(
`Congrats, you have been given the role ${gRole.name}. We tried to DM `
);
}
},
};
You can use GuildChannel.updateOverwrites() to update the permissions on a channel.
// Update or Create permission overwrites for a message author
message.channel.updateOverwrite(message.author, {
SEND_MESSAGES: false
})
.then(channel => console.log(channel.permissionOverwrites.get(message.author.id)))
.catch(console.error);
(From example in the discord.js docs)
Using this function, you can provide a User or Role Object or ID of which to update permissions (in your case, you can use gRole).
Then, you can list the permissions to update followed by true, to allow, or false, to reject.
Here is a full list of permission flags you can use
This method is outdated and doesn't work on V13+ the new way is doing this:
channel.permissionOverwrites.edit(role, {SEND_MESSAGES: true }
channel.permissionOverwrites.edit(member, {SEND_MESSAGES: true }
Hello I'm making a ticket bot for my server.
But I'm getting error like message.guild.createChannel is not a function
The code
if (message.content.toLowerCase().startsWith(prefix + `openticket`)) {
const reason = message.content.split(" ").slice(1).join(" ");
if (message.guild.channels.cache.find(c => c === `ticket-${message.author.id}`)) return message.channel.send(`You already opened a ticket.`);
message.guild.createChannel(`ticket-${message.author.id}`, "text").then(c => {
let role2 = message.guild.roles.find("name", "#everyone");
c.overwritePermissions(role, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.overwritePermissions(role2, {
SEND_MESSAGES: false,
READ_MESSAGES: false
});
c.overwritePermissions(message.author, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
message.channel.send(`:white_check_mark: Your ticket is opened, #${c.name}.`);
const embed = new Discord.RichEmbed()
.setColor(0xCF40FA)
.addField(`Hey ${message.author.username}!`, `Your Ticket is opened.`)
.setTimestamp();
c.send({ embed: embed });
message.delete();
}).catch(console.error);
}
İ think the code is too old. I got this code from my friends.
Your code seems to be a mix between discord.js v11 and discord.js v12 version.
v12 introduced Managers.
To create a channel on a guild, you have to use the GuildChannelManager, this is the v12 way to do it (see GuildChannelManager.create method documentation) :
message.guild.channels.create(`ticket-${message.author.id}`, { type: 'text' }).then(c => {
...
});
Useful guide that shows changes between v11 and v12.