discord.js code error: args is not defined - javascript

so I created a code to unban people but since I'm new in coding I have absolutely no idea how to make my code works, this is my code:
client.on("messageCreate", message => {
if(message.content === "!ping"){
message.channel.send("pong")
} else if(message.content === '!unban') {
let permissionToKick = true;
if(!message.member.hasPermission("BAN_MEMBERS")) {
permissionToKick = false
message.channel.send(`**${message.author.username}**, You do not have perms to unban someone`)
}
if(!message.guild.me.hasPermission("BAN_MEMBERS")) {
permissionToKick = false
message.channel.send(`**${message.author.username}**, I do not have perms to unban someone`)
}
if(permissionToKick) {
let userID = args[0] //args[] are not defined, and this will throw an error
message.guild.fetchBans().then(bans=> {
if(!bans.size === 0) {
let bUser = bans.find(b => b.user.id === userID)
if(bUser) {
message.guild.members.unban(bUser.user)
}
}
})
}
}
})
can anyone fix this for me, I know I'm asking a bit much but I'm new in coding and I have no one to ask, please don't be mad

You didn't define it. Try this:
const args = message.content.split(" ");
The final code would look like:
if(permissionToKick) {
// Split the content in an array
const args = message.content.split(" ");
// args[0] would be the command so args[1] is the userID
let userID = args[1]
message.guild.fetchBans().then(bans=> {
if(!bans.size === 0) {
let bUser = bans.find(b => b.user.id === userID)
if(bUser) {
message.guild.members.unban(bUser.user)
}
}
})
}

Related

JoinCommand discord.js issue, Cannot read property 'voice' of undefined

