How to make this bot listen to argument after prefix and answer? - discord

so i'm trying this 8ball bot, and everything is working fine, but i can't get how can i leave in the condition that only when the bot get "!verda arg1 arg2" it answers one of the replies in the array.
meanwhile my condition is if the user type the prefix "!verda" only, it replies , i want to include the argument too in the condition
const Discord = require("discord.js");
const client = new Discord.Client();
const cfg = require("./config.json");
const prefix = cfg.prefix;
client.on("message", msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase;
if (msg.content === prefix){
let replies = [
"Yes.",
"No.",
"I don't know.",
"Maybe."
];
let result = Math.floor((Math.random() * replies.length));
msg.channel.send(replies[result]);
}
else if (msg.content === "!help"){
msg.channel.send("I have only 1 command [!verda]");
}
})
client.login(cfg.token);

const command = args.shift().toLowerCase;
toLowerCase is a function and therefore should be
const command = args.shift().toLowerCase();
By doing msg.content === prefix, you are checking if the whole content of the message is equal to that of cfg.prefix
if(msg.content.startsWith(`${prefix}8ball`) {
}

The answer was simple as i figured it out, i simply had to join the spaces
if (msg.content === `${prefix} ${args.join(" ")}`)

Related

Same value in replit database

i am having a problem that whenever i type the +warn <#user> then everything goes well , lets take an example that i want to warn any user so i'll type +warn <#user> and then it will show a embed by saying that your are banned by this this and you are banned from this this and also shows that how many warns the user now have and lets also take that he have 1 warn till now, and now warn another user by typing +warn <#user> and then it will show the thing blah blah blah but.. when the bot shows that how many warns the second user have then it will show the same value of warn as the first user like this warns(of the first user): 1 but when with the second user it shows warns(of the second user): 2 and even the second user have 0 warns but it will show 2 and when you retry to warn the first user it will show 3 warns idk why
code:-
const config = require("../config.json");
const Database = require("#replit/database")
const db = new Database()
const { MessageEmbed, username } = require('discord.js')
exports.run = async (client, message, args, Discord) => {
let reason = args.slice(1).join(" ")
if (!reason) reason = "No reason provided"
const user = message.author.id
let warns = await db.get(`warns_${message.author.id}`)
let member = message.mentions.members.first()
if (!member) return message.reply("Please mention a user to warn")
const wembed = new MessageEmbed()
.setTitle(`You have been warned`)
.setDescription(`You have been warned by ${message.author.username}\nFrom the server of: ${message.guild.name}\nWith the reason: ${reason}\nNow you have ${warns} warns`)
if (!member === member.user.bot) {
member.send({embeds: [wembed]})
} else {
message.channel.send(`unable to send dm to ${member}`)
}
const embed = new MessageEmbed()
.setTitle(`Warn to ${member}`)
.setDescription(`${member} has been warned successfully warned\n\n${member} have now ${warns}\nReason: ${reason}`)
message.channel.send({embeds: [embed]})
await db.set(`warns_${message.author.id}`, warns + 1)
member.send({embeds: [wembed]})
}
exports.conf = {
aliases: ['warning']
};
exports.help = {
name: "warn"
};```

Discord.js how to use bot mention and a set prefix as prefixes

I want to make it so that if I do [prefix] [command] it will give the same effect as [mention bot] [command] but the way I create commands and args makes that difficult:
The prefix is stored as var prefix = '!3';
And this is how I create commands:
bot.on('message', msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot)
return;
//the first message after '!13 '
//!
let args = msg.content.toLowerCase().substring(prefix.length).split(" ");
//^
//any capitalisation is allowed (ping,Ping,pIng etc.)
switch(args[1]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}//switch (command) ends here
};//event listener ends here
You can have a list of predefined prefixes and loop over that to determine if the msg has a prefix from that list.
let prefixList = ['!31 ', '!asdf ', `<#${bot.user.id}> `, `<#!${bot.user.id}> `]
function hasPrefix(str) {
for(let pre of prefixList)
if(str.startsWith(pre))
return true;
return false;
}
<#${bot.user.id}> , <#!${bot.user.id}> will set up bot mention as a prefix.
Here's the shorter version of secretlyrice's answer:
const startsWithPrefix = (command) =>
['!prefix1 ', '!prefix2', <#botId>, <#!botId>].some(p => command.startsWith(p))
Nice code, but change it 1 to 0
switch(args[0]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}
I assume you are running on an older version of Discord.js cause if you are using v13 message is depricated and should be messageCreate but this is what I used when I wasn't using slash commands.
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const prefix = '!'
bot.on('message', async msg => {
const prefixRegex = new RegExp(`^(<#!?${bot.user.id}>|${escapeRegex(prefix)})\\s*`)
if (!prefixRegex.test(message.content)) return
// checks for bot mention or prefix
const [, matchedPrefix] = message.content.match(prefixRegex)
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/)
// removes prefix or bot mention
const command = args.shift().toLowerCase()
// gets command from next arg
if (command === 'ping') {
msg.channel.send('Pong!')
}
})

client.commands.has() not working with normal input

To get the files with commands (such as ping.js)
module.exports = {
name: 'ping',
description: 'Play some ping pong.',
execute(message, args) {
const bot = require('../bot.js');
message.channel.send('pong!');
bot.log(message, '$ping', message.guild.name);
},
};
I use this in bot.js
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command_file = require(`./commands/${file}`);
client.commands.set(command_file.name, command_file);
}
I'm trying to set the variable for the command with this:
let command = '';
if(message.content.includes(' ')){
command = message.content.substr(1, message.content.indexOf(' ')).toLowerCase();
} else {
command = message.content.substr(1).toLowerCase();
}
which returns the name of the command as a string, like 'info' or 'ping'.
But, when I put that variable into client.commands.has() it doesnt find the command and returns back with this:
if(!client.commands.has(command)) return;
I cant find any answers to this online so I figured I'd ask, sorry if this doesnt fit
Try this instead:
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 to make a counter of people who have been invited to the server?

