Break up if statements to multiple modules - node.js

I would like to break up my following code into multiple files for management instead of having everything run on the main file. The whole code is located as one Node.js modal know as index.js I would like to break the code up into multiple files management.js and interantion.js and they communicate with node.js
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
const ms = require("ms");
client.on("ready", () => {
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
client.user.setGame(config.game);
});
client.on("guildCreate", guild => {
console.log(`New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`);
client.user.setGame(`on ${client.guilds.size} servers`);
});
client.on("guildDelete", guild => {
console.log(`I have been removed from: ${guild.name} (id: ${guild.id})`);
});
client.on("guildMemberAdd", function(member) {
//Welcomes a user
member.guild.channels.find("name", "general").send("Please welcome " + member.toString() + " to the server! " + member.toString() + " Make sure to read the rules and enjoy your stay :heart:." + " https://imgur.com/a/pCcSm");
});
//managment
client.on("message", async message => {
if (message.author.bot) return;
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
var mutedrole = message.guild.roles.find("name", "muted");
//Managment
if (command === "say") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
const sayMessage = args.join(" ");
message.delete().catch(O_o => {});
message.channel.send(sayMessage);
}
if (command === "kick") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.kickable) return message.reply("I cannot kick this user! Do they have a higher role? Do I have kick permissions?");
let reason = args.slice(1).join(' ');
if (!reason) return message.reply("Please indicate a reason for the kick!");
await member.kick(reason).catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason}`);
}
if (command === "ban") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.bannable) return message.reply("I cannot ban this user! Do they have a higher role? Do I have ban permissions?");
let reason = args.slice(1).join(' ');
if (!reason) return message.reply("Please indicate a reason for the ban!");
await member.ban(reason).catch(error => message.reply(`Sorry ${message.author} I couldn't ban because of : ${error}`));
message.reply(`${member.user.tag} has been banned by ${message.author.tag} because: ${reason}`);
}
if (command === "purge") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
const deleteCount = parseInt(args[0], 10);
if (!deleteCount || deleteCount < 2 || deleteCount > 100) return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
const fetched = await message.channel.fetchMessages({
count: deleteCount
});
message.channel.bulkDelete(fetched).catch(error => message.reply(`Couldn't delete messages because of: ${error}`));
}
if (command == "mute") {
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a member");
let muteRole = message.guild.roles.find("name", "Muted");
if (!muteRole) return message.reply("Role: Muted not found.");
let params = message.content.split(" ").slice(1);
let time = args[1];
if (!time) return message.reply("Please specify how long the user should be muted.");
member.addRole(muteRole.id);
message.channel.send(`You've been muted for ${ms(ms(time), {long: true})}, ${member.user.tag}`);
setTimeout(function() {
member.removeRole(muteRole.id);
message.channel.send(`${member.user.tag} You were unmuted! The mute lasted: ${ms(ms(time), {long: true})}`)
}, ms(time));
}
//interaction
if (command === "ping") {
const m = await message.channel.send("Pong");
m.edit(`Fine here you go >.<! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
if (command == "drops") {
message.channel.send("https://docs.google.com/spreadsheets/d/1_SlTjrVRTgHgfS7sRqx4CeJMqlz687HdSlYqiW-JvQA/htmlview?sle=true#gid=0");
}
});
client.login(config.token);
The result look something like this:
index.js
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
const ms = require("ms");
client.on("ready", () => {
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
client.user.setGame(config.game);
});
client.on("guildCreate", guild => {
console.log(`New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`);
client.user.setGame(`on ${client.guilds.size} servers`);
});
client.on("guildDelete", guild => {
console.log(`I have been removed from: ${guild.name} (id: ${guild.id})`);
});
client.on("guildMemberAdd", function(member) {
//Welcomes a user
member.guild.channels.find("name", "general").send("Please welcome " + member.toString() + " to the server! " + member.toString() + " Make sure to read the rules and enjoy your stay :heart:." + " https://imgur.com/a/pCcSm");
});
//managment
client.on("message", async message => {
if (message.author.bot) return;
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
});
client.login(config.token);
managment.js
//Managment
if (command === "say") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
const sayMessage = args.join(" ");
message.delete().catch(O_o => {});
message.channel.send(sayMessage);
}
if (command === "kick") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.kickable) return message.reply("I cannot kick this user! Do they have a higher role? Do I have kick permissions?");
let reason = args.slice(1).join(' ');
if (!reason) return message.reply("Please indicate a reason for the kick!");
await member.kick(reason).catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason}`);
}
if (command === "ban") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.bannable) return message.reply("I cannot ban this user! Do they have a higher role? Do I have ban permissions?");
let reason = args.slice(1).join(' ');
if (!reason) return message.reply("Please indicate a reason for the ban!");
await member.ban(reason).catch(error => message.reply(`Sorry ${message.author} I couldn't ban because of : ${error}`));
message.reply(`${member.user.tag} has been banned by ${message.author.tag} because: ${reason}`);
}
if (command === "purge") {
if (!message.member.roles.some(r => ["Management"].includes(r.name))) return message.reply("Sorry, you don't have permissions to use this!");
const deleteCount = parseInt(args[0], 10);
if (!deleteCount || deleteCount < 2 || deleteCount > 100) return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
const fetched = await message.channel.fetchMessages({
count: deleteCount
});
message.channel.bulkDelete(fetched).catch(error => message.reply(`Couldn't delete messages because of: ${error}`));
}
if (command == "mute") {
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a member");
let muteRole = message.guild.roles.find("name", "Muted");
if (!muteRole) return message.reply("Role: Muted not found.");
let params = message.content.split(" ").slice(1);
let time = args[1];
if (!time) return message.reply("Please specify how long the user should be muted.");
member.addRole(muteRole.id);
message.channel.send(`You've been muted for ${ms(ms(time), {long: true})}, ${member.user.tag}`);
setTimeout(function() {
member.removeRole(muteRole.id);
message.channel.send(`${member.user.tag} You were unmuted! The mute lasted: ${ms(ms(time), {long: true})}`)
}, ms(time));
}
interaction.js
//interaction
if (command === "ping") {
const m = await message.channel.send("Pong");
m.edit(`Fine here you go >.<! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
if (command == "drops") {
message.channel.send("https://docs.google.com/spreadsheets/d/1_SlTjrVRTgHgfS7sRqx4CeJMqlz687HdSlYqiW-JvQA/htmlview?sle=true#gid=0");
}
I have tried using a required method, but it gives me file not found error.

I'm not entirely sure how you could do this, possibly by using fs or something similar. You could, however, use commando.js rather than discord.js.
Commando.js has one index file for logging in and so on, and then each command is set up into different categories under folders and each command has its own file. It's certainly something to look into.

Related

tag a user using discord node js

I want to make a command that tags a user when there name got mentoined. But now the bot only tags the username and not a nickname the person has in the server
client.on("message", message => {
if(message.content === 'test'){
message.channel.send("works")
console.log("logged the message")
}
})
client.on("message", message => {
const list = message.guild;
list.members.cache.each(member => {
pinging = member.user.id
console.log(member.user.username)
if(message.content.includes(member.user.username)){
message.channel.send(`<#${pinging}>`)
}
})
})
can anyone help?
First thing, you only want to have one listener for the message event, so try this code:
client.on("message", message => {
if (message.content === 'test'){
message.channel.send("works")
console.log("logged the message")
}
// insert choices from below here
})
If you want it to listen for a member being tagged
const mentionedMember = message.mentions.members.first()
if (mentionedMember){
message.channel.send(`${mentionedMember}`)
}
Now if you want it to listen for username instead of #username
const args = message.content.slice().trim().split(' ')
const guild = message.guild
args.forEach(arg => {
const member = guild.members.cache.find(member => member.user.username.toLowerCase() === arg.toLowerCase())
if (member) {
message.channel.send(`${member}`)
} else {
return
}
})
To listen for displayName
const args = message.content.slice().trim().split(' ')
const guild = message.guild
args.forEach(arg => {
const member = guild.members.cache.find(member => member.displayName.toLowerCase() === arg.toLowerCase())
if (member) {
message.channel.send(`${member}`)
} else {
return
}
})

