How to add a prefix discord.js - discord

require('dotenv').config();
const Discord = require('discord.js');
const bot = new Discord.Client();
const TOKEN = process.env.TOKEN;
const prefix = ".";
bot.login(TOKEN);
bot.on('ready', () => {
console.info(`Logged in as ${bot.user.tag}!`);
});
bot.on('message', msg => {
if (msg.content === 'ping') {
msg.channel.send('pong');
} else if (msg.content.startsWith('!kick')) {
if (msg.mentions.users.size) {
const taggedUser = msg.mentions.users.first();
msg.channel.send(`You wanted to kick: ${taggedUser.username}`);
} else {
msg.reply('Please tag a valid user!');
}
}
});
currently that is what im using im trying to make it so i have to type .pingto get the message Pong but i cant figure out how to get the prefix to use

You could use this code to get the command name:
bot.on('message', msg => {
const command = msg.content.slice(prefix.length).split(' ')[0]
if (command === 'ping') {
msg.channel.send('pong');
} else if (command === 'kick') {
if (msg.mentions.users.size) {
const taggedUser = msg.mentions.users.first();
msg.channel.send(`You wanted to kick: ${taggedUser.username}`);
} else {
msg.reply('Please tag a valid user!');
}
}
});
Note that this changes the kick command from !kick to .kick.
I recommend reading this section of the Discord.js guide for how to setup commands (and also user arguments if you need).