I'm still trying to place an order for the voice bot to enter. I want to make a music system using youtube-dl and I always get this error saying that it doesn't know what "Voice" means in the line "message.member.voiceChannel"
I'm already getting nervous about this problem, I tried to add permissions, but it doesn't work, I want to specify that it uses Discord.js#v12
below you have all the files that I use for the command, such as message event and command class.
Error Code:
2022-06-02 05:39:42 [info] [Command] "n!join" (join) ran by "GhostStru#1982" (780808189226123294) on guild "GhostStru🌿's server" (939865905708552242) channel "#cmmds" (980923745768181831)
TypeError: Cannot read properties of undefined (reading 'voice')
at module.exports.run (C:\Users\Ghost\Desktop\NucleusNEW\commands\music\join.js:23:36)
at module.exports.runCommand (C:\Users\Ghost\Desktop\NucleusNEW\events\message\message.js:417:23)
at module.exports.run (C:\Users\Ghost\Desktop\NucleusNEW\events\message\message.js:391:20)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
This is my Join command
const { joinVoiceChannel } = require('#discordjs/voice');
const { MessageEmbed, Util } = require('discord.js');
const discord = require("discord.js")
const Command = require('../../structures/Command');
module.exports = class extends Command {
constructor(...args) {
super(...args, {
name: 'join',
aliases: ['add'],
usage: "",
category: "Music",
examples: ["join"],
description: "Join into you'r voice channel.",
cooldown: 5,
})
}
async run(client, message, args) {
const voiceChannel = message.member.voice.channel;
if (!message.member.voiceChannel) return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`You must be a voice channel before using this command.`)]});
if (message.guild.me.voiceChannel && message.member.voiceChannel.id !== message.guild.me.voiceChannel.id) return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`You are not in same voice channel.`)]});
try {
joinVoiceChannel({
channelId: message.member.voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
await message.react('👍').catch(() => { });
} catch {
return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`An error occurred while joining the voice channel.`)]});
}
}
}
This is my message event
const Event = require('../../structures/Event');
const { Permissions, Collection } = require("discord.js");
const afk = require("../../models/afk");
const Statcord = require("statcord.js");
const moment = require('moment');
const discord = require("discord.js");
const config = require('./../../config.json');
const { MessageEmbed } = require('discord.js');
const logger = require('../../utils/logger');
const nsfwplease = require('../../assets/json/nfsw.json');
const mongoose = require('mongoose');
const Guild = require('../../database/schemas/Guild');
const User = require('../../database/schemas/User');
const Moderation = require('../../database/schemas/logging');
const Blacklist = require('../../database/schemas/blacklist');
const customCommand = require('../../database/schemas/customCommand');
const autoResponse = require('../../database/schemas/autoResponse');
const autoResponseCooldown = new Set();
const inviteFilter = require('../../filters/inviteFilter');
const linkFilter = require('../../filters/linkFilter');
const maintenanceCooldown = new Set();
const metrics = require('datadog-metrics');
const permissions = require('../../assets/json/permissions.json')
const Maintenance = require('../../database/schemas/maintenance')
require("moment-duration-format");
module.exports = class extends Event {
constructor(...args) {
super(...args);
this.impliedPermissions = new Permissions([
"VIEW_CHANNEL",
"SEND_MESSAGES",
"SEND_TTS_MESSAGES",
"EMBED_LINKS",
"ATTACH_FILES",
"READ_MESSAGE_HISTORY",
"MENTION_EVERYONE",
"USE_EXTERNAL_EMOJIS",
"ADD_REACTIONS"
]);
this.ratelimits = new Collection();
}
async run(message) {
try {
if (!message.guild) return;
if(config.datadogApiKey){
metrics.init({ apiKey: this.client.config.datadogApiKey, host: 'nucleus', prefix: 'nucleus.' });
}
const mentionRegex = RegExp(`^<#!?${this.client.user.id}>$`);
const mentionRegexPrefix = RegExp(`^<#!?${this.client.user.id}>`);
if (!message.guild || message.author.bot) return;
const settings = await Guild.findOne({
guildId: message.guild.id,
}, async (err, guild) => {
if (err) console.log(err)
if (!guild) {
const newGuild = await Guild.create({
guildId: message.guild.id,
prefix: config.prefix || 'p!',
language: "english"
});
}
});
//if (!settings) return message.channel.send('Oops, this server was not found in the database. Please try to run the command again now!');
if (message.content.match(mentionRegex)) {
const proofita = `\`\`\`css\n[ Prefix: ${settings.prefix || '!'} ]\`\`\``;
const proofitaa = `\`\`\`css\n[ Help: ${settings.prefix || '!'}help ]\`\`\``;
const embed = new MessageEmbed()
.setTitle('Hello, I\'m Nucleus. What\'s Up?')
.addField(`Prefix`,proofita, true)
.addField(`Usage`,proofitaa, true)
.setDescription(`\nIf you like Nucleus, Consider [voting](https://top.gg/bot/980373513691090974), or [inviting](https://discord.com/oauth2/authorize?client_id=980373513691090974&scope=bot&permissions=470150262) it to your server! Thank you for using Nucleus, we hope you enjoy it, as we always look forward to improve the bot`)
.setFooter('Thank you for using Nucleus!!')
.setColor('#FF2C98')
message.channel.send(embed);
}
if(config.datadogApiKey){
// Add increment after every darn message lmfao!
metrics.increment('messages_seen');
}
// Filters
if (settings && await inviteFilter(message)) return;
if (settings && await linkFilter(message)) return;
let mainPrefix = settings ? settings.prefix : '!';
const prefix = message.content.match(mentionRegexPrefix) ?
message.content.match(mentionRegexPrefix)[0] : mainPrefix
const guildDB = await Guild.findOne({
guildId: message.guild.id
});
const moderation = await Moderation.findOne({
guildId: message.guild.id
});
if(!moderation){
Moderation.create({
guildId: message.guild.id
})
}
// maintenance mode
const maintenance = await Maintenance.findOne({
maintenance: "maintenance"
})
const userBlacklistSettings = await Blacklist.findOne({ discordId: message.author.id,});
const guildBlacklistSettings = await Blacklist.findOne({ guildId: message.guild.id });
//autoResponse
const autoResponseSettings = await autoResponse.findOne({ guildId: message.guild.id, name: message.content.toLowerCase() });
if (autoResponseSettings && autoResponseSettings.name) {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
if(maintenance && maintenance.toggle == "true") return;
if(autoResponseCooldown.has(message.author.id)) return message.channel.send(`${message.client.emoji.fail} Slow Down - ${message.author}`)
message.channel.send(autoResponseSettings.content
.replace(/{user}/g, `${message.author}`)
.replace(/{user_tag}/g, `${message.author.tag}`)
.replace(/{user_name}/g, `${message.author.username}`)
.replace(/{user_ID}/g, `${message.author.id}`)
.replace(/{guild_name}/g, `${message.guild.name}`)
.replace(/{guild_ID}/g, `${message.guild.id}`)
.replace(/{memberCount}/g, `${message.guild.memberCount}`)
.replace(/{size}/g, `${message.guild.memberCount}`)
.replace(/{guild}/g, `${message.guild.name}`)
.replace(/{member_createdAtAgo}/g, `${moment(message.author.createdTimestamp).fromNow()}`)
.replace(/{member_createdAt}/g, `${moment(message.author.createdAt).format('MMMM Do YYYY, h:mm:ss a')}`))
autoResponseCooldown.add(message.author.id)
setTimeout(()=>{
autoResponseCooldown.delete(message.author.id)
}, 2000)
return;
}
//afk
let language = require(`../../data/language/english.json`)
if(guildDB) language = require(`../../data/language/${guildDB.language}.json`)
moment.suppressDeprecationWarnings = true;
if(message.mentions.members.first()){
if(maintenance && maintenance.toggle == "true") return;
const afklist = await afk.findOne({ userID: message.mentions.members.first().id, serverID: message.guild.id});
if(afklist){
await message.guild.members.fetch(afklist.userID).then(member => {
let user_tag = member.user.tag;
return message.channel.send(`**${afklist.oldNickname || user_tag || member.user.username}** ${language.afk6} ${afklist.reason} **- ${moment(afklist.time).fromNow()}**`).catch(() => {});
});
}
}
const afklis = await afk.findOne({ userID: message.author.id, serverID: message.guild.id});
if(afklis) {
if(maintenance && maintenance.toggle == "true") return;
let nickname = `${afklis.oldNickname}`;
message.member.setNickname(nickname).catch(() => {});
await afk.deleteOne({ userID: message.author.id });
return message.channel.send(new discord.MessageEmbed().setColor('GREEN').setDescription(`${language.afk7} ${afklis.reason}`)).then(m => {
setTimeout(() => {
m.delete().catch(() => {});
}, 10000);
});
};
if (!message.content.startsWith(prefix)) return;
// eslint-disable-next-line no-unused-vars
const [cmd, ...args] = message.content.slice(prefix.length).trim().split(/ +/g);
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
// maintenance mode
if(!this.client.config.developers.includes(message.author.id)){
if(maintenance && maintenance.toggle == "true") {
if(maintenanceCooldown.has(message.author.id)) return;
message.channel.send(`Nucleus is currently undergoing maintenance which won't allow anyone to access Nucleus Commands. Feel free to try again later. For updates: https://discord.gg/FqdH4sfKBg`)
maintenanceCooldown.add(message.author.id);
setTimeout(() => {
maintenanceCooldown.delete(message.author.id)
}, 10000);
return;
}
}
// Custom Commands
const customCommandSettings = await customCommand.findOne({ guildId: message.guild.id, name: cmd.toLowerCase() });
const customCommandEmbed = await customCommand.findOne({ guildId: message.guild.id, name: cmd.toLowerCase() });
if (customCommandSettings && customCommandSettings.name && customCommandSettings.description) {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
let embed = new MessageEmbed()
.setTitle(customCommandEmbed.title)
.setDescription(customCommandEmbed.description)
.setFooter(``)
if( customCommandEmbed.image !== "none") embed.setImage(customCommandEmbed.image)
if( customCommandEmbed.thumbnail !== "none") embed.setThumbnail(customCommandEmbed.thumbnail)
if( customCommandEmbed.footer !== "none") embed.setFooter(customCommandEmbed.footer)
if( customCommandEmbed.timestamp !== "no") embed.setTimestamp()
if( customCommandEmbed.color == 'default') {
embed.setColor(message.guild.me.displayHexColor)
} else embed.setColor(`${customCommandEmbed.color}`)
return message.channel.send(embed)
}
if (customCommandSettings && customCommandSettings.name && !customCommandSettings.description && customCommandSettings.json == "false") {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
return message.channel.send(customCommandSettings.content
.replace(/{user}/g, `${message.author}`)
.replace(/{user_tag}/g, `${message.author.tag}`)
.replace(/{user_name}/g, `${message.author.username}`)
.replace(/{user_ID}/g, `${message.author.id}`)
.replace(/{guild_name}/g, `${message.guild.name}`)
.replace(/{guild_ID}/g, `${message.guild.id}`)
.replace(/{memberCount}/g, `${message.guild.memberCount}`)
.replace(/{size}/g, `${message.guild.memberCount}`)
.replace(/{guild}/g, `${message.guild.name}`)
.replace(/{member_createdAtAgo}/g, `${moment(message.author.createdTimestamp).fromNow()}`)
.replace(/{member_createdAt}/g, `${moment(message.author.createdAt).format('MMMM Do YYYY, h:mm:ss a')}`)
)
}
if (customCommandSettings && customCommandSettings.name && !customCommandSettings.description && customCommandSettings.json == "true") {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
const command = JSON.parse(customCommandSettings.content)
return message.channel.send(command).catch((e)=>{message.channel.send(`There was a problem sending your embed, which is probably a JSON error.\nRead more here --> https://nucleus.xyz/embeds\n\n__Error:__\n\`${e}\``)})
}
if (command) {
await User.findOne({
discordId: message.author.id
}, (err, user) => {
if (err) console.log(err)
if (!user) {
const newUser = new User({
discordId: message.author.id
})
newUser.save()
}
});
const disabledCommands = guildDB.disabledCommands;
if (typeof(disabledCommands) === 'string') disabledCommands = disabledCommands.split(' ');
const rateLimit = this.ratelimit(message, cmd);
if (!message.channel.permissionsFor(message.guild.me).has('SEND_MESSAGES')) return;
// Check if user is Blacklisted
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) {
logger.warn(`${message.author.tag} tried to use "${cmd}" command but the user is blacklisted`, { label: 'Commands' })
return message.channel.send(`${message.client.emoji.fail} You are blacklisted from the bot :(`);
}
// Check if server is Blacklisted
if (guildBlacklistSettings && guildBlacklistSettings.isBlacklisted) {
logger.warn(`${message.author.tag} tried to use "${cmd}" command but the guild is blacklisted`, { label: 'Commands' })
return message.channel.send(`${message.client.emoji.fail} This guild is Blacklisted :(`);
}
let number = Math.floor((Math.random() * 10) + 1);
if (typeof rateLimit === "string") return message.channel.send(` ${message.client.emoji.fail} Please wait **${rateLimit}** before running the **${cmd}** command again - ${message.author}\n\n${number === 1 ? "*Did You know that Nucleus has its own dashboard? `https://nucleus.xyz/dashboard`*" : ""}${number === 2 ? "*You can check our top.gg page at `https://vote.nucleus.xyz`*" : ""}`).then((s)=>{
message.delete().catch(()=>{});
s.delete({timeout: 4000}).catch(()=>{})
}).catch(()=>{})
if (command.botPermission) {
const missingPermissions =
message.channel.permissionsFor(message.guild.me).missing(command.botPermission).map(p => permissions[p]);
if (missingPermissions.length !== 0) {
const embed = new MessageEmbed()
.setAuthor(`${this.client.user.tag}`, message.client.user.displayAvatarURL({ dynamic: true }))
.setTitle(`<:wrong:822376943763980348> Missing Bot Permissions`)
.setDescription(`Command Name: **${command.name}**\nRequired Permission: **${missingPermissions.map(p => `${p}`).join(' - ')}**`)
.setTimestamp()
.setFooter('https://nucleus.xyz')
.setColor(message.guild.me.displayHexColor);
return message.channel.send(embed).catch(()=>{})
}
}
if (command.userPermission) {
const missingPermissions =
message.channel.permissionsFor(message.author).missing(command.userPermission).map(p => permissions[p]);
if (missingPermissions.length !== 0) {
const embed = new MessageEmbed()
.setAuthor(`${message.author.tag}`, message.author.displayAvatarURL({ dynamic: true }))
.setTitle(`<:wrong:822376943763980348> Missing User Permissions`)
.setDescription(`Command Name: **${command.name}**\nRequired Permission: **${missingPermissions.map(p => `${p}`).join('\n')}**`)
.setTimestamp()
.setFooter('https://nucleus.xyz')
.setColor(message.guild.me.displayHexColor);
return message.channel.send(embed).catch(()=>{})
}
}
if(disabledCommands.includes(command.name || command)) return;
if (command.ownerOnly) {
if (!this.client.config.developers.includes(message.author.id)) return
}
if(config.datadogApiKey){
metrics.increment('commands_served');
}
if (command.disabled) return message.channel.send(`The owner has disabled the following command for now. Try again Later!\n\nFor Updates: https://discord.gg/duBwdCvCwW`)
if (command.nsfwOnly && !message.channel.nsfw && message.guild) return message.channel.send(`${nsfwplease[Math.round(Math.random() * (nsfwplease.length - 1))]}`)
Statcord.ShardingClient.postCommand(cmd, message.author.id, this.client);
await this.runCommand(message, cmd, args)
.catch(error => {
if(config.datadogApiKey){
metrics.increment('command_error');
}
return this.client.emit("commandError", error, message, cmd);
})
}
} catch(error) {
if(config.datadogApiKey){
metrics.increment('command_error');
}
return this.client.emit("fatalError", error, message);
}
}
async runCommand(message, cmd, args) {
if (!message.channel.permissionsFor(message.guild.me) || !message.channel.permissionsFor(message.guild.me).has('EMBED_LINKS'))
return message.channel.send(`${message.client.emoji.fail} Missing bot Permissions - **Embeds Links**`)
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
logger.info(`"${message.content}" (${command.name}) ran by "${message.author.tag}" (${message.author.id}) on guild "${message.guild.name}" (${message.guild.id}) channel "#${message.channel.name}" (${message.channel.id})`, { label: 'Command' })
await command.run(message, args)
}
ratelimit(message, cmd) {
try {
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
if (message.author.permLevel > 4) return false;
const cooldown = command.cooldown * 1000
const ratelimits = this.ratelimits.get(message.author.id) || {}; // get the ENMAP first.
if (!ratelimits[command.name]) ratelimits[command.name] = Date.now() - cooldown; // see if the command has been run before if not, add the ratelimit
const difference = Date.now() - ratelimits[command.name]; // easier to see the difference
if (difference < cooldown) { // check the if the duration the command was run, is more than the cooldown
return moment.duration(cooldown - difference).format("D [days], H [hours], m [minutes], s [seconds]", 1); // returns a string to send to a channel
} else {
ratelimits[command.name] = Date.now(); // set the key to now, to mark the start of the cooldown
this.ratelimits.set(message.author.id, ratelimits); // set it
return true;
}
} catch(e) {
this.client.emit("fatalError", error, message);
}
}
}
And this is my Command class
module.exports = class Command {
constructor(client, name, options = {}) {
this.client = client;
this.name = options.name || name;
this.aliases = options.aliases || [];
this.description = options.description || "No description provided.";
this.category = options.category || "General";
this.usage = `${this.name} ${options.usage || ''}` || "No usage provided.";
this.examples = options.examples || [];
this.disabled = options.disabled || false;
this.cooldown = "cooldown" in options ? options.cooldown : 5 || 5;
this.ownerOnly = options.ownerOnly || false;
this.guildOnly = options.guildOnly || false;
this.nsfwOnly = options.nsfwOnly || false;
this.botPermission = options.botPermission || ['SEND_MESSAGES', 'EMBED_LINKS'];
this.userPermission = options.userPermission || null;
}
// eslint-disable-next-line no-unused-vars
async run(message, args) {
throw new Error(`The run method has not been implemented in ${this.name}`);
}
reload() {
return this.store.load(this.file.path);
}
}
In this "code cases" i put my personal codes, and i dont know where can i find the problem, or what can i modifiy in my code, thats all i can say..
Can someone tell me what can i do?...
Its a simple join command, and he cannot read voice.channel...

