discord.js v13 How do I verify a guildMember is also a member of another guild? - discord.js

This is my first post here, sorry in advance if the formatting isn't great.
I'll try to keep it short and sweet. I've made a small bot with discord.js v13 and it's main purpose is to check if new people that join is part of another guild, if they are they get a role and if they had a nickname, they'll get that assigned. The bot is on both servers with full admin rights and the server members intent is enabled. I've tried all sorts of things.
Currently, the code looks like this:
const {other_server_ID, role_ID, text_channel_ID} = require("../config.json");
module.exports = {
name: 'guildMemberAdd',
async execute( member, bot ) {
//Log the newly joined member to console
console.log(member.user.tag + ' has joined the server!');
if(member.bot) return
const text_channel = member.guild.channels.cache.get(text_channel_ID)
const role = member.guild.roles.cache.get(role_ID)
text_channel.send(member.user.tag + ' has joined the server!')
const other_server = bot.guilds.cache.get(other_server_ID)
const other_server_member = other_server.members.cache.get(member.user.id)
console.log(other_server_member)
if (other_server_member === null) text_channel.send(member.user.tag + " was not a member of other_server :(")
else {
text_channel.send(member.user.tag + " was a member of other_server!")
if(!other_server_member.nickname){
text_channel.send(member.tag + " had no nickname on other_server.")
}
else {
await member.setNickname(other_server_member.nickname)
text_channel.send("Their old nickname, " + other_server_member.nickname + ", was returned to them! :)")
}
if(!member.guild.roles.cache.get(role_ID)){
text_channel.send("Role not found.")}
else{
await member.roles.add(role)
text_channel.send("They were given the role " + role.name)
}
}
}
}
As you can see, I am trying to get the other server (it works that far) and then try to grab the user from the other server's cache. Currently I try with get and the user.id but I have also tried:
const other_server_member = other_server.members.cache.find(mem => mem.user.id === member.user.id) || other_server.members.cache.find(mem => mem.user.tag === member.user.tag) || null
I found that code snippet during my search for a solution. So far I always got errors because other_server_member was always undefined/null. I also tried putting await infront of the find/get part.
Thanks for your help and time.
UPDATE:
It works fine with fetch(), code now looks like this:
const {other_server_ID, role_ID, text_channel_ID} = require("../config.json");
module.exports = {
name: 'guildMemberAdd',
async execute( member, bot ) {
//Log the newly joined member to console
console.log(member.user.tag + ' has joined the server!');
if(member.bot) return
const text_channel = member.guild.channels.cache.get(text_channel_ID)
const role = member.guild.roles.cache.get(role_ID)
text_channel.send(member.user.tag + ' has joined the server!')
const other_server = bot.guilds.cache.get(other_server_ID)
const other_server_member = null
try {
other_server_member = await other_server.members.fetch(member.user.id)
} catch (e) {
console.log(e)
return text_channel.send(member.user.tag + " was not a member of " + pluto.name + ".")
}
console.log(other_server_member)
if (other_server_member === null) text_channel.send(member.user.tag + " was not a member of other_server :(")
else {
text_channel.send(member.user.tag + " was a member of other_server!")
if(!other_server_member.nickname){
text_channel.send(member.tag + " had no nickname on other_server.")
}
else {
await member.setNickname(other_server_member.nickname)
text_channel.send("Their old nickname, " + other_server_member.nickname + ", was returned to them! :)")
}
if(!member.guild.roles.cache.get(role_ID)){
text_channel.send("Role not found.")}
else{
await member.roles.add(role)
text_channel.send("They were given the role " + role.name)
}
}
}
}

Related

Unban is not defined