You can check for a concatenation of the prefix and the command name.
To check for .ping where prefix is .
if (msg.content === prefix + 'ping') {
// do something
}
To make it safer you can make it return early by checking if the message starts with the prefix.
if (!msg.content.startWith(prefix)) {
return;
}
This way when that check passes, you can slice away the prefix, and check the command name directly without having to worry about the prefix.
const commandName = msg.content.slice(prefix.length); // remove prefix character(s)
if (commandName === 'ping') {
// do something
}
All together it'd look like:
const prefix = '.'
bot.on('message', msg => {
// not start with prefix -> return early
if (!msg.content.startWith(prefix)) return;
// remove prefix to get command name
const commandName = msg.content.slice(prefix.length);
// check for command name directly
if (commandName === 'ping') {
// do something
} else if (commandName === 'kick') {
// do another thing
}
}

Related

Eval command doesn't work at all, but it doesn't error

I'm trying to make an eval command for my bot. It doesn't error, but it doesn't send a message to the console or the discord channel. Heres my eval code:
const clean = async (client, text) => {
if (text && text.constructor.name == "Promise")
text = await text;
if (typeof text !== "string")
text = require("util").inspect(text, { depth: 1 });
text = text
.replace(/`/g, "`" + String.fromCharCode(8203))
.replace(/#/g, "#" + String.fromCharCode(8203));
text = text.replaceAll(client.token, "[REDACTED]");
return text;
}
client.on("messageCreate", async (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(`${p}eval`)) {
if (message.author.id !== 821682594830614578) {
return;
}
try {
const evaled = eval(args.join(" "));
const cleaned = await clean(client, evaled);
message.channel.send(`\`\`\`js\n${cleaned}\n\`\`\``);
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${cleaned}\n\`\`\``);
}
}
});
Let me know if I have to give you more code.
It seems like you put a number as your ID... Discord.js IDs are in strings so you should put your ID into a string.
if (message.author.id !== "821682594830614578") {
return;
}
Probably your Discord ID is wrong. Tell me your discord username, I will add you as friend and will solve it in DMs.
This is my Discord Username Nishant1500#9735

How to make a say embed command in Discord.js

I'm new to coding and am making a Discord bot for a friend. They are requesting a say command that could act as a confession command where it would look like this. An embed with a set Title, set color, and completely anonymous but with an editable description that would fill in with what they want to confess. As i'm new to coding I don't know how to do this. If anyone can help that would be really appreciated! Thank you!
(Edit) I realise that i wasn't through enough about what the code was so im making an edit with my main.js code.
const client = new Discord.Client();
const prefix = 'wtf ';
const fs = require('fs');
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);
}
bot.once('ready', () => {
console.log('Tomoko is online!');
});
bot.on('message', async msg =>{
if(!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(msg, args, Discord);
} else if (command === 'creator'){
client.commands.get('creator').execute(msg, args, Discord);
} else if (command === 'help'){
client.commands.get('help').execute(msg, args, Discord);
} else if (command === 'kick'){
client.commands.get('kick').execute(msg, args, Discord);
} else if (command === 'ban'){
client.commands.get('ban').execute(msg, args, Discord);
} else if (command === 'mute'){
client.commands.get('mute').execute(msg, args, Discord);
} else if (command === 'unmute'){
client.commands.get('unmute').execute(msg, args, Discord);
} else if (command === 'warn'){
client.commands.get('warn').execute(msg, args)
} else if (command === 'deletewarns'){
client.commands.get('deletewarns').execute(msg, args);
} else if (command === 'warnings'){
client.commands.get('warnings').execute(msg, args);
} if (args[0].toLowerCase() === 'confess') {
const description = args.splice(1).join(" ");
const embed = new MessageEmbed().setTitle('✦┊‧๑ ꒰<a:ccc:862524564457390150><a:ooo:862524674185101322><a:nnn:862524667368833024><a:fff:862524592202973244><a:eee:862524583802568714><a:sss:862524709782683648><a:sss:862524709782683648>꒱ ‧๑┊✧').setColor('ffaaaa').setDescription(description);
await msg.delete().catch(e => console.log(e));
msg.channel.send(embed);
} else if (command === "unban"){
client.commands.get('unban').execute(msg, args, Discord);
;}
});
client.login('DAMN YOU WISH I WOULD SHOW YOU');
So if possible can anyone give me the advanced command handler say embed command. Thank you!!
That depends on how you handle your commands. But in general: generate a new embed, and set the description to the contents of your message.
Check here on how to create an embed.
A simple bot to do your job
// importing dependencies
const { MessageEmbed, Client } = require('discord.js');
const prefix = '!';
const bot = new Client(); // init discord client
bot.on('ready', () => console.log('yee im on'));
// listening for messages
bot.on('message', async msg => {
if (!msg.content.startsWith(prefix)) return // dont run if the prefix is not used
const args = msg.content.substring(prefix.length).split(" "); // creating array of the message contents
if (args[0].toLowerCase() === 'say') { // a simple command handler
const description = args.splice(1).join(" ");
const embed = new MessageEmbed().setDescription(description); // setTitle and stuff according to your preference
await msg.delete().catch(e => console.log(e)); // deleting the user message since it should be anonymous
msg.channel.send(embed);
}
});
bot.login('yourtokenhere');
Make sure to replace token and prefix with your token and prefix
How to run the command :
!say ooh this is a confession

Discord bot snipe command "Cannot read property 'get' of undefined"

