Trying to execute a random command without having to restart bot - javascript

I was trying to follow this link: Random Message Reply Discord.js 2020
But am stuck when trying to get it implemented. Basically, using the discord.js library I have one channel that I want to allow one word and one word only. When someone posts anything in said channel that is NOT that word, I want the bot to delete it and send a randomly picked reply from an array. I have gotten it to randomly select an indexed item, but it does not truly stay random. The only time the reply changes, is if the bot is restarted. I want it to execute after every time the event takes place, but every time I try, I get ReferenceError: execute is not defined.
Today is my first day ever working with Javascript, so any way of simplifying this would be GREATLY appreciated. I have repeatedly tested it, and it works great until I tried working with the execute function. I am using Visual Code Studio for the coding, and node.js for running the file.
I have not imported any other files besides discord.js, dotenv, and nodemon. I don't know what execute is supposed to do. I was just blindly following the link.
Here is my code:
const client = new Client();
const bredfreply = [
'Excuse me person. I see you are participating in the "bredf" channel in the INCREDIBLE Realm of Eden. Unfortunately, this channel is only limited to bredf. I cannot believe you would speak any other word. You should be ashamed!',
'Did you do what I think you just did? EXCUSE ME, but bredf is only for bredf. You MUST say bredf because it is bredf and everyone knows bredf is only bredf and not whatever you thought it was. bredf. Only bredf.',
'You person, are in trouble. For the fact that you are rebelling against the bredf, you have lost one cookie. I do not care if you already did not have cookie because now you have less than no cookies. You actually OWE cookies so pay up.',
'Whatever you just did? That was not bredf.',
'bredf bredf bredf bredf bredf bredf bredf bredf bredf bredf bredf bredf',
'PLEASE only post bredf in the channel. You are scaring the other bredfs.',
'Did you hear about bredf? It is this really cool thing that all the cool kids post in bredf. Oh, you must not be bredf because I do not see you in there. You should be bredf.',
'*sniffles* I want bredf. Can you help me? Put it in the channel then because I do not think you can.',
'I only like people that say bredf. Since you apparently are not, that must mean I do not like you. Hmph'
];
client.on('ready', () => {
console.log(`${client.user.username} is ready to start the day!`);
});
client.on('message', (message) => {
if(message.channel.id == '840422367829164052' && message.content != 'bredf'
&& message.author.id != '854877244157853716')
execute(message,)
const randombredfreply = bredfreply[Math.floor(Math.random(1)) * bredfreply.length];
message.author.send(randombredfreply);
message.delete()
}
)```

Did you import function execute from any other file? Or what does execute function do?

I was able to solve this by playing around with it. I acheived my goal by moving my
By moving my
var randombredfreply = bredfreply[Math.floor(Math.random() * bredfreply.length]);
Into my if(... command) it will re-calculate this whenever the if parameters are met.
Here is the final code:
if(message.channel.id == '840422367829164052' && message.content != 'bredf'
&& message.author.id != '854877244157853716')
{
var randombredfreply = bredfreply[Math.floor(Math.random() * bredfreply.length)];
message.author.send(randombredfreply);
message.delete()
}
})

Related

discord.js mention command not picking up users but picks up itself

I've started my bot after a while and for some reason the mention command is not working. Code and response to the command is below:
client.on('message', message => {
if (message.content.startsWith('L!bite')) {
let targetMember = message.mentions.members.first();
if (!targetMember) return message.reply('you need to tag a user in order to bite them!!');
// message goes below!
message.channel.send(`${targetMember.user}, You just got a bitten!`);
message.channel.send({files:["./nom/"]})
//let embed = new Discord.RichEmbed()
//embed.setImage(`https://media1.tenor.com/images/4f5666861516073c1c8015b2af7e2d15/tenor.gif?itemid=14720869`)
message.channel.send(embed);
}
});
Response on Discord: (it does picks itself up as a user but not anyone else)
Β·._.β€’πŸŽ€ πΉπ΅πΌπΏπŸ’—πΏπΌπ’’πΌπ‘…πΏ πŸŽ€β€’._.Β·Today at 1:18 PM
L!bite #Β·._.β€’πŸŽ€ πΉπ΅πΌπΏπŸ’—πΏπΌπ’’πΌπ‘…πΏ πŸŽ€β€’._.Β·
._.Β·πŸŽ€πΉπ΅πΌπΏβ™‘π“π’Ύπ”Ÿπ“Έπ“£πŸŽ€Β·._.BOT Today at 1:18 PM
#Β·._.β€’πŸŽ€ πΉπ΅πΌπΏπŸ’—πΏπΌπ’’πΌπ‘…πΏ πŸŽ€β€’._.Β·, you need to tag a user in order to bite them!!
I'm just confused on why it's saying that I'm or other people are not users, but it picks up itself? E.g.:
Β·._.β€’πŸŽ€ πΉπ΅πΌπΏπŸ’—πΏπΌπ’’πΌπ‘…πΏ πŸŽ€β€’._.Β·Today at 1:18 PM
L!bite #._.Β·πŸŽ€πΉπ΅πΌπΏβ™‘π“π’Ύπ”Ÿπ“Έπ“£πŸŽ€Β·._.
._.Β·πŸŽ€πΉπ΅πΌπΏβ™‘π“π’Ύπ”Ÿπ“Έπ“£πŸŽ€Β·._.BOT Today at 1:18 PM
#._.Β·πŸŽ€πΉπ΅πΌπΏβ™‘π“π’Ύπ”Ÿπ“Έπ“£πŸŽ€Β·._., You just got a bitten!
GIF HERE
Try converting the message.mentions.members to array and then filter your bot! -
const mentions = message.mentions.members.array() // will return members array of GuildMember class
const firstMention = mentions.filter(mention=> !mention.user.id === "BOT_ID")[0]
Alternatively, there's already a parameter you can implement in your code where it can automatically check if the message came from a bot. Although, this process may not work if you want to have other bots automatically tag it, but I think that's unlikely.
if (message.author.bot) return; FYI, not sure of which version of discord.js you're using, but the embed naming convention has changed. Instead of RichEmbed(), you should use MessageEmbed().
So the place you would implement this is right after your first if conditional block, like this:
if (message.content.startsWith('L!bite')) {
//the thing that checks if the user who posted was the bot
if (message.author.bot) return;
Hopefully this helps!

I want to make a Discord.js reaction collector, counter, timer and role dm

So I made a suggestion command which sends an embed with the suggestor name and the suggestion to a specific channel. It then reacts with πŸ‘ and πŸ‘Ž.
How can I make a collector, that counts the reactions and after e.g 1 week it stops it and DMs everyone in a specific role (e.g Staff) with the results and edits the embed in the channel saying Suggestion accepted/denied.
Also, how can I make a collector that runs a command with permissions (roles e.g
Staff)
I know I am asking for a lot, but I looked at discord.js.org's documentation and I couldn't understand it.
Thanks for taking off your time to help me!
Here is my code so far:
if (command === 'suggest') {
if (!args.length) {
const suggestHelp = new Discord.MessageEmbed()
.setTitle('Suggestions')
.setDescription('Help')
.addField('Usage', 'The easiest way for community to rate suggestions!')
.addField(
'Commands',
'`/suggest` Displays info about the suggestions \n `/suggest <suggestion>` Make a suggestion, which can be rated by the community'
)
.setFooter('Powered by Monebot')
.setColor(0x2e86c1);
message.channel.send(suggestHelp);
return;
} else if (args.length) {
let suggestor = message.author.username;
let suggestionText = args.slice(0).join(' ');
const suggestEmbed = new Discord.MessageEmbed()
.setDescription(suggestionText)
.setColor(0xf5b041)
.setAuthor(`Suggestion from ${suggestor}`);
//.setThumbnail('https://i.imgur.com/wSTFkRM.png')
client.channels.cache
.get('ID')
.send(suggestEmbed)
.then((messageReaction) => {
//Setup 1 Channel ID for suggestions
messageReaction.react('πŸ‘');
messageReaction.react('πŸ‘Ž');
});
}
}
You are not specific with what you want us to help you with.
You're asking us too much to do in one time and you litterally gave us you code and asked us to change it ^^'
But i get what you are trying to do so i suggest you to search in a discord.js guide wich is extremelt helpful in this case
If i helped you can approuve this suggestion, if not please edit yours so that we can help you.
Markdown would be helful
And i have the same question as ortogonal
What are you having issues on? I would suggest you try to make everything you listed before coming to here, do you have an error?

Words filter stopped working - Discord.JS 12

Hello!
So I'm currently updating my bot to version 12.3.1 of DiscordJS. Unfortunately, I got stuck on a problem that I can't really find a workaround. So, my bot has a module to filter out all of the bad words, like profanity, racial slurs, etc.
It's currently working just fine on 11.4, but cannot get it to work on 12.3.1
For some reason, the bot just does not react at all to given message.
I had two "filters" one for words, one for invites. Both of them stopped working.
bot.on('message', async message => {
// Events Listeners
if (message.author.bot) return;
if (message.channel.type === 'dm') return;
let messageArray = message.content.split(' ');
let command = messageArray[0];
let args = messageArray.slice(1);
if (!command.startsWith(prefix)) return;
let cmd = bot.commands.get(command.slice(prefix.length)) || bot.aliases.get(command.slice(prefix.length));
if (cmd) cmd.run(bot, message, args);
// First filter
var array = ['testing', 'yes', 'no'];
if (array.includes(message.content.toLocaleLowerCase())) {
message.channel.send('test')
}
// Second filter
if (message.content.includes('discord.gg/') {
message.delete()
}
}
That's the current one I found from another StackOverflow post, made 2 months ago.
Discord.js V12 Rude words filter not working
I'd really love to get some help if possible, as I can't find any reason why this feature has stopped working.
Thank you! :)
Your filters are after your command handling logic.
You have the line:
if (!command.startsWith(prefix)) return;
early in your code, and this causes message handling to terminate immediately on any message which is not a command. Due to this, the code will never reach your filters unless the message starts with your bot's prefix, at which point the message content cannot possibly be equal to any of the words and is extremely unlikely to contain discord.gg/.
Simply move your filters to the beginning of your message handler. Or alternatively separate the command handling and filter handling into separate functions, so that the return statement above only exits the command handling and the filter handling will still run.

Overlapping commands?

I'm trying to make a fun little discord chat bot with JavaScript and node.js and I'd like to put in a specific command without it affecting another one I already have set up.
She works wonderfully on all the servers I have her on, and I've got it set up so that when someone in the server says anything with "rei are", she responds with a constant from areResponses.
//const!!!
const areResponses = ["HELL yeah!", "Yep!", "I'm pretty sure that's true!", "I\'m not gonna put all the responses here because then it'd be too long..."];
//theres some other bot stuff (console log, now playing) under here but it isn't relevant until...
//the basics...
if (message.content.toLowerCase().includes("rei are")) {
var response = areResponses [Math.floor(Math.random()*areResponses.length)];
message.channel.send(response).then().catch(console.error);
}
What I want to have happen is, preferably, this command to function without setting off the "rei are" command I coded in.
if(message.content.toLowerCase().includes("rei are you happy")) {
message.channel.send("Yes, absolutely.");
}
As of right now, whenever I try to input the above command, it just triggers the "rei are" command AND the "rei are you happy" command with two messages...
else/if chains work beautifully for this actually!!!
if(message.content.toLowerCase().includes("rei do you like girls")) {
message.channel.send("Yes, absolutely. Girls are just... yeah...");
}
else if (message.content.toLowerCase().includes("rei are")) {
var response = areResponses [Math.floor(Math.random()*areResponses.length)];
message.channel.send(response).then().catch(console.error);
}
All you need to do is put the command that would overlap with the larger commands at the very bottom of the else if chain, and then you're good!!

Trouble with Discord.js Ping Numbers

So I recently decided to make a Discord bot, and had been going through some tutorials with no problem. However, when I tried to make a ping command (you know, the kind that says "Your ping is 137 ms"), I got numbers that didn't make sense.
Numbers such as -627 ms, 32 ms, 1001 ms, -10 ms, 238 ms. Basically anything and everything between -1000 and 1000.
Now correct me if I'm wrong, but I'm pretty sure that getting negative numbers means I'm sending the response before I even ask for it, and I'm almost certain I didn't write a precognitive bot :P
I spent some time online looking for a reason why I was getting strange ping numbers, but I came up with zilch. I thought to myself, "Hmmmm..... maybe I'm generating them wrong." So I looked at how other people generated their numbers with discord.js...
...aaaand I hit a wall. As far as I can tell, no one has ever tried generating ping numbers with discord.js. If they have, they haven't shared their precious findings online. At least, that's what it looks like to me. (if you have a link to such a tutorial or post, please send it to me)
I'm generating the numbers with ${Date.now() - message.createdTimestamp} This is the only way I have found to generate them, so if anyone has a better method, I would love to see it.
That snippet fits right in with the rest of my code (and yes, it is a very boring bot):
const Discord = require('discord.js');
const client = new Discord.Client();
const token = require('./token.json').token;
client.on('ready', () => {
console.log('Bot is up and running!');
});
var prefix = "?"
client.on('message', message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
if (message.content.startsWith(prefix + 'ping')) {
message.channel.sendMessage('Pong! Your ping is `' + `${Date.now() - message.createdTimestamp}` + ' ms`');
}
});
client.login(token);
If anybody could give me a reason why I'm getting negative numbers, or give me a better way to generate them, I would be extremely grateful. Thanks in advance.
The variation in ping you're experiencing is due to the variation between between your clock and the remote clock as well as the message id's used to calculate the timestamp not being all that accurate.
Before you jump to one meaning for ping you have to decide what you want to measure. If you're looking to measure the round trip time to send a message and get that same message back frond discord, you could potentially send a discord message, start a timer. then when the promise resolves check how much time has passed.
You could also use .ping as suggested in another answer for the heartbeat ping.
You could also ping the api endpoint though you would probably only be measuring your delay to cloudflare...
You may getting different results, because the Date.now is based on your computer's clock and message.createdTimestamp comes from Discord server (not your computer) clock.
The reason nobody's sharing the ping feature is because it's just reading a client object property client.ws.ping.
https://discord.js.org/#/docs/main/stable/class/WebSocketManager?scrollTo=ping
You can not get the actual ping of another user. But you can get pretty close.
You know that using the system's clock won't work for you because it's out of sync with the actual server.
Your bot can send a message and edit it after that. Then you have two timestamps:
var resMsg = await msg.channel.send('Ping is being appreciated... :bar_chart:');
resMsg.edit('Ping: ' + Math.round((resMsg.createdTimestamp - msg.createdTimestamp) - client.ws.ping))); //client.ping has been moved to the WebSocketManager under client.ws.ping
Subtracting the ping of the bot will remove it's latency to the API while submitting the message.
Hope I could help!
Try this:
client.on('message', message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
if (message.content.startsWith(prefix + 'ping')) {
msg.channel.send({embed: {
color: 0x2ed32e,
fields: [{
name: "Pong",
value: "My Ping: " + Math.round(client.ws.ping) + ' ms' //client.ping has been moved to the WebSocketManager under client.ws.ping
}
],
}
})
}})
I hope this will help c:
client.on('messageCreate', message => {
if (message.content === `${config.PREFIX}ping`) {
message.channel.send("Calculating ...").then(m =>{
var ping = Math.round((m.createdTimestamp - client.ws.ping) - message.createdTimestamp ); //more closer to discord ping
setTimeout(() => {
m.edit(`**Your Ping Is: **${ping}ms`);
}, 3000);
});
}) //DISCORD.JS V13
I'm sorry that you're facing this issue with your Discord bot. I used your code to analyse the issue and have come up with this solution. You see how you have:
${Date.now() - message.createdTimestamp}
Well, all you have to do is swap around "Date.now()" and "message.createdTimestamp" around
What you will achieve from this is:
${message.createdTimestamp - Date.now()}
I tried this method, and it worked fine. It gave me the most accurate results.
Hope this answer helped you!

Categories

Resources