const Discord = require('discord.js');
module.exports = {
name: 'unban',
aliases: ['uban', 'unban'],
category: 'misc',
permissions: ['BAN_MEMBERS'],
description:
'Use this command to permanately or temporary ban a server member from Sekai.',
/**
* #param {Discord.Message} message
* #param {Array} args
*/
async execute(message, args) {
if (message.mentions.users.size === 0)
return message.reply('Please mention a user to unban ❌');
const targetid = message.mentions.users.first().id;
if (targetid === message.client.user.id)
return message.reply(
"Me? Really? That's not very nice, I guess you failed 🤡"
);
const targed = await message.guild.members.cache.get(targetid);
let reason = [];
if (args.length >= 2) {
args.shift();
reason = args.join(' ');
} else reason = 'No Reason provided';
try {
let extra = '';
try {
const embed = new Discord.MessageEmbed()
.setTitle('Moderation message regarding on your **BAN**')
.setAuthor("Joony's Den")
.setDescription(
`you have been banned from **${message.guild.name} ✅ **\nReason for ban: **${reason}\n${extra}**`
)
.addField('Contact','If you believe that your ban was unjustified, please feel free to contact any of these staff members. **JOONY#9513** or any of administrators online.')
.setColor('#2243e6')
.addField('Appeal Accepted?','if your appeal was accepted, please join using this link. your link will expire after 1 use. **https://discord.gg/4yuCzUC7aw**')
.addField(
'Appeal',
'Because you have been banned from the server, you will have one chance to appeal 🔨. Your appeal will be processed to the administrators or appeal managers ✅ **[CLICK HERE TO APPEAL](https://forms.gle/atc75ZftpdfJhfH56)**'
);
targed.send(embed);
} catch (error) {
extra = 'Messaging the user has failed! ❌';
}
setTimeout(() => {
targed.unban(targed, [reason])
const embed = new Discord.MessageEmbed()
.setTitle('User unbanned')
.setDescription(
`${
targed.tag || targed.user.username
} has been sucessfully unbanned from **${
message.guild.name
} ✅ **\nReason for unban: **${reason}\n${extra}**`
)
.setColor('#FA2657');
message.channel.send(embed);
}, 2000);
} catch (error) {
message.channel.send(
`I could not unban the given member, make sure that my role is above member! ❌`
);
}
},
};
Hello! how do I unban the user using this format, it has an error saying "guild.unban is undefined"
it has an error saying
targed.unban([reason])
^
TypeError: targed.unban is not a function
at Timeout._onTimeout (C:\Users\Joon\Documents\GitHub\Discord-Bot\commands\misc\unban.js:49:16)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
You cannot unban a GuildMember (a banned user is not a member of a Guild). You should call unban on GuildMemberManager. See https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=unban

How do i change nickname via a command?

There's a joke on the server where when we use the command +h kidnap, and then we change the nickname to User (Kidnapper's Property), how would I go about automatically changing the nickname via the command?
var rand = [
'https://tenor.com/view/anime-kidnap-shh-reading-walking-gif-16716474',
'https://tenor.com/view/kidnap-crazy-anime-animation-cartoon-gif-5137884',
'https://media.tenor.com/images/5ae68746d329f3102d72d2ecc20ec1b0/tenor.gif',
'https://i.kym-cdn.com/photos/images/newsfeed/001/010/345/e2d.gif',
'https://media1.tenor.com/images/0cb215fd5530a8e3c127095c987e455f/tenor.gif?itemid=5869143',
'https://cdn.discordapp.com/attachments/576014006280519701/772153347742367784/1538820468_2e00f539e9a47173911f2af39ae5ecfe96f32ae4_hq.gif',
'https://cdn.discordapp.com/attachments/576014006280519701/772153350057623622/1512286824_1472546756_tumblr_ockwd0wF3R1qz64n4o1_540.gif'
];
return rand[Math.floor(Math.random() * rand.length)];
}
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'kidnap':
const personTagged = message.mentions.members.first();
if(!args[1]) {
message.channel.send('You are missing arguments!')
}else{
message.channel.send('`' + message.author.username + '`' + ' is kidnapping ' + personTagged.displayName + '! Quick! Run! ' + doKidnapAction())
}
break;
}
})
Again, how would I go about changing the nickname?
You could do it like this I belive: personTagged.setNickname("Kidnapper's Property")

Discord.Js - making a bot that creates custom roles