I'm trying to design a snipe command for my discord bot, so I went and looked at a tutorial on how to do so, but I always stumble upon this problem, no matter what I try to do to fix it. Is there any reason why this would be happening? The error that pops up is: "Cannot read property 'get' of undefined". Any help would be appreciated, thank you!
const Discord = require("discord.js");
const prefix = '='
module.exports = {
name: "snipe",
description: "Recover a deleted message from someone.",
execute (bot, message, args) {
const msg = bot.snipes.get(message.channel.id)
if (!msg) return message.channel.send(`That is not a valid snipe...`);
const embed = new Discord.MessageEmbed()
.setAuthor(msg.author.tag, msg.author.displayAvatarURL({ dynamic: true, size: 256 }))
.setDescription(msg.content)
.setFooter(msg.date);
if (msg.image) embed.setImage(msg.image);
message.channel.send(embed);
}
};
Edit: bot.snipes is defined here
bot.snipes = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
bot.commands.set(command.name, command);
}
bot.on('ready', () => {
console.log('THE WORST BOT IN THE WORLD IS READY TO FAIL AGAIN!');
bot.user.setActivity('WUNNA FLOW', {type: "LISTENING"})
});
bot.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 (command === 'anmar') {
bot.commands.get('anmar').execute(message, args);
} else if (command === 'mar') {
bot.commands.get('anmar').execute(message, args);
} else if (command === 'fishe') {
bot.commands.get('fishe').execute(message, args);
} else if (command === 'ran') {
bot.commands.get('ran').execute(message, args);
} else if (command === 'help') {
bot.commands.get('help').execute(message, args);
} else if (command === 'snipe') {
bot.commands.get('snipe').execute(message, args);
}
});
bot.on("messageDelete", message => {
bot.snipes.set(message.channel.id, message);
});
bot.login (botconfig.token);
The issue is when you are calling execute:
bot.commands.get('snipe').execute(message, args);
Here, you pass the message instead of bot as the first argument when your execute function expects 3 arguments: bot, message, and args.
Use this instead:
bot.commands.get('snipe').execute(bot, message, args);
Alternatively, you can refactor your commands to get the bot from the message:
execute (message, args) {
const bot = message.client;
// rest of code...
}
bot.commands.get('snipe').execute(message, args);

Prefix is changing

So in my config.json file I had put my prefix as "!". I was testing the bot in my friends server and the prefix was clashing with other bots. I changed it to ";". But now both the prefixs are functioning "!" and";". I saved all my files and restarted node too, but the commands are still responding to "!". Am I missing something?
The structure of my file system is -
1. index.js
2. config.json
3. commands folder (command files)
index.js
const Discord = require('discord.js');
const fs = require('fs');
const { prefix, token } = require('./config.json');
const profanity = require('profanities')
//console.log(profanity);
const client = new Discord.Client();
const cooldowns = new Discord.Collection();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); //returns an array of all file anmes in a dir ['ping.js', beep.js, ....]; the filter is used to get only .js files.
const commandFiles_mod = fs.readdirSync('./commands/mod').filter(file => file.endsWith('.js')); //mod folder
const commandFiles_info = fs.readdirSync('./commands/info').filter(file => file.endsWith('.js')); //info folder
const commandFiles_extras = fs.readdirSync('./commands/extras').filter(file => file.endsWith('.js')); //
//file system
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// set a new item in the Collection
// with the key as the command name and the value as the exported module
client.commands.set(command.name, command); //set takes the file name and the path to the file. //command is the path to file and command.name is the name of the file
}
for (const file of commandFiles_info) {
const command1 = require(`./commands/info/${file}`);
client.commands.set(command1.name, command1);
}
for (const file of commandFiles_mod) {
const command2 = require(`./commands/mod/${file}`);
client.commands.set(command2.name, command2);
}
for (const file of commandFiles_extras) {
const command3 = require(`./commands/extras/${file}`);
client.commands.set(command3.name, command3);
}
client.once('ready', () => {
client.user.setActivity(`${prefix}help`)
console.log(`Hello! ${client.user.username}-bot is now online!`)
});
client.on('message', message => {
//command handling
if (message.content === 'galaxy-prefix') {
const prefix_embed = new Discord.MessageEmbed()
.setTitle('Prefix')
.setDescription(`Use this ahead of comamnds for usage: **${prefix}**`)
.setColor('RANDOM')
.setTimestamp()
message.channel.send(prefix_embed);
}
if (message.content.startsWith(prefix) || !message.author.bot || !message.channel.type === 'dm') { //edit here
const args = message.content.slice(prefix.length).split(/ +/); //caveats
//console.log(args);
const messageArray = message.content.split(/ +/);
//console.log(messageArray);
const cmd = args[1];
//console.log(cmd);
const commandName = args.shift().toLowerCase();
//console.log(commandName);
/*if (!message.content.startsWith(prefix) && !message.author.bot) {
const messageArray = message.content.split(" ");
console.log(messageArray);
}*/
/*for (i=0; i < profanity.length; i++) {
if (messageArray.includes(profanity[i])) {
message.delete();
break;
}
}*/
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)); //aliases
if (!command) return;
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!'); //cannot dm this command
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``; //usage check, in file as usage: '<...>'
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) { //cooldown
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
//console.log(now);
const timestamps = cooldowns.get(command.name); // gets the collection for the triggered command
const cooldownAmount = (command.cooldown || 3) * 1000; //3 is default cooldown time, if cooldown isnt set in command files.
if (timestamps.has(message.author.id)) {
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(client, message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
}
});
client.on('shardError', error => {
console.error('A websocket connection encountered an error:', error);
});
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection:', error);
});
client.login(token);
config.json
{
"token": " ................. ",
"prefix": ";"
}
Your bot will respond to anything actually...
if (message.content.startsWith(prefix) || !message.author.bot || !message.channel.type === 'dm')
This means your bot will run if the message starts with the prefix OR the sender is not a bot OR the channel type is DM. You should try using ? - .... They will probs work too.
To use an and you use && instead of ||

