Unban is not defined - discord

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

Related

Discord warn command + time

Greetings I want to do something to my warn command
I want to add a time to it like: ,warn Noob 5m Cause a noob
warn [name | nickname | mention | ID] [time] [Reason]
I have no idea how to do it can someone help?
const { MessageEmbed } = require("discord.js");
const { redlight } = require('../../JSON/colours.json')
const db = require('quick.db');
module.exports = {
config: {
name: "warn",
aliases: ['report'],
category: "moderation",
description: "reports a user of the guild",
usage: "[name | nickname | mention | ID] <reason> (optional)",
accessableby: "Administrator",
},
run: async (bot, message, args) => {
if (!message.member.hasPermission("MANAGE_GUILD")) return message.channel.send("**You Dont Have The Permissions To Report Someone! - [MANAGE_GUILD]**");
if (!args[0]) return message.channel.send("**Please Enter A User!**")
let target = 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 (!target) return message.channel.send("**Please Enter A User!**")
if (target.id === message.member.id) return message.channel.send("**Cannot Warn Yourself!**")
let reason = args.slice(1).join(" ")
if (target.roles.highest.comparePositionTo(message.guild.me.roles.highest) >= 0) return message.channel.send('**Cannot Warn This User!**')
if (target.hasPermission("MANAGE_GUILD") || target.user.bot) return message.channel.send("**Cannot Warn This User!**")
try {
const sembed2 = new MessageEmbed()
.setColor("RED")
.setDescription(`**Hello, You Have Been Warned In ${message.guild.name} for - ${reason || "No Reason!"}**`)
.setFooter(message.guild.name, message.guild.iconURL())
target.send(sembed2)
} catch {
}
if (reason) {
const embed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(`${message.guild.name}`, message.guild.iconURL())
.setDescription(`**${target.displayName} Has Been Warned for ${reason}!**`)
message.channel.send(embed)
} else {
const embed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(`${message.guild.name}`, message.guild.iconURL())
.setDescription(`**${target.displayName} Has Been Warned!**`)
message.channel.send(embed)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (!channel) return;
const sembed = new MessageEmbed()
.setColor(redlight)
.setTimestamp()
.setThumbnail(target.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("**Moderation**", "report")
.addField("**User Reported**", `${target}`)
.addField("**User ID**", `${target.user.id}`)
.addField("**Reported By**", `${message.member}`)
.addField("**Reported in**", `${message.channel}`)
.addField("**Reason**", `**${reason || "No Reason"}**`)
.addField("**Date**", message.createdAt.toLocaleString());
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(sembed)
}
}
Thanks in advance!
(Telling me to add more details but idk what I can say more so ignore this lol)
Basically, Your code is hard to get, atleast for me. But you can add timeout fuction like this:-
setTimeout(function(){
//thing you wanna do
}, 1000); //time in milliseconds
Also before you proceed ahead, I don't think you want to make timed warns, which clear after particular time, Maybe. it's on you.

send error message or without permission on the channel

My bot is having some problems with some servers, the problem is Missing Permissions, it happens when the bot tries to do a function that it does not have permission on the server, and to alert the users of the bot that it does not have permission to execute the command on the server, I put 2 functions so that it warns the member that it does not have enough permission, but it is not advancing because the bot does not send the message on the channel saying that it does not have permission
The first function where he tells the member that he is not allowed to create the invitation is
in if (!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE')) { return message.channel.send('I am not allowed to create invitations.');}
And the second is
in } catch (e) { console.log(e) return message.reply(`The following error occurred :( \`${e.message}\` add the required permission \`MANAGE_INVITES\`.`);
const ms = require('parse-ms')
const { DiscordAPIError, MessageEmbed } = require("discord.js");
const { invalid } = require("moment");
module.exports = {
name: "jogar",
description: "Set the prefix of the guild!",
category: "economia",
run: async (bot, message, args) => {
if (!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE')) { return message.channel.send('Eu não\ tenho permissão para fazer isso!');
}
const { chunk } = require('../../functionsss');
let guild = bot.guilds.cache.get("759003907858104350");
let emoji = guild.emojis.cache.find(emoji => emoji.name === 'loading');
let emoji2 = guild.emojis.cache.find(emoji => emoji.name === 'check');
if(!message.member.voice.channel) return message.reply(`Você precisa está conectado ao um canal de voz para procurar partida!`)
const voiceChannels = message.guild.channels.cache.filter(c => c.type === 'voice');
let count = 0;
const vo = message.member.voice.channel.members.size
for (const [id, voiceChannel] of voiceChannels) count += voiceChannel.members.size;
let membro = message.author;
let newInfo = args.join(' ');
if (!newInfo) return message.reply('Insira o codigo da sala do among! **a!jogar BCETYJ**');
if (newInfo.length > 6) return message.channel.send(`**Max \`6\` Caracteres permitidos!**`);
let newsInfo = chunk(newInfo, 42).join('\n');
let embed = new Discord.MessageEmbed();
try {
let channel = message.member.voice.channel;
channel.createInvite({
maxAge: 3600, // 0 = infinite expiration
maxUses: 10 // 0 = infinite uses
})
.then(invite=>{
embed
.setTitle(`${emoji} Procurando partida..`)
.setColor('RANDOM')
.setTimestamp()
.setDescription(`Pessoal <#${membro.id}> está procurando mais gente para jogar!
\n<:info:775212992895254548> **Informações:**
**・Canal:** ${channel}
**・Codigo:** ${newsInfo}
**・Jogadores:** ${vo}
\n[Entrar na partida](https://discord.gg/${invite.code})`)
.setThumbnail('https://attackofthefanboy.com/wp-content/uploads/2020/09/Among-Us-3.jpg')
message.channel.send(embed)
message.react("✅");
})
} catch (e) {
console.log(e)
return message.reply(`The following error occurred :( \`${e.message}\` add the required permission \`MANAGE_INVITES\`.`);
}}}```
I've had this problem before and I spent hours troubleshooting. I eventually figured out that it was the way that I was looking for permissions. Discord.js v12 has added many changes to this type of function. I suggest changing
(!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE'))
to
(!message.guild.me.hasPermission("Create_Instant_Invite"){
//rest of your code
}

Bot Crashed When you dont mention

I have this command on my bot where you can mute someone using the command g!mute where the 'user' is mentioned using #. However, if you don't mention e.g GeoGeo instead of #GeoGeo, it causes the bot to crash. I know you need to put .catch(console.error); somewhere, but I'm not sure where. Thanks in advance. The Error is
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
^
TypeError: message.guild.members.get is not a function
Code:
const Discord = require('discord.js');
const ms = require('ms');
module.exports = {
name: 'mute',
description: "this is mute command",
execute(message, args){
if(!message.member.roles.cache.find(r => r.name ==="Staff", "Head Staff", "Owner", "Co-Owner")) return message.channel.send(`YOU DO NOT HAVE PERMISSION TO DO THAT`)
let members = args[0];
if(!members) return message.reply("g!mute <user> <time>")
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
if(!person) return message.reply("That person is not in the server!");
let mainrole = message.guild.roles.cache.find(role => role.name === "Fans");
let muterole = message.guild.roles.cache.find(role => role.name === "muted");
if(!muterole) return message.reply("That role does not exist");
let time = args[1];
if(!time){
return message.reply("g!mute <user> <time>");
}
person.roles.remove(mainrole.id);
person.roles.add(muterole.id);
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has now been muted for ${ms(ms(time))}`)
.setColor(0x01B8FF)
message.channel.send(embed);
setTimeout(function(){
person.roles.add(mainrole.id)
person.roles.remove(muterole.id)
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has been unmuted`)
.setColor(0x01B8FF)
message.channel.send(embed);
}, ms(time));
}
}
When faced with an error like: TypeError: message.guild.members.get is not a function
The logical thing to do is check the docs to see that message.guild.members really has a function named get. Here's the docs: https://discord.js.org/#docs/main/stable/class/GuildMemberManager
No get. But there is a cache like you use elsewhere in the code. Just by checking over the docs you can tell that your existing code is wrong (it's outdated) and you need to use cache like you do elsewhere in your code:
message.guild.members.cache.get(args[1])

Is it possible to make a command that sets the log channel?

I'm creating a new for moderation, and was wondering if it was possible to make a command that sets the log channel, example if they set it to #logs, and if they ban a member it sends a message to #logs Thanks!
I've tried DB, and a support server but no one knew how to create one.
I have tried this:
if (command === "ban") {
if (!message.member.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send("Error: Insufficient Permissions")
if (!message.guild.me.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send(`Error: I have Insufficient Permissions to ban Members`)
let member = message.mentions.members.first() || message.guild.members.get(args[0]);
if (!member) return message.channel.send(`Error: Missing Arguments, define member\nUsage: ${prefix}ban [member] [reason]`)
if (member.hasPermission("BAN_MEMBERS", "KICK_MEMBERS", "MANAGE_SERVER", "ADMINISTRATOR", "MANAGE_MESSAGES", "MANAGE_ROLES")) return message.channel.send(`Error: That user is a mod/admin, I can't do that.`)
if (!member.bannable)
return message.channel.send(`I cannot ban ${member}`)
let reason = args.slice(1).join(" ");
if (!reason) return message.channel.send(`Error: Missing Arguments, define reason\nUsage: ${prefix}ban [member] [reason]`)
let log = db.fetch(`channel_${message.guild.id}`)
if (log === null) return
let logged = message.guild.channels.get(log)
member.ban(reason)
logged.send(`Banned!`)
message.channel.send(`${member.user.tag} has been successfully banned`)
}
I expected it to send a message to the logged channel.
So first of all you create a file for example setlogchannel.js where you save the channel on your db i'm pretty sure you using quick.db so you can just copy and paste that code.
const {discord, MessageEmbed } = require('discord.js');
let db = require('quick.db')
module.exports.run = async (client, message, args) => {
try {
message.delete(15000)
let ads = db.get(`channel_${message.guild.id}`);
if (!message.member.hasPermission('ADMINISTRATOR')) return message.reply("Nope!").then(m => m.delete(15000));
if(!args[0]) return message.reply("You should enter a channel");
if (!ads) {
db.set(`channel_${message.guild.id}`, args[1])
return message.reply("Done, the log channel is :", args).then(msg => msg.delete(15000))
}
} catch (error) {
console.error(error);
let embed = new MessageEmbed()
.setTitle('Something went wrong!')
.setColor('RED');
return message.say(embed).then(msg => msg.delete({ timeout: 15000}));
}
}
module.exports.help = {
name: 'setlogchannel',
aliases: ['slc']
};
And on your index.js you just verify if it exists if it does then you just send it to that channel
if (command === "ban") {
if (!message.member.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send("Error: Insufficient Permissions")
if (!message.guild.me.hasPermission(["BAN_MEMBERS", "ADMINISTRATOR"])) return message.channel.send(`Error: I have Insufficient Permissions to ban Members`)
let member = message.mentions.members.first() || message.guild.members.get(args[0]);
if (!member) return message.channel.send(`Error: Missing Arguments, define member\nUsage: ${prefix}ban [member] [reason]`)
if (member.hasPermission("BAN_MEMBERS", "KICK_MEMBERS", "MANAGE_SERVER", "ADMINISTRATOR", "MANAGE_MESSAGES", "MANAGE_ROLES")) return message.channel.send(`Error: That user is a mod/admin, I can't do that.`)
if (!member.bannable)
return message.channel.send(`I cannot ban ${member}`)
let reason = args.slice(1).join(" ");
if (!reason) return message.channel.send(`Error: Missing Arguments, define reason\nUsage: ${prefix}ban [member] [reason]`)
let log = db.fetch(`channel_${message.guild.id}`)
if (log) {
let logged = message.guild.channels.get(log)
logged.send(`Banned!`)
}
member.ban(reason)
message.channel.send(`${member.user.tag} has been successfully banned`)
}

How can I prohibit the use of the command on certain roles

I want to write code that will check if the roles are in the list. If yes, then they can be issued, and if not, then no. I'm new in discord js.
if(!rMember.roles.has((['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']))) return message.reply("nope.");
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if(!message.member.hasPermission("MANAGE_MEMBERS")) return message.reply();
let rMember = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
if(!rMember) return message.reply("I can't find player.");
let role = args.join(" ").slice(22);
if(!role) return message.reply("specify rang!");
let gRole = message.guild.roles.find(`name`, role);
if(!gRole) return message.reply("I can't find this rang!.");
if(rMember.roles.has(gRole.id)) return message.reply("I can't do it.");
if(!rMember.roles.has((['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']))) return message.reply("nope.");
await(rMember.removeRoles(['00000000000000', '00000000000000, '00000000000000', '00000000000000', '00000000000000']));
await(rMember.addRole(gRole.id));
try{
await rMember.send(`Your rang was changed to ${gRole.name}!`)
}catch(e){
}
}
module.exports.help = {
name: "role"
}
It works without check code, but if I add it, all times, when I will try to change role of user, it gives out "nope".
You could check whether the given role is in the list of allowed roles using Array.includes().
const allowed = ['id', 'anotherID', 'andAnother'];
if (!allowed.includes(gRole.id)) return;
// Returns if the role is *not* in the 'allowed' array.

Resources