Declaration Or Statment expected Javascript/Discord.js

So Im coding in javascript a discord bot and then what happens is i get an Declaration Or Statment expected error even if its not needed
const client = new Discord.Client({ intents: 32767 });
client.on("ready", () => {
console.log("✔✔ online")
})
client.on("messageCreate", message => {
const prefix = ">"
if(!message.content.startsWith(prefix)) return;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (message.content === `${prefix}test`) {
message.reply("Working")
}
if (cmd == `${prefix}kick`) {
if(!args[0]) return message.reply("Please Mention Someone or Put That Persons ID or Put That Persons Username to Kick The User Out Of The Server!");
const member = (message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(x => x.user.username.toLowerCase() === args.slice.join(" ") || x.user.username === args[0]));
if(!message.member.permissions.has("KICK_MEMBERS")) return message.reply("Since When You Have a kick members perm" || "You need to have the kick permission perm to use this command");
});
client.login("not showing token ");```
You have a wrong synatax. Your code should be
const client = new Discord.Client({ intents: 32767 });
client.on("ready", () => {
console.log("✔✔ online")
})
client.on("messageCreate", message => {
const prefix = ">"
if(!message.content.startsWith(prefix)) return;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (message.content === `${prefix}test`) {
message.reply("Working")
}
if (cmd == `${prefix}kick`) {
if(!args[0]) return message.reply("Please Mention Someone or Put That Persons ID or Put That Persons Username to Kick The User Out Of The Server!");
const member = (message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(x => x.user.username.toLowerCase() === args.slice.join(" ") || x.user.username === args[0]));
if(!message.member.permissions.has("KICK_MEMBERS")) return message.reply("Since When You Have a kick members perm" || "You need to have the kick permission perm to use this command");
};
});
client.login("not showing token ");

TypeError: Cannot read property 'has' of undefined // Discord.js

So, I was creating a bot for my Discord server. And I got this error. Please remember that I am an amateur :). Thanks in advance, appreciate it^^.
const config = require('../config.js');
module.exports = message => {
let client = message.client;
if (message.author.bot) return;
if (!message.content.startsWith(config.prefix)) return;
let command = message.content.split(' ')[0].slice(config.prefix.length);
let params = message.content.split(' ').slice(1);
let cmd;
if (client.commands.has(command)) {
cmd = client.commands.get(command);
} else if (client.aliases.has(command)) {
cmd = client.commands.get(client.aliases.get(command));
};
if (cmd) {
if(!message.guild) {
if(cmd.config.guildOnly === true) {
return;
};
};
if (cmd.config.permLevel) {
if(cmd.config.permLevel === "BOT_OWNER") {
if(!config.geliştiriciler.includes(message.author.id)) {
message.channel.send(`Bu komutu kullanabilmek için \`${cmd.config.permLevel}\` yetkisine sahip olmalısın.`).then(msg => msg.delete({timeout: 3000}));
return;
}
}
if(!message.member.hasPermission(cmd.config.permLevel)) {
message.channel.send(`Bu komutu kullanabilmek için \`${cmd.config.permLevel}\` yetkisine sahip olmalısın.`).then(msg => msg.delete({timeout: 3000}));
return;
};
};
cmd.run(client, message, params);
};
};
Add some booleans for checking if client.commands/client.aliases is undefined.
if (client.commands && client.commands.has(command)) {
cmd = client.commands.get(command);
} else if (client.aliases && client.aliases.has(command)) {
cmd = client.commands.get(client.aliases.get(command));
};
At line no 7, please try this
const cmd =
message.client.commands.get(command) ||
message.client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(command) // if you're also using aliases
);
if (!command) return;