Discord Reaction Roles not working after the bot restarts

Recently I decided to update my Discord Bot from V12 to V13 and I encountered a problem with my Reaction Roles.
It only works if the bot doesn't restart. It worked perfectly on discord.js 12.5.3 and now I'm using discord.js 13.5.0. Could you guys help me with the problem?
Here is my code:
const { MessageEmbed } = require("discord.js");
const Discord = require('discord.js');
const { Client } = require('discord.js');
const client = new Client({
intents: 32767,
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});
const config2 = require("../config2");
module.exports = async (client, message, args) => {
client.on('messageCreate', async message => {
if (message.content.startsWith("22ar")) {
const embed = new MessageEmbed()
.setColor('#FFA500')
.setTitle(`Pick the roles`)
.setDescription(`πŸ”“ **- You unlock yourself.**
βœ… **- You get access to the server.**
πŸ’œ **- You get notified for X things.**
[πŸ”“, βœ…] - obligatory.
[πŸ’œ] - optional.
\`Wait at least 30 seconds and try again if you don't get the roles.\``)
const msg = await message.channel.send({ embeds: [ embed ] })
msg.react('πŸ”“')
msg.react('βœ…')
msg.react('πŸ’œ')
}
})
const CHANNEL = config2.ROLECHANNEL;
const UROLE = config2.UNLOCKROLE;
const MROLE = config2.MEMBERROLE;
const NROLE = config2.NOTIFYROLE;
const unlockEmoji = 'πŸ”“';
const checkEmoji = 'βœ…';
const notifyEmoji = 'πŸ’œ';
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Fetching message failed: ', error);
return;
}
}
if (!user.bot) {
if(reaction.message.channel.id === CHANNEL) {
if (reaction.emoji.name == checkEmoji) {
const memberRole = reaction.message.guild.roles.cache.find(r => r.id === MROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.add(MROLE);
}
if (reaction.emoji.name == unlockEmoji) {
const unlockRole = reaction.message.guild.roles.cache.find(r => r.id === UROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.remove(UROLE)
}
if (reaction.emoji.name == notifyEmoji) {
const notifyRole = reaction.message.guild.roles.cache.find(r => r.id === NROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.add(NROLE)
}
}
client.on('messageReactionRemove', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Fetching message failed: ', error);
return;
}
}
if (!user.bot) {
if(reaction.message.channel.id === CHANNEL) {
if (reaction.emoji.name == checkEmoji) {
const memberRole = reaction.message.guild.roles.cache.find(r => r.id === MROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.remove(memberRole);
}
if (reaction.emoji.name == unlockEmoji) {
const unlockRole = reaction.message.guild.roles.cache.find(r => r.id === UROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.remove(unlockRole)
}
if (reaction.emoji.name == notifyEmoji) {
const notifyRole = reaction.message.guild.roles.cache.find(r => r.id === NROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.remove(notifyRole)
}
}
}
})
}
})
}
I am not getting any error in the console and the bot continues to work as usual.
Thank you for your attention.
Messages sent before your bot started are uncached unless you fetch them first. By default, the library does not emit client events if the data received and cached is not sufficient to build fully functional objects. Since version 12, you can change this behavior by activating partials.
Official guide about this here (Listening for reactions on old messages).

