how do I read args in discord.js? I am trying to create a support bot and I want to have an !help {topic} command. how do I do that?
my current code is very basic
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = ("!")
const token = ("removed")
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
}
if (msg.content === 'help') {
msg.reply('type -new to create a support ticket');
}
});
client.login(token);
You can make use of a prefix and arguments like so...
const prefix = '!'; // just an example, change to whatever you want
client.on('message', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.trim().split(/ +/g);
const cmd = args[0].slice(prefix.length).toLowerCase(); // case INsensitive, without prefix
if (cmd === 'ping') message.reply('pong');
if (cmd === 'help') {
if (!args[1]) return message.reply('Please specify a topic.');
if (args[2]) return message.reply('Too many arguments.');
// command code
}
});
you can use Switch statement instead of
if (command == 'help') {} else if (command == 'ping') {}
client.on ('message', async message => {
var prefix = "!";
var command = message.content.slice (prefix.length).split (" ")[0],
topic = message.content.split (" ")[1];
switch (command) {
case "help":
if (!topic) return message.channel.send ('no topic bro');
break;
case "ping":
message.channel.send ('pong!');
break;
}
});
let args = msg.content.split(' ');
let command = args.shift().toLowerCase();
this is the simplified answer from #slothiful.
usage
if(command == 'example'){
if(args[0] == '1'){
console.log('1');
} else {
console.log('2');
You can create a simple command/arguments thing (I don't know how to word it correctly)
client.on("message", message => {
let msgArray = message.content.split(" "); // Splits the message content with space as a delimiter
let prefix = "your prefix here";
let command = msgArray[0].replace(prefix, ""); // Gets the first element of msgArray and removes the prefix
let args = msgArray.slice(1); // Remove the first element of msgArray/command and this basically returns the arguments
// Now here is where you can create your commands
if(command === "help") {
if(!args[0]) return message.channel.send("Please specify a topic.");
if(args[1]) return message.channel.send("Too many arguments.");
// do your other help command stuff...
}
});
You can do
const args =
message.content.slice(prefix.length).trim().split(' ');
const cmd = args.shift().toLocaleLowerCase();
Word of advice, use a command handler and slash commands - this will solve both the need for a help command and reading arguments. Also helps with readability.
Anyways...
message.content.split(' '): This will split your string into an array of sub-strings, then return a new array.
.shift(): This will remove the first index in the array.
Combining this will get you your arguments: const args = message.content.split(' ').shift()
Related
I want to do so that when I use !pm (user) (some message), my bot will send a private message to the user, although I have no idea how to select everything after the (user) and assign it to a variable, to send it to the user.
My current code looks like this:
module.exports = {
name: 'pm',
description: 'Sends a personal message!',
execute(message, args, client) {
const pmMessage = args[1];
client.users.cache.get('464839066781745167').send(pmMessage);
}
}
Since you know the array index of the pmMessage, with the help of that index, you can use the slice method which returns the array from specified stating to end index.
Eg:
let pmMessage = args.slice(2); //returns array.
Note: If the end index is not specified, then it considers till the last index of the array.
Now, using the join method, you can join all the indexes with whatever specified character. Eg:
let MessageContent = pmMessage.join(' '); //joined by space.
let args = ["UserID","This","represents","the","message","content","to","be","sent"];
console.log(args.slice(1));
console.log(args.slice(1).join(' '));
Try this, I think this should work:
let pm_args = args.slice(1).join(' ')
if(args[0]){
let user = getUserFromMention(args[0])
if(!user){
return message.reply('please mention a user.');
}
return client.users.cache.get(user.id).send(pm_args);
}
return message.reply('please mention a user.');
(This is what I used for mention thingie:)
function getUserFromMention(mention){
if(!mention) return;
if(mention.startsWith('<#') && mention.endsWith('>')){
mention = mention.slice(2, -1);
if(mention.startsWith('!')){
mention = mention.slice(1);
}
return bot.users.cache.get(mention);
}
};
client.on("message", message => {
if(!message.content.startsWith(config.prefix)) return;
const withoutPrefix = message.content.slice(config.prefix.length);
const split = withoutPrefix.split(/ +/);
const command = split[0];
const args = split.slice(1);
// Code...
});
i was trying to make an afk command with discord.js
i keep getting command.execute is not a function, and i have no idea how to fix it. please help!
client.on("message", async message => {
if (message.author.client) return;
if (message.channel.type === "dm") return;
let prefix = config.prefix;
let messageArray = message.content.split(" ");
let command = messageArray[0].toLowerCase();
let args = messageArray.slice(1);
if (message.content.includes(message.mentions.members.first())) {
let mentioned = client.afk.get(message.mentions.users.first().id);
if (mentioned) message.channel.send(`**${mentioned.usertag}** is currently afk. Reason: ${mentioned.reason}`);
}
let afkcheck = client.afk.get(message.author.id);
if (afkcheck) return [client.afk.delete(message.author.id), message.reply(`you have been removed from the afk list!`).then(msg => msg.delete(5000))];
if (!command.startsWith(prefix)) return;
let cmd = client.commands.get(command.slice(prefix.length));
if (cmd) cmd.run(client, message, args);
});```
In the scope of your function, command is the variable that is equal to messageArray[0].toLowerCase();, which is a string and does not have a execute method.
I guess you are trying to call the execute method of an object you called command, try to change the naming of your variables to avoid overriding the one you need.
I am attempting to make a command like dank memer has, when someone says F or f, the bot replies with F. My problem is that it will not work without the prefix, but I would like to be able to do it without the prefix.
Here is my code. I use a command handler.
//THIS IS THE INDEX.JS FILE
const Discord = require('discord.js');
const { default_prefix, token_bot } = require('./config.json');
const client = new Discord.Client();
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);
}
client.once('ready', () => {
console.log('Ready Player One!');
});
client.on('message', message => {
if (!message.content.startsWith(default_prefix) || message.author.bot) return;
const args = message.content.slice(default_prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'f'){
client.commands.get('f').execute(message, args);
}
And this one is the f.js command that it calls on.
module.exports = {
name: 'f',
description: "This is an f command",
execute(message, args){
message.channel.send('F');
},
};
This is not all of my index.js file, it is too long.
The solution to this is very simple. All commands have prefixes, so I would not consider what you are trying to create as a command, I would say it is technically more of an auto-response. Therefore, you should not be using the code of your args or command variables to check if "F" has been sent, you should instead directly check the message's content.
client.on('message', message => {
if (!message.content.startsWith(default_prefix) || message.author.bot) return;
const args = message.content.slice(default_prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message.content.toLowerCase() == 'f'){
client.commands.get('f').execute(message, args);
}
});
I would advise looking into the args and command variables and learning how their values are being retrieved. Your code, as it is, seems to heavily rely on a simple template, but you cannot entirely depend on this template if you want to fully customize how your bot/commands will look and function.
client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
if(!member) return message.channel.send('Cannot find this member');
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
}
This is the code of kick and ban.^^
https://sourceb.in/2e6ba31dc3 - this is my discord bot code where I want to put the ban and kick command code
You want to put the command inside of the client.on("message", (message) block.
I'll use it in your code as an example:
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
}
// Kick start
if (command === 'kick') {
// Only check if the command caller has permission,
// AFTER the command is called, not before.
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
// Define which member needs to get kicked by grabbing the first mentioned guild member
let member = message.mentions.members.first();
// If the tagged member is not found in your guild,
// throw this message
if(!member) return message.channel.send('Cannot find this member');
// Proceed to kick the member
member.kick().then((member) => {
message.channel.send("```" + member.displayName + " has been kicked ```");
});
}
});
I hope this answers your question. Check the discordjs docs here if you haven't checked them already. They feature a nice tutorial on setting up your bot.
I've never had a problem with the say command until I start using modules and cleaned up my code but since I have few my commands have bugged. I'm trying to figure out why it is saying the command.
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("message", async message => {
if (!message.content.startsWith(PREFIX)) return;
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case "say":
bot.commands.get("say").execute(message, args);
break;
const Discord = require("discord.js");
module.exports = {
name: "say",
description: "Show's avatar",
async execute(message, args){
const sayMessage = args.join(" ");
message.delete().catch(O_o => {});
message.channel.send(`${sayMessage} - ${message.author}`);
}
}
Thanks in advance!
The code is doing exactly what you programmed it to, be it not intended.
let args = message.content.substring(PREFIX.length).split(" "); // args = ['say', 'Hello', 'World']
bot.commands.get("say").execute(message, args); // Passing in the entire args array
const sayMessage = args.join(" "); // sayMessage = 'say Hello World'
One solution of many:
let args = message.content.substring(PREFIX.length).split(" ");
const command = args.splice(0, 1); // args now only contains the arguments
switch (command) {
...
}
Here you go this is using the anidiots guidebot boiler plate i highly recommend using it to help you better understand incorporating a command handler into your discord bot.
your going to want to download the repo from here https://github.com/AnIdiotsGuide/guidebot/
extract it
run npm install
in the commands folder add say.js using the code below this is how to properly execute what your trying todo
by default the prefix is ~ to change it in discord chat run ~conf edit prefix Example: ~conf edit prefix !
run !say hello world
exports.run = async (client, message, args) => {
const sayMessage = args.join(" ");
message.delete();
message.channel.send(sayMessage + ' - ' + message.author)
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: "User"
};
exports.help = {
name: "say",
category: "Miscelaneous",
description: "say command",
usage: "say"
};```