.includes firing muiltple times - discord

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.

Related

Update one List from values another List

I wrote the code what get Json data and put in listPc. And wrote the loop that add value 'hostName' form listPc to pcBusy List. But my code only add values to second list, If I press GetButton values in pcBusy list duplicates. I need to update the pcBusy List, not only add the same values.
This print if I press button two times:
[S14, S18, S19, S12, S02, V08, S01, O09, S14, S18, S19, S12, S02, V08, S01, O09]
Thanks for help!)
void fetchDataStandart() async {
final urlAuth =
Uri.parse('http://XXX.XX.XXX.XXX/api/usersessions/activeinfo');
final response = await http
.get(urlAuth, headers: <String, String>{'authorization': basicAuth});
if (response.statusCode == 200) {
List listPc = List.from(json.decode(response.body)['result']);
for (int i = 0; i < listPc.length; i++) {
pcBusy.add(listPc[i]['hostName']);
}
print(pcBusy);
} else {
throw Exception('Ошибка получения данных');
}
}
TLDR: add Future<void> as your function return type and consider invoking pcBusy.clear() before overwriting with new data (depends on your logic, though).
With a little more context you'd help me giving you a more complete answer, but here's what I can see from your code:
Your button adds data as many times as you're pressing it. IF you press it two times, you'll get "double" the data, sooner or later. This happens because you use the add method, which just appends data on your list. You can either reset the values with pcBusy.clear() before you add values or do something else if you think that this function shouldn't be overwriting your list. This really depends on your logic;
You're awaiting a Future (via the async keyword), yet your Function doesn't return a Future. This means that - most likely - somewhere else you're awaiting for this function that in reality doesn't need to be awaited. As a consequence this means that when you first press the button, i.e. you fire the future, you can't await for it to happen and your UI doesn't update. The second time, it does update your UI with the previous result and the Future is fired again, letting it update your list with twice the values again as explained in step (1).
Hope this helps. EDIT. Here's some edited code:
// we want this function to be awaited: let it be a Future<void> async function
Future<void> fetchDataStandart() async {
// ... firing an async HTTP request
if (response.statusCode == 200) {
// if everything is OK, decode the JSON
List listPc = List.from(json.decode(response.body)['result']);
// the following will OVERWRITE the list.
pcBusy.clear(); // Or maybe save previous data somewhere else?
for (int i = 0; i < listPc.length; i++) {
pcBusy.add(listPc[i]['hostName']);
}
print(pcBusy);
} else {
throw Exception('Ошибка получения данных');
}
}
To remove duplicates you can convert the list to a set then back to a list again.
pcBusy.toSet().toList();

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

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.

Discord.js bot isn't clearing messages, but still sends the x amount of messages have been deleted message

I tried to copy this piece of code over from a previous bot I have made on the same server with a different command name, and now it isn't deleting the messages and I can't figure out why not.
bot.on('message', msg =>{
if(!msg.author.bot && msg.content.startsWith(PREFIX))
{
let args = msg.content.substring(PREFIX.length).split(" ");
switch(args[0])
{
case 'ClearMessages':
if (msg.member.roles.cache.some(r=>["RNGesus"].includes(r.name)))
{
msg.channel.bulkDelete(args[1], true).catch(err=> {
console.error(err)
msg.channel.send("An error has occured while trying to delete messages")
});
msg.channel.send(`${args[1]} messages have been deleted`)
.then(msg =>{
msg.delete({timeout: 3000})
})
.catch(console.error)
}
break;
It also doesn't give any error messages in the console when the bot is supposed to be deleting the messages. If anybody can help at all it would be appreciated, I am fairly new to discord.js and one of my friends helped me make this. I tried to ask them for help but they couldn't figure it out either.
The first parameter of TextChannel.bulkDelete() is supposed to be an array/collection of messages or number of messages to delete. Obviously you're trying to give a number of messages to delete, however you're actually providing a string.
You need to first convert args[0] to a number using the unary plus operator (+), then round it to an integer using Math.floor() (or using a double bitwise NOT operator (~) if you want to be fancy and more efficient). As a suggestion, you should also put in a check to make sure the number is valid.
if (msg.member.roles.cache.some((r) => ['RNGesus'].includes(r.name))) {
if (+args[1] < 2 || +args[1] > 100)
return message.channel.send('The number must be at least 2 and at most 100');
msg.channel.bulkDelete(Math.floor(+args[1]), true).catch((err) => {
console.error(err);
msg.channel.send('An error has occured while trying to delete messages');
});
msg.channel
.send(`${args[1]} messages have been deleted`)
.then((msg) => {
msg.delete({ timeout: 3000 });
})
.catch(console.error);
}

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!

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();
});

Resources