Discord.JS Reaction collector not working

const optionsEmbed = new Discord.MessageEmbed()
.setTitle("What would you like to setup?")
.setDescription(":one: Prefix\n:two: Mod Log Channel")
.setColor('RANDOM');
message.channel.send(optionsEmbed)
.then(async (msg) => {
await msg.react('1️⃣');
await msg.react('2️⃣');
const filter = (reaction, user) => {
return reaction.emoji.name === '1️⃣' || reaction.emoji.name === '2️⃣' && user.id === message.author.id;
};
const collector = message.createReactionCollector(filter, {
time: 30000
});
let collected = 0;
collector.on('collect', (reaction, user) => {
collected++;
if (reaction.emoji.name === "one") return managePrefix();
if (reaction.emoji.name === "two") return manageModLogChannel();
msg.delete();
collector.end();
});
collector.on('end', collected => {
if (collected === 0) return message.channel.send("You took too long to react, cancelled setup.");
});
});
async function managePrefix() {
const getCurrentPrefix = await message.getServerDatabase(message.guild.id, "prefix")
const currentPrefixEmbed = new Discord.MessageEmbed()
.setTitle("Info")
.setDescription("Current Prefix: " + getCurrentPrefix + "\n\nPlease reply with the new prefix or *cancel* to cancel.")
.setColor('RED');
message.channel.send(currentPrefixEmbed)
.then(async (msg) => {
const filter = (msgg, user) => {
return user.id == message.author.id;
}
const collector = message.channel.createMessageCollector(filter, {
time: 60000
});
let collected = 0;
collector.on('collect', async (m) => {
collected++;
msg.delete()
if (m.content.toLowerCase() === "cancel") {
m.delete();
return collector.end()
}
await message.setServerDatabase(message.guild.id, "prefix", m.content)
await m.reply("Set prefix to `" + m.content + "`");
collector.end()
});
collector.on('end', collected => {
if (collected === 0) return message.channel.send("You took too long to respond, cancelled setup.")
});
});
}
async function manageModLogChannel() {
const getCurrentPrefix = await message.getServerDatabase(message.guild.id, "modLogChannel")
const currentPrefixEmbed = new Discord.MessageEmbed()
.setTitle("Info")
.setDescription("Current ModLogChannel: <#" + getCurrentPrefix + ">\n\nPlease reply with the new channel or *cancel* to cancel.")
.setColor('RED');
message.channel.send(currentPrefixEmbed)
.then(async (msg) => {
const filter = (msgg, user) => {
return user.id == message.author.id;
}
const collector = message.channel.createMessageCollector(filter, {
time: 60000
});
let collected = 0;
collector.on('collect', async (m) => {
collected++;
msg.delete()
if (m.content.toLowerCase() === "cancel") {
m.delete();
return collector.end()
}
if (!m.mentions.channels.first()) {
m.delete()
message.channel.send("Not a valid channel, cancelled setup.");
return collector.end();
}
const channel = m.mentions.channels.first();
await message.setServerDatabase(message.guild.id, "modLogChannel", channel.id)
await m.reply("Set channel to `<#" + m.content + ">`");
collector.end()
});
collector.on('end', collected => {
if (collected === 0) return message.channel.send("You took too long to respond, cancelled setup.")
});
});
}
I am trying to make a config command, upon reacting to the first embed.. nothing happens.
If that first listener is not working, then I doubt the message collectors are working either.
The user should be able to react to a main embed which asks them if they want to change the prefix or mod log channel, from there it will then ask them what they want to change it to with the cancel option, it then saves it in the database using the custom functions (message.getServerDatabase and message.setServerDatabase())
Does anyone know what I'm doing wrong?
The reason it is not working as you want it to is that you are calling the .createReactionCollector() method on the wrong Message object. You should create the reaction collector on msg instead of message.
Like this:
const collector = msg.createReactionCollector(filter, {
time: 30000
});
Also collector.end() is not a function, you probably want to use collector.stop() instead.

