Trying to find a way where a discord bot can randomly send a message in a given channel - discord.js

I'm using the commando framework. I want the bot I'm making to be able start randomly sending messages in a certain channel when given a command to do so. For example if I typed "!radar" I would expect the bot to continue to randomly send a predetermined message in that channel until it is told to stop.
Here's the code I attempted to use:
async run(message){
message.say("Scanning....")
while(true){
var number = 30;
var imageNumber = Math.floor (Math.random() * (number - 1 + 1)) + 1;
if(imageNumber == 1){
message.say("^ detected!");
}
}
}
When I attempt this code I don't seem to get any errors logs, but I don't get any response from the bot when I send the command.

Related

.includes firing muiltple times

I am trying to test whether a message (string) sent from the user/client is containing a word and then it will pick 1 of 2 random responses and it works, however it sends the message way too many times.
client.on("messageCreate", message => {
if(message.content.includes("dream")) {
var msgnumber= (Math.floor((Math.random() * 2) + 1));
console.log(msgnumber);
if (msgnumber===1) {
message.channel.send("did someone say dream!?");
} else if (msgnumber===2) {
message.channel.send("why we talkin' about dream... huh!?")
}
}
})
It does pick a random message if a message sent contains the keyword, one problem is it sends way too many times.
The output message
Your bot is activating itself. Whenever it posts a message containing "dream", it sees that message, and decides to post a reply, creating an infinite loop. Try adding the line if (msg.author.bot) return; right above where you check for if the message contains "dream". This will exit the function early and avoid the loop.

How can i, after a time x, send me a message with the amount of emojis of a message

How can i, after a time x, send me a message with the amount of emojis of a message. for example
5 reactions to the emoji: 😀
6 reactions to the emoji: 😍
You can use something like this:
message.channel.send('message').then(async (msg) => { // send the message
setTimeout(() => { // use the setTimeout function to add a delay before executing
switch (msg.reactions.cache.size) { // get the number of emojis reacted
case 1: { // if there was 1 emoji:
message.channel.send('something');
break;
}
case 2: { // if there was 2:
message.channel.send('something2');
break;
}
case 3: { // if there was 3:
message.channel.send('something3');
break;
}
// etc.
}
console.log(`${msg.reactions.cache.size} emojis were reacted.`);
}, 10000); // execute after whatever time (in milliseconds) you prefer, I'm using 10000 (10 seconds) as an example
});
After you get the number of emojis reacted (<message>.reactions.cache.size), you can do anything you want with it, I was just using the switch statement as an example.
You also don't have to use the setTimeout function, it's just the easiest way to trigger something after a delay. For example, you could trigger after an event, or anything else you might want.
I am assuming things right now cause for one I don't exactly get what you are trying to say and two, you are being a bit vague without giving any already existing code.
If the bot should send you the message only when a message with emojis is sent then all you have to do is, in your message event, check if the message contains an emoji. A simple regular expression would do: const emojiRegex = /<:[a-zA-Z0-9]{0,}:\d{18}>/ig;. Then check if the message contains any match.
const matches = message.content.match(emojiRegex);
if (matches) {
const owner = client.users.cache.get('user_id'); // enter your user id
owner.send(`There have been ${matches.length} emojis in message \`${message.id}\` at ${message.url}`);
}
First, Calculate the number of reactions on your message.
If the number of reactions on your message reaches 5, then tell your bot to send you a message!

How to delete n messages from a channel?

I am working on a discord bot. I want to implement a feature like Tatsumaki's t!prune 5 (deletes 5 messages from the history).
Okay, lemme show you what I mean one way or another:
msg.channel.delete(2); // 2 is the number of messages being deleted.
// this is not a real function, just an example
Is there such a thing like what I showed?
Try to use the following
const fetchedMessages = await msg.channel.fetchMessages();
const amount = 50 // number of messages that should be deleted (max 50 otherwise you have to change the option limit property for .fetchMessages())
for (let i = 0; i < amount; i++) {
await fetchedMessages[i].delete()
}
You could also use the .bulkDelete() function:
await msg.channel.bulkDelete(AMOUNT)

Getting count of a specific reaction on a message

