Discord js addedRole executor - javascript

Basically this code, if user gave a role or lost a role log this condition
client.on('guildMemberUpdate', (oldMember, newMember) => {
let channel = oldMember.guild.channels.cache.find(channel => channel.name === "member-log");
let addedRoles = newMember.roles.cache.filter(role => !oldMember.roles.cache.has(role.id));
let removedRoles = oldMember.roles.cache.filter(role => !newMember.roles.cache.has(role.id));
if (removedRoles.size > 0) {
const removeRoleEmbed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setAuthor(`${oldMember.user.tag}` , oldMember.user.avatarURL())
.setDescription(`<#!${oldMember.id}> kişisinden <#&${removedRoles.map(r => r.id)}> rolü alındı.`)
.setTimestamp()
.setFooter(`Kullanıcı ID : ${oldMember.id}`)
channel.send(removeRoleEmbed)
}
if (addedRoles.size > 0) {
const addRoleEmbed = new Discord.MessageEmbed()
.setColor('#80FF00')
.setAuthor(`${oldMember.user.tag}` , oldMember.user.avatarURL())
.setDescription(`<#!${oldMember.id}> kişisine <#&${addedRoles.map(r => r.id)}> rolü verildi.`)
.setTimestamp()
.setFooter(`Kullanıcı ID : ${oldMember.id}`)
channel.send(addRoleEmbed)
}
});
I have this code and i want who give role a user
Note: Sorry for my english and thank in advance

For that, I believe you need to look at the Audit logs. Now, in Djs v12, you can check audit logs easily. You're looking for the MEMBER_ROLE_UPDATE action. Here are the list of all possible actions.
Here's from the Guide on how to listen to Audit Logs:
https://discordjs.guide/popular-topics/audit-logs.html
(Assuming async function)
const log = await message.guild.fetchAuditLogs({ limit: 1, type: 'MEMBER_ROLE_UPDATE' }).then(logs => logs.entries.first());
// This should log the id of the person who gave out that role.
console.log(log.executor.id);
That's it.

Related

How can i get my discord.js v14 bot to stop saying "The application did not respond" if the slash command works?

i have multiple commands that work perfectly fine but i always get this message in return.
here is the code for that command. it works perfectly fine i guess it just doesn't respond to the interaction even though i feel like it should be?
how can i get it to ignore this message or reply properly?
const Discord = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('totalfrozencheckouts')
// command description
.setDescription('Add up every message in the frozen checkouts channel after a specific message ID')
.addStringOption(option =>
option.setName('messageid')
.setDescription('The message ID')
.setRequired(true)),
async execute(interaction) {
const channel = '<#' + process.env.FROZENCHECKOUTS + '>';
const messageId = interaction.options.getString("messageid");
// Check if the channel mention is valid
if (!channel.startsWith('<#') || !channel.endsWith('>')) {
return interaction.channel.send(`Invalid channel mention. Please use the format: ${this.usage}`);
}
// Extract the channel ID from the channel mention
const channelId = channel.slice(2, -1);
// Try to fetch the messages from the requested channel and message ID
interaction.guild.channels.cache.get(channelId).messages.fetch({ after: messageId })
.then(messages => {
// Create an array of the message contents that are numbers
const numbers = messages.map(message => message.content).filter(content => !isNaN(content));
// Check if there are any messages
if (numbers.length === 0) {
return interaction.channel.send(`No messages were found in ${channel} after message ID https://discord.com/channels/1059607354678726666/1060019655663689770/${messageId}`);
}
// Adds up the messages
const sum = numbers.reduce((accumulator) => accumulator + 1, 1);
// Create an embed object
const embed = new EmbedBuilder()
.setColor(0x4bd8c1)
.setTitle(`Total Checkouts in #frozen-checkouts for today is:`)
.addFields(
{name: 'Total Checkouts', value: sum.toString() , inline: true},
)
.setThumbnail('https://i.imgur.com/7cmn8uY.png')
.setTimestamp()
.setFooter({ text: 'Frozen ACO', iconURL: 'https://i.imgur.com/7cmn8uY.png' });
// Send the embed object
interaction.channel.send({embeds: [embed]});
})
.catch(error => {
console.error(error);
interaction.channel.send('An error occurred while trying to fetch the messages. Please try again later.');
});
}
}
I don't really know what to try because it literally works I just don't know how to get it to either ignore that message or respond with nothing. It doesn't break the bot its just annoying to look at.
Use interaction.reply instead of interaction.channel.send to reply.

Unable to find a role by its name

