Discord.js Multiple Commands - node.js

how can i make multiple commands with the discord.js module?
code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('message', msg => {
if (msg.content === '!hello') {
msg.reply('Hello!!');
}
});
client.login('token');
So, how do i make it so I can use multiple commands? Like !hi and !whatsup.
I hope someone can help.
Thanks

You can resume your if statement with else if()
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('message', msg => {
if (msg.content === '!hello') {
msg.reply('Hello!!');
} else if(msg.content === "!hi") {
msg.reply("Hi there!!");
}
});
client.login('token');

as a temporary solution, you can use "else if()" like so:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('message', message => {
if(message.content === '!command1') {
message.channel.send('working!');
} else if(message.content === '!command2') {
message.channel.send('working!');
} else if(message.content === '!command3') {
message.channel.send('working');
}
});
client.login('Your Token goes here');
a better solution is to set up a command handler. there are a lot on youtube, one is: https://youtu.be/AUOb9_aAk7U
hope this helped!

its really easy
const Discord = require("discord.js");
const client = new Discord.Client();
client.on('message', async message => {
if(message.content.toLowerCase().startsWith("hello")) {
message.channel.send("hola")
}
if(message.content.startsWith("hi there")) {
message.channel.send("hello")
}
})

You can use if() as a temporary solution but it would be better to setup a command handler.
const Discord = require("discord.js");
const client = new Discord.Client();
client.on('message', async message => {
if(message.content.toLowerCase().startsWith("command1")) {
message.channel.send("...")
}
if(message.content.toLowerCase().startsWith("command2")) {
message.channel.send("...)
}
})

Related

Discord JS SlashCommandBuilder

I'm Currently trying to implement SlashCommandBuilder into my Discord Bot.
The bot is currently using prefix '!' and I want to remake it to work with the SlashCommandBuilder, The following code is what i have used and tested, as it pretty much works fine or looks like it's working fine I'm still having an issue caused when someone uses '/hello' It will give him Error 'The application did not respond'.
I did double check the API, Token and such using a Prefix as a check.
The Code does actually add the command to the discord and it looks in the lists of commands.
I'm also splitting the commands inside 'commands' folder.
index.js :
const Discord = require('discord.js');
const fs = require('fs');
const { Client, Collection } = require('discord.js');
const { REST } = require('#discordjs/rest');
const config = require('./config.json');
const { Routes } = require('discord-api-types/v9');
const client = new Client();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
client.commands = new Collection();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Bot is ready!');
const rest = new REST({ version: '9' }).setToken(config.token);
rest.put(
Routes.applicationCommands(client.user.id),
{ body: client.commands },
)
.then(() => console.log('Successfully registered commands'))
.catch(error => console.error(error));
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
interaction.reply({ content: 'Error executing command', ephemeral: true });
}
});
client.login(config.token)
commands/hello.js
module.exports = {
name: 'hello',
description: 'Replys with Hi',
execute(interaction) {
interaction.reply({ content: 'Hi!' });
},
};
Please if anyone has information on why this was caused, i would love to listen.
Thank you for reading and appreciate any help or hints.

invalid or unexpection token, i tried to make my bot discord today, but there this error

const Discord = require(‘discord.js’);
const client = new Discord.Client();
var prefix = ‘!’
on(‘message’, message => {
if(message.author === client.user) return;
if(message.content.startsWith(prefix + ‘start’)) {
message.channel.sendMessage(‘Welcome to server);
}
});
client.login(‘TOKEN’);
I did these spaces only on this site because it doesn't allow me to post code.
Here I rewrote the code for you so it should work now:
const Discord = require('discord.js');
const client = new Discord.Client();
var prefix = '!'
client.on('message', message => {
if (message.author === client.user) return;
if (message.content.startsWith(prefix + 'start')) {
message.channel.send('Welcome to server');
}
});
client.login('TOKEN');

TypeError: message.guild.channels.forEach is not a functionl

i would like to make a Discord bot but i got stucked in here. Heres my code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.login('xxx');
client.on('message', message =>{
if(message.author.id == "xxx") {
if(message.content === "!bye") {
message.guild.channels.forEach(channel => channel.delete())
}
}
})
It says:
message.guild.channels.forEach is not a function
I would like to know why is it say to me. (Sorry for my bad english)
In discord 12, you need use new class channelManager
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.login('xxx');
client.on('message', message =>{
if(message.author.id == "xxx") {
if(message.content === "!bye") {
message.guild.channels.cache.forEach(channel => channel.delete())
}
}
})

How to check to see if a reaction is posted in discord.js

I have a discord.js bot that I would like to have a gateway entry on. It works that when they react to a reaction on a message, they get a role. How would I be able to accomplish that?
Hope you find this useful :)
flutter.on('guildMemberAdd', async member => {
let welcomeRole = member.guild.roles.find(role => {return role.id==="ROLE ID"});
await member.addRole(welcomeRole);
Promise.resolve(flutter.channels.get("CHANNEL ID")).then(async welcome => {
const msg = `Welcome to the community. :emojiName: We are **please** that you have joined us!`;
Promise.resolve(welcome.send(msg)).then(async message => {
flutter.on('messageReactionAdd', async (reaction, user) => {
if(user === message.author.bot) return;
if(reaction.emoji.name === "👍") {
let role = member.guild.roles.find(role => {return role.id==="ROLE TO REMOVE ID"});
await member.removeRole(role);
let roleTwo = member.guild.roles.find(role => {return role.id==="ROLE TO ADD ID"});
await member.addRole(roleTwo);
}
});
});
});
});
Wherever you see the word flutter just change it with your bots client name.
Example:
const Discord = require("discord.js");
const client = new Discord.Client();
Best of luck~

Discord.JS Events Handler Commands

Ok so I finally figured out how to code my fs events handler to use the events folder. now I just need to know the basic method for coding the evtns in their own files.
Here is what I have for now [starting with the ready.js file]. Is this correct and if not how do I code the event files properly?
module.exports = {
name: 'avatar',
description: 'Get the avatar URL of the tagged user(s), or your own avatar.',
execute(message) {
client.on("ready", () => {
client.user.setActivity(`on ${client.guilds.size} servers`);
console.log(`Ready to serve on ${client.guilds.size} servers, for ${client.users.size} users.`);
}
}};
This is my index.js file for reference:
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token } = require('./config.json');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
fs.readdir('./events/', (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
const eventFunction = require(`./events/${file}`);
if (eventFunction.disabled) return; //
const event = eventFunction.event || file.split('.')[0];
const emitter = (typeof eventFunction.emitter === 'string' ? client[eventFunction.emitter] : eventFunction.emitter) || client; /
const once = eventFunction.once;
try {
emitter[once ? 'once' : 'on'](event, (...args) => eventFunction.run(...args));
} catch (error) {
console.error(error.stack);
}
});
});
client.login(token);
The upper code block is not ready.js its avatar.js i think.

Resources