I'm trying to make a bot that will delete messages with a certain amount of thumbsdown reactions. I'm having trouble identifying the count of a specific reaction on a message.
Basically, I've created a command that waits for messages and adds them to my msgarray. After each message, I want to go through the array and delete any messages with the specified amount of reactions.
This is what I have so far:
var msgarray = [];
const msgs = await message.channel.awaitMessages(msg => {
msgarray.push(msg);
for (i = 0; i < msgarray.length; i++) {
// I'm not sure where to go from here, I want to make an if statement that checks
// for a certain amount of thumbsdown reactions on the message
if (msgarray[i].reactions) {
// incomplete
}
}
});
This is my first time programming in javascript, so I apologize if this code doesn't make much sense.
TextChannel.awaitMessages() resolves with a Collection, so the msg parameter you're using is not a single message, but a Collection of multiple messages.
Also, it would be better to check messages only when they get a reaction, using the messageReactionAdd event, that fires every time someone adds a reaction.
It should look like this:
// this code is executed every time they add a reaction
client.on('messageReactionAdd', (reaction, user) => {
let limit = 10; // number of thumbsdown reactions you need
if (reaction.emoji.name == '👎' && reaction.count >= limit) reaction.message.delete();
});

Discord.js how to make an announcement command

I'm trying to make an announcement command for my discord bot running discord.js. For example, if I say +ann (#CHANNEL) (ANNOUNCEMENT) it will post it there. I don't have any code for this and have been looking for ages. May you please help?
Basic Command Setup
When making a basic command, the first thing you're gonna want to set up is something like this:
<Discord.Client instance here>.on("message", message => {
if(message.author.bot) return;
let messageArray = message.content.split(" ");
let command = messageArray[0];
let args = messageArray.slice(1);
}
What does this do?
First of all, the code inside those curly braces is called whenever the bot "receives" a message. This means that the code is run whenever a message is sent in any channel in any server it is a part of, including DMs. The first line in this function ensures that the user who sent the message was not a bot, as you don't want other bots triggering commands on your bot.
Then, this code does some simple splitting on the message, so that the messageArray is an array of each word in the message, as determined by a space. For example, this would mean that if I sent Hello there, Cloudy Sounds!, messageArray would contain the following:
['Hello', 'there,', 'Cloudy', 'Sounds!']
command is the first word of this message (in this case 'Hello'). This is important because when sends a command to the bot, such as the +ann command you wanted above, the standard format of a message is
<prefix><command> <arguments>
So, later on in your code, you can use command to get both the prefix and the command in one string, allowing you to see if someone wants the bot to do something, or if they're just chatting with a friend and want nothing to do with the bot.
Finally, args is an array of the rest of the words, in this case ['there,', 'Cloudy', 'Sounds!'].
By using the 3 of these variables in combination, you can easily extract all the important information out of a message.
Getting The Channel
Since the user's command will contain a mentioned channel, the first thing we're gonna want to do is get that channel as a Discord.js Channel Class, so we can later send messages to it.
To get this, we can store the result of message.mentions.channels() into channel. Since we're going to be mentioning a chanel in a guild, we're gonna want to make sure it's not a DM first, and that the command actually starts with our prefix, in this case '+'. So now, our code looks like this:
<Discord.Client instance here>.on("message", message => {
if(message.author.bot) return;
let messageArray = message.content.split(" ");
let command = messageArray[0];
let args = messageArray.slice(1);
if(message.channel.type === "dm") return;
if(!message.content.startsWith('+')) return;
if(command === '+ann') {
let channel = message.mentions.channels();
}
}
Extracting the Announcement
Now that we have out channel, we're gonna want to get our announcement out from the message. We'll do this using args.
So, how do we do this?
First of all, we know that args[1] is going to be the mention of the channel ('#channel'), so that's not a part of the command. Everything else, however, is a part of our announcement, so we combine that all into a string using the following:
let announcement = args.slice(1).join(" ");
Putting it all together
Now that we have our announcement and channel, we can finally send it.
The final code would be:
<Discord.Client instance here>.on("message", message => {
if(message.author.bot) return;
let messageArray = message.content.split(" ");
let command = messageArray[0];
let args = messageArray.slice(1);
if(message.channel.type === "dm") return;
if(!message.content.startsWith('+')) return;
if(command === '+ann') {
let channel = message.mentions.channels();
let announcement = args.slice(1).join(" ");
channel.send(announcement);
}
}
Welcome to Stack Overflow, and let me know if you have any problems with this answer, or need further clarification!
Try this:
.on("message", message => {
if(message.author.bot) return;
let messageArray = message.content.split(" ");
let command = messageArray[0];
let args = messageArray.slice(1);
if(message.channel.type === "dm") return;
if(!message.content.startsWith('+')) return;
if(command === '+ann') {
let channel = message.mentions.channels();
let announcement = args.slice(1).join(" ");
channel.send(announcement);
}

Resources