I'm trying to make a command where you can set up an LFG role (LFG = looking for game).
Right now, I need the bot to find a role by its name, but it doesn't work. I have no idea why, I have tried many other thing like finding the role by its ID or structuring the code differently but nothing... Heres is the code:
collector1.on('collect', () => {
// Si l'utilisateur a cliqué sur 1️⃣ LFG
message.reactions.removeAll();
const embed1 = new MessageEmbed()
.setTitle(
`**--------------------LFG role configuration--------------------**`,
)
.addField(
`You clicked on 1️⃣`,
`Send in the next 30 the name of the new LFG role.`,
true,
)
.addField(
`Missclicked?`,
`Wait 30 seconds for the bot to send a timeout message and try again.`,
true,
);
let filter = (m) => m.author.id === message.author.id;
m.edit(embed1).then(() => {
message.channel
.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time'],
})
.then((message) => {
message.reactions.removeAll();
message = message.first();
let role = message.guild.roles.cache.find((r) => r.name === message);
message.channel.send(`Alright, The new lfg role is ${role}!`);
})
.catch((collected) => {
message.channel.send('Timeout.');
});
});
});
Also, I have a second problem which is the bot doesn't remove all the reactions.
message is not a string- it's a Message object. I think you meant message.content
let role = message.guild.roles.cache.find((r) => r.name === message.content);
Also, I have a second problem which is the bot doesn't remove all the reactions
Maybe you meant m.reactions.removeAll()?
To find a role by name you can simply use
message.guild.roles.find(role => role.name === "Rolename");

Show users connected to voice channel?

I want to know is it possible to know if any member is connected to a any voice channel in discord.js v12.2.0. Please let me know if you have any clues on it.
Use VoiceChannel.members
const vc = <message>.guild.channels.cache.get('VC Id')
const members = vc.members //COLLECTION
To check if a member is in vc, use GuildMember.voice
const vc = <member>.voice.channel //VOICE CHANNEL
//if you want, you can check the vc name, id, etc with vc.name, vc.id, etc
EDIT
Here is an example for what you said in the comments
//MAKE SURE IT IS ASYNC CALLBACK
await client.guilds.fetch();
const VCs = [];
client.guilds.cache.forEach(async guild => {
await guild.channels.fetch();
let VCs = guild.channels.cache.filter(c => c.type === 'voice');
VCs.forEach(vc => {
if(vc.members) {
VCs.push(vc)
}
})
})
I hope this is what you wanted (VCs is an array with all VCs with members)

Member online counter

My member counter didn't work
Why always my channel have name "online 0" 0 errors, console log working I don't know why
This is my code
const guild = client.guilds.cache.get('693805106906398722');
setInterval(() =>{
const memberCount = guild.memberCount;
const channel = guild.channels.cache.get('824050164376666182');
channel.setName(`Użytkownicy ${memberCount.toLocaleString()}`);
console.log('Member Status: Updating...');
}, 1200000);
setInterval(() =>{
const memberCollection = guild.members.cache;
const online = memberCollection.filter(member => {
member.presence.status === 'online'
}).size;
const channel1 = guild.channels.cache.get('824050194177720391');
channel1.setName(`Online ${online}`);
console.log('Member online Status: Updating...');
}, 1200);
} ```
Do you have Intents Enabled in your bot? If you do not: Then please do it in the Discord Developers Portal for your Application. You need to enable Guild Members intent. Also please do not forget to update your stuff in the Client Constructor (aka const client = new Discord.Client()) so that you can access the guild Member information!
There's a mistake in the code
const online = memberCollection.filter(member => {
member.presence.status === 'online'
}).size;
Please make it
const online = memberCollection.filter(member => {
return member.presence.status === 'online'
}).size;
Since for the filter to work, you need to have a function which returns a boolean and you're not returning anything from your filter function, it is getting a bit messed up.

How would I bypass a cetian role on a cooldown script discord.js/ command that restricts a certain command to a certain channel

This is the current code that I have, I would like to make it where if you have a certain role then you can bypass the cooldown, also if anyone knows how to make a command that restricts a certain command to a certain channel, instead of having this really long message.channel.id.
const Discord = require('discord.js');
const fetch = require('node-fetch');
const talkedRecently = new Set();
module.exports.run = async(client, message, args, queue, searcher, ) => {
if (talkedRecently.has(message.author.id)) {
message.channel.send("Wait 1 minute before getting typing this again. " +'<#'+ message.author.id + '>');
} else {
switch(args[0].toLowerCase()){
case 'neko':
if(message.channel.id === '739002385531404288'||
message.channel.id === '646849145289834506'||
message.channel.id === '785079847763574794'||
message.channel.id === '782891383361896469'||
message.channel.id === '784417039425994772'){
fetch('https://nekos.life/api/v2/img/lewd')
.then(res => res.json())
.then(json => {
let nekoEmbed = new Discord.MessageEmbed()
.setTitle('Lewd Nekos! (=^・ω・^=)')
.setImage(json.url)
message.channel.send(nekoEmbed)
})
}else{
return}}
talkedRecently.add(message.author.id);
setTimeout(() => {
talkedRecently.delete(message.author.id);
}, 60000);
}
}
module.exports.config = {
name: "hentai",
aliases: ['ht']
}
```
Answering Your First Question:
Simply check if the member has a certain role. If they do, construct your if statement so that it will not fire if they have that role
Make sure to use message.member when checking roles
if (talkedRecently.has(message.author.id) && !message.member.roles.cache.has('bypass role id here')) {
// Your cooldown message
}
Learn more about Roles#has
Answering your 2nd question:
You can have an array of channel id's then use includes to check if any of the id's in the array match the current channel id
const ids = ['id1', 'id2', 'id3', 'id4'] // And so on
if (ids.includes(message.channel.id)) {
// Your Code
}
Learn more about Array.prototype.includes

Categories

Resources