I'm someone who just got into coding recently.
I'm trying to create a Discord bot that can do custom roles that can allow a user of that custom role to edit its hex or name.
There's also the creation of a role creator that also assigns the mentioned user the role.
My problem is that I've encountered an issue with the role creation + assignment and the commands that allow the user to edit their role.
Here are the problems:
(node:6288) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined for the role creator command
When I try to use the commands that allow the user to customize their roles, the commands don't work, or to be more specific, they don't activate.
I do believe that the codes I'm using could be outdated, therefore if that is the case, please give me the exact location and the right code.
Here are some pictures of the codes. I've pasted the codes below, but I'm a bit new to this forum, so please pay attention to the separating pieces like "Role Customization Code:" to distinguish which one's which. For some reason, the module.exports aren't going in there. Please describe and let me know a solution to these problems in a specific way since I am a newbie at this topic.
Role creation command + assignment error.
Role creation command + assignment code part 1.
Role creation command + assignment code part 2.
Role customization code part 1.
Role customization code part 2.
Role customization code part 3.
Role creation + assignment code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
if (!args[0]) return message.channel.send("Please specify a user to add!");
let toAdd = message.guild.members.get(args[0]) || message.guild.members.get(message.mentions.users.first().id);
let rolejoin = args.slice(1).join(" ");
let myRole = message.guild.roles.cache.get((val) => val.name.toLowerCase() === rolejoin.toLowerCase());
if (!toAdd) return message.channel.send("User not found!");
if (!rolejoin) return message.channel.send("Please specify a role to add!");
let botRole = message.guild.members.get(bot.user.id).highestRole;
let isPosition = botRole.comparePositionTo(myRole);
if (isPosition <= 0) return message.channel.send(embedFail("This role is higher than me, I cannot add this role!"));
let res = await query(`SELECT * FROM user_roles WHERE role_id='${myRole.id}'`);
if (res[0]) {
await query(`DELETE FROM user_roles where role_id='${myRole.id}'`);
toAdd.removeRole(myRole);
message.channel.send(embedSuccess(`Removed role ${myRole.name} from ${toAdd.user.username}`));
} else if (!res[0]) {
await query(`INSERT INTO user_roles (guild_id, user_id, role_id) VALUES ('${message.guild.id}',${toAdd.id},'${myRole.id}')`);
toAdd.addRole(myRole);
message.channel.send(embedSuccess(`Adding role ${myRole.name} to ${toAdd.user.username}`));
}
};
Role Customization Code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args, db) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
let res = await query(`SELECT * FROM user_roles WHERE guild_id = '${message.guild.id}' AND user_id = '${message.author.id}'`);
if (!args[0]) {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
let assignNames = "";
let embed = new Discord.RichEmbed()
.setAuthor(`Current role assigned to ${message.author.username}`, message.guild.iconURL)
.setColor(myRole.hexColor)
.addField(`Name`, `${myRole.name}`, true)
.addField(`Colour`, `${myRole.hexColor}`, true);
message.channel.send(embed);
} else {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
if (!myRole) {
await query(`DELETE FROM user_roles where guild_id = '${message.guild.id}' AND role_id = '${res[i].role_id}' and user_id = '${res[i].user_id}'`);
return message.channel.send(embedFail("You do not have a role!"));
}
switch (args[0]) {
case "name":
let name = args.slice(1).join(" "),
oldName = myRole.name;
await myRole.setName(name);
await message.channel.send(embedSuccess(`You have changed ${oldName}'s name to ${name}!`));
break;
case "color":
case "color":
let hexCode = args[1],
oldHex = myRole.hexColor;
await myRole.setColor(hexCode);
await message.channel.send(embedSuccess(`You have changed ${myRole.name}'s color from ${oldHex} to #${hexCode}!`));
break;
}
}
};

When user type !verify gets verified role