Discord.js command handler problems

I've been trying to fix a command handler for 3 hours now, but anytime I try to add a custom command nothing happens. It loads the command, but when the command is run it does nothing. Here's some code:
index.js:
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
console.log(`[LOG] Loaded command ${file}`);
client.commands.set(command.name, command);
}
commands/kick.js:
const fs = require('fs');
var moment = require('moment');
var logger = fs.createWriteStream(`./logs/${moment().format('MM-DD-YYYY')}.log`, {
flags: 'a'
});
module.exports = {
name: "kick",
category: "moderation",
description: "Kicks the mentioned user.",
usage: "<imputs>",
run: (client, message, args) => {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
if (message.mentions.users.size < 1) return message.reply('You must mention someone to kick them.').then(msg => { msg.delete(10000) }).catch(console.error);
if (user.id === message.author.id) return message.reply("You cannot kick yourself.").then(msg => { msg.delete(10000) });
if (user.id === client.user.id) return message.reply("You cannot kick me.").then(msg => { msg.delete(10000) });
if (!message.member.hasPermission("KICK_MEMBERS")) return message.reply("You don't have the **Kick Members** permission!").then(msg => { msg.delete(10000) });
if (reason.length < 1) reason = 'No reason supplied';
if (!message.guild.member(user).kickable) return message.reply('I could not kick that member').then(msg => { msg.delete(10000) });
message.delete();
message.guild.member(user).kick();
const embed = new Discord.RichEmbed()
.setColor(0x0000FF)
.setTimestamp()
.addField('Action:', 'Kick')
.addField('User:', `${user.username}#${user.discriminator} (${user.id})`)
.addField('Moderator:', `${message.author.username}#${message.author.discriminator}`)
.addField('Reason', reason)
.setFooter(`© NetSync by Towncraft Developers`);
let logchannel = message.guild.channels.find('name', 'logs');
if (!logchannel){
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}.`).then(msg => { msg.delete(10000) });
logger.log(`[LOG] [KICK] ${user.username}#${user.discriminator} (${user.id}) was kicked by ${message.author.username}#${message.author.discriminator}.`);
}else{
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}. I\'ve also logged the kick in <#${logchannel.id}>.`).then(msg => { msg.delete(10000) });
client.channels.get(logchannel.id).send({embed});
}
if(user.bot) return;
return message.mentions.users.first().send({embed}).catch(e =>{
if(e) return
});
}
}
Like I said, been trying to do this for 3 hours now, and I'm stumped. If someone could tell me what I did wrong that'd be awesome, thanks.
You need execute command in you main.js file on bot.on('message' block.
Like this:
client.on('message', message => {
if (message.channel.type === "dm") return;
let prefix = '!'
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if (!message.content.startsWith(prefix)) return;
let commandfile = client.commands.get(cmd.slice(prefix.length));
if (commandfile) commandfile.run(client, message, args, botconfig);
})

Resources