How to only allow certian roles ot use this command

I'm trying to only allow people with the Staff role to run this command.
Basically what the command does, is allowing a bot to DM users
the command is <prefix>send #RandomUserName <message>
I am trying to prevent random users from abusing this command to flood other players DMs.
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message.member.roles.cache.some(role => role.name === 'Staff')) return;
if (command === 'send'){
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return mention;
}
}
const user = getUserFromMention(args[0])
let MessageDM = args[1]
client.users.cache.get(user).send(MessageDM);
}
// ...
});
You're missing a negation (!) in your role-check. Your current if only evaluates to true, when the role is present. But you want to return if the role is not present.
Change your line
if (message.member.roles.cache.some(role => role.name === 'Staff')) return;
to
if (!message.member.roles.cache.some(role => role.name === 'Staff')) return;
Also, as I mentioned in my comment, putting a function inside an if is never a good idea. I'd just put it into the upper scope:
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return mention;
}
}
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!message.member.roles.cache.some(role => role.name === 'Staff')) return;
if (command === 'send'){
const user = getUserFromMention(args[0]);
let MessageDM = args[1];
client.users.cache.get(user).send(MessageDM);
}
// ...
});

VSC discord bot event locking

Hi I Coded A Bot But I Want To limit Bot's One Exact Event in One Channel This is Code
No Errors Just Need To Lock This Event in one channel
module.exports = async (client, message) => {
if (message.author.bot) return
if (message.channel.type === "dm") {
const guild = client.guilds.cache.get("736112465678565437")
const channel = guild.channels.cache.find(c => c.name === "modmail-messages")
const embed = new Discord.MessageEmbed()
.setAuthor(`${message.author.tag} | ${message.author.id}`, message.author.displayAvatarURL())
.addField("Message", message.content)
.setFooter("Sent")
.setTimestamp()
.setColor("PURPLE")
await message.author.send("Sending To Staff...")
await channel.send(embed)
}
if (message.channel.type !== "dm" && message.guild.channels.cache.find(c => c.name === "modmail-messages")) {
const user = message.mentions.members.first()
const args = message.content.slice(process.env.PREFIX.length).trim().split(/ +/g)
let response = args.slice(1).join(' ')
if (!response)
return message.reply("please provide a response to the user!")
if (!user)
return message.reply("please specify a user!")
await user.send(`**(β€’Hyper Staff)** ${message.member.displayName}: ${response}`)
}
if (message.content.indexOf(process.env.PREFIX) !== 0) return
const args = message.content.slice(process.env.PREFIX.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
const cmd = client.commands.get(command)
if (!cmd) return
cmd.run(client, message, args)
}```
What do you mean by "locking the event in one channel"? You want the bot to send a message in a specific channel?

Resources