how do i unban user with discord.js

hey i need my code which i wrote fixed because it wont work here it is the terminal shows the args arent defined if there is some how a different way to do this its accepted too thanks in advance. <3
const Discord = require('discord.js');
const { Client, MessageEmbed } = require('discord.js');
const bot = new Client();
const token = 'tokengoeshere';
bot.on('message', message => {
if (!message.guild) return;
const ubWords = ["!unban", "?unban", ".unban","-unban","!ub","?ub",".ub","-ub"];
if (ubWords.some(word => message.content.toLowerCase().includes(word)) )
if(!message.member.hasPermission("BAN_MEMBERS")) {
return message.reply(`, You do not have perms to unban someone`)
}
if(!message.guild.me.hasPermission("BAN_MEMBERS")) {
return message.reply(`, I do not have perms to unban someone`)
}
let userID = args[0]
message.guild.fetchBans().then(bans=> {
if(bans.size == 0) return
let bUser = bans.find(b => b.user.id == userID)
if(!bUser) return
message.guild.members.unban(bUser.user)
})
});
bot.login(token);
let userID = args[0]
if (!userID) return message.reply("Please specify the user ID you wish to unban!")
try {
message.guild.fetchBans().then(bans => {
if(bans.size === 0) {
return message.reply("There is no users banned!")
} else {
message.guild.members.unban(userID)
}
})
} catch (err) {
console.log(err)
}
You can simply define args like this:
const args = message.content.slice('?'.length).trim().split(/ +/g)
Put it after the message.guild check