What i want to happen is when user type command "!verify" i want them to give "Verified" role,
i am currently running the latest Discord.js which is version 12.3.1 based on dependencies.
if(message.content.startsWith(`${prefix}verify`)){
let member = message.mentions.members.first();
var role = guild.roles.cache.find('name', 'Verified');
member.addrole(role).then((member)=> {
message.channel.send(":white_check_mark: " + member.displayName + " is now verified!");
})
}
})
There are a few lines in your code that won't work due to having being deprecated methods.
var role = message.guild.roles.cache.find('name', 'Verified');
// should be replace with:
var role = message.guild.roles.cache.find(role => role.name === 'Verified);
and
member.addrole(role).then((member)= > {
message.channel.send(":white_check_mark: " + member.displayName + " is now verified!");
})
// should be replaced with:
member.roles.cache.add(role)
message.channel.send(":white_check_mark: " + member.displayName + " is now verified!");

How to add an audit log for role added, removed, and username changed in Discord.js?

For my Discord.js bot, I am attempting to create an audit log that sends messages to a specific log channel within every server it is in for user changes. I have a working 'message deleted' audit log function, but when I attempt to carry it over to role adding and deletion, usernames, nicknames, and avatar changes, the bot fails to log this and crashes. How do I fix this issue within my code?
I have included both the message delete audit log message send, and the role add/remove/username change
client.on('messageDelete', function (message) {
if (message.channel.type === 'text') {
// post in the server's log channel, by finding the accuratebotlog channel (SERVER ADMINS **MUST** CREATE THIS CHANNEL ON THEIR OWN, IF THEY WANT A LOG)
var log = message.guild.channels.find('name', CHANNEL)
if (log != null) {
log.sendMessage('**Message Deleted** ' + message.author + '\'s message: ' + message.cleanContent + ' has been deleted.')
}
}
})
// sends message when important (externally editable) user statuses change (for example nickname)
// user in a guild has been updated
client.on('guildMemberUpdate', function (guild, oldMember, newMember) {
// declare changes
var Changes = {
unknown: 0,
addedRole: 1,
removedRole: 2,
username: 3,
nickname: 4,
avatar: 5
}
var change = Changes.unknown
// check if roles were removed
var removedRole = ''
oldMember.roles.every(function (value) {
if (newMember.roles.find('id', value.id) == null) {
change = Changes.removedRole
removedRole = value.name
}
})
// check if roles were added
var addedRole = ''
newMember.roles.every(function (value) {
if (oldMember.roles.find('id', value.id) == null) {
change = Changes.addedRole
addedRole = value.name
}
})
// check if username changed
if (newMember.user.username != oldMember.user.username) {
change = Changes.username
}
// check if nickname changed
if (newMember.nickname != oldMember.nickname) {
change = Changes.nickname
}
// check if avatar changed
if (newMember.user.avatarURL != oldMember.user.avatarURL) {
change = Changes.avatar
}
// post in the guild's log channel
var log = guild.channels.find('name', CHANNEL)
if (log != null) {
switch (change) {
case Changes.unknown:
log.sendMessage('**[User Update]** ' + newMember)
break
case Changes.addedRole:
log.sendMessage('**[User Role Added]** ' + newMember + ': ' + addedRole)
break
case Changes.removedRole:
log.sendMessage('**[User Role Removed]** ' + newMember + ': ' + removedRole)
break
case Changes.username:
log.sendMessage('**[User Username Changed]** ' + newMember + ': Username changed from ' +
oldMember.user.username + '#' + oldMember.user.discriminator + ' to ' +
newMember.user.username + '#' + newMember.user.discriminator)
break
case Changes.nickname:
log.sendMessage('**[User Nickname Changed]** ' + newMember + ': ' +
(oldMember.nickname != null ? 'Changed nickname from ' + oldMember.nickname +
+newMember.nickname : 'Set nickname') + ' to ' +
(newMember.nickname != null ? newMember.nickname + '.' : 'original username.'))
break
case Changes.avatar:
log.sendMessage('**[User Avatar Changed]** ' + newMember)
break
}
}
})
I expected the bot to send a message to my channel saying 'User Role Removed: memberName + their old role', and vise versa for role adding, but my bot fails to send these messages to the bot log channel I had set up.
There is no guild parameter in a GuildMemberUpdate event. Therefore, newMember is undefined because only two parameters are passed.
client.on('guildMemberUpdate', (oldMember, newMember) => {
const guild = newMember.guild;
// continue with code
});

Resources