Its my code
var args = message.content.slice(prefix.length).trim().split(/ +/g);
var command = args.shift().toLowerCase()
if(command == "myinv"){
var invs = (await message.member.guild.fetchInvites().then(invites => invites.findAll("memberCount"))).values()
return message.channel.send(elo)
}
When i use command i got error like this:
(node:22680) DeprecationWarning: Collection#findAll: use Collection#filter instead
(node:22680) UnhandledPromiseRejectionWarning: Error: Value must be specified.
Can anyone help me?
Discord collection has no method .findAll, the one way to get count of invites uses, its
get serverinvites, then filter this collection, because discord not guaranteed property of invite.uses, then you can reduce it for get a summ.
var args = message.content.slice(prefix.length).trim().split(/ +/g);
var command = args.shift().toLowerCase()
if(command == "myinv"){
let invites = message.member.guild.fetchInvites().then(invites => {
let countInvites = invites.filter(invite => (invite.hasOwnProperty('uses'))).reduce((a, b) => {
a.uses + b.uses
}, 0)
message.channel.send(`Total server invite uses: **${countInvites}**`)
})
}

How do I make a command call a different command along with itself?

I don't know how to do this and I have been looking for answer but am unable to find it.
if message.content.startswith('^trivia autostart'):
await client.send_message(message.channel, "Game is starting!\n" +
str(player1) + "\n" + str(player2) + "\n" + str(player3) + "\n" +
str(player4) + "\n" + str(player5) + "\n" + str(player6) )
--
I have this code and i'm trying to make it so it when that code gets run that it calls my ^trivia play command without typing it in chat.
Is this possible?
The solution to that would be defining functions for each command you need to be called globally by your bot. Take the following example:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('error' => console.log);
bot.on('message', message => {
let prefix = '!';
let sender = message.author;
let msg = message.content;
let cont = msg.split(' ');
let args = cont.slice(1);
let cmd = msg.startsWith(prefix) ? cont[0].slice(prefix.length).toUpperCase() : undefined;
// Ping function
// can be: function pingCommand () {...}
let pingCommand = () => {
message.channel.send(`Pong!\nTime: ${bot.ping} ms`);
}
// Main command
if (cmd === 'PING') {
pingCommand();
}
// Calling command in another command
if (cmd === 'TEST') {
message.channel.send('Running a ping test on the bot');
pingCommand();
}
});
bot.login(token);
Hope you understand how it would work

Resources