Finding users with two or more roles discord.js

I'll post my entire code because on other forums people were confused:
I am trying to make a discord bot that can display a list of users that have a specific role. I know I need to list all roles in an array and then compare the user inputs to see if they match the strings in the array. Then it will check for users who have all of the user input roles and display them.
Example: if Spookybot and SpookySeed both have the role of admin but only Spookybot has the role of moderator as well, if i type role admin moderator the result should only display Spookybot since he has both roles. Any suggestions on how to accomplish this?
const Discord = require ('discord.js')
const { MessageEmbed } = require ('discord.js')
const { type } = require('os')
const { receiveMessageOnPort } = require('worker_threads')
const client = new Discord.Client()
client.on('ready', () => {
console.log("Connected as " + client.user.tag)
client.user.setActivity("you senpai!", {type: "LISTENING"})
})
client.on('message', (receivedMessage) => {
if (receivedMessage.author == client.user) {
return
}
if (receivedMessage.content.startsWith("``")) {
processCommand(receivedMessage)
}
})
function processCommand(receivedMessage) {
let fullCommand = receivedMessage.content.substr(2)
let splitCommand = fullCommand.split(" ")
let primaryCommand = splitCommand[0]
let argument = splitCommand.slice(1)
if (primaryCommand == "help") {
helpCommand(argument, receivedMessage)
}
else if (primaryCommand == "role") {
roleDisplayCommand(argument, receivedMessage)
}
else {
receivedMessage.channel.send("Uknown command")
}
}
function helpCommand(argument, receivedMessage) {
if (arguments.length > 0) {
receivedMessage.channel.send("It looks like you might need help with but i am still in beta sorry!")
} else {
receivedMessage.channel.send("Unknown command")
}
}
function roleDisplayCommand(arguments, receivedMessage) {
if (arguments.length > 0) {
const roleNames = receivedMessage.content.split(" ").slice(1);
receivedMessage.author.send(`These users have the ${roleNames.join(" ")} role(s)` )
const userList = roleNames.map(roleName => receivedMessage.guild.roles.cache.find(r => r.name === roleName).members.map(m=>m.user.tag).join("\n"))
const sortedList = userList.join().split(",").filter((item, index, self) => self.indexOf(item) === index);
receivedMessage.author.send(sortedList.join("\n"))
}
else {
receivedMessage.channel.send("Unknown command")
}
}
client.login("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
You can use filter on your guild users list:
const specificsUsers = users.filter(user =>
user.roles.has(role1.id) && user.roles.has(role2.id)
)
I'd iterate over the roles and filter out the users without the roles. Something like this should work.
function roleDisplayCommand(arguments, receivedMessage) {
...
const roleNames = receivedMessage.content.split(" ").slice(1);
receivedMessage.author.send(`These users have the ${roleNames.join(" ")} role(s)` )
let users = receivedMessage.guild.members.cache;
const userList = roleNames.every(
role => {
users = users.filter(u => u.roles.cache.some(r => r.name === role));
});
// Either
receivedMessage.author.send(Array.from(users.values()).join("\n"));
// or, but not tested and might have some weird behaviors
receivedMessage.author.send(Array.prototype.join.call(users, "\n"));
...
}

Categories

Resources