How do I make the collector, specifically for each person - javascript

So I have a bot, then I want to make the bot can collect a message, then reply if he detect a spesific word, but the problem is my bot keep creating new collector if someone type the tekong, so when the bot detect the word it will gonna respond twice, depend on how many collector are created. How do I make the bot so that 1 person can only create 1
Here's my code
client.on("message", (message) => {
if (message.content.toLowerCase().startsWith('tekong')) {
message.channel.send('Bot is collector messages...')
let filter = m => m.content.includes('test') && m.author.id === '744882468741709824'
let collector = message.channel.createMessageCollector(filter, {max: 1})
collector.on('collect', indonesia => {
console.log(indonesia.content);
})
collector.on('end', m => {
console.log(`Collected ${m.size} items`)
if (m.size === 1) {
message.channel.send('Congratulations your enchantments is works!')
}
})
}

You can just simply make a Set ( Array would also be an option, but I prefer Set as its easier to delete entries):
let blocked = new Set();
Then inside your message event you can use:
if (message.content.toLowerCase().startsWith('tekong')) {
if(blocked.has(message.author.id)) return;
blocked.add(message.author.id);
If you are done and want the user to allow to use the command again, you can simply use:
blocked.delete(message.author.id);

Related

How to make button count dynamic in discord.js or discord.py

I want to make a role store for an economic bot in discord, where you can buy and set roles, but I have 1 problem, I don’t know how to make dynamic buttons (an indefinite number) for buying, I want to do it like in the screenshot below
enter image description here
I tried to somehow solve this problem using the nextcord library (Python), but in the end these attempts were unsuccessful, I also started to study discord.js (JavaScript), but there is still not enough knowledge to solve the problem
Looks like you want a polling where users reaction are the votes in discordjs? here's the script for that, not sure about the buying logic.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('message', async message => {
if (message.content === '!poll') {
// Create the poll message
const pollMessage = await message.channel.send('What is your favorite color?');
// Add the emoji reactions
await pollMessage.react('πŸ”΄');
await pollMessage.react('🟒');
await pollMessage.react('πŸ”΅');
// Create a collector to collect the user reactions (adjust voting time in milliseconds)
const filter = (reaction) => reaction.emoji.name === 'πŸ”΄' || reaction.emoji.name === '🟒' || reaction.emoji.name === 'πŸ”΅';
const collector = pollMessage.createReactionCollector(filter, { time: 15000 });
// Create a variable to store the results
let results = {'πŸ”΄': 0, '🟒': 0, 'πŸ”΅': 0};
// Collect the reactions
collector.on('collect', (reaction, user) => {
results[reaction.emoji.name]++;
});
// Print the results when the collector stops (you can put the buying logic here)
collector.on('end', () => {
message.channel.send(`Results: \nπŸ”΄: ${results['πŸ”΄']} \n🟒: ${results['🟒']} \nπŸ”΅: ${results['πŸ”΅']}`);
});
}
});
client.login(YOUR_TOKEN);

Custom bot to temporarily add roles in discord.js

Hey so my i want my bot to temporarily assign a role when the client (user) uses a certain word. I have the code for the words ready but i dont have any clue on how to temprole them the role.
bot.on('message', message=>{
const swearWords = ["xyz"];
if( swearWords.some(word => message.content.toLowerCase().includes(word)) ) {
message.reply("Oh no you said a bad word!!!");
You can use <member>.roles.add() method to add the role and assign a timeout function to remove the role after a specific time using <member>.roles.remove()
bot.on('message', message=>{
const swearWords = ["xyz"];
if( swearWords.some(word => message.content.toLowerCase().includes(word)) ) {
message.reply("Oh no you said a bad word!!!");
const role = message.guild.roles.cache.find(x => x.name == 'rolenamehere'); // finding the role
message.member.roles.add(role); // adding the role
setTimeout(() => message.member.roles.remove(role), 3000); // second param is time in milliseconds
});

discord.js | Remove a role from a member and give said role to another member

I'm trying to remove a role from one person, and give that role to the person who initiated the command.
It works the first time, when person A does it. But when someone else tries call the command for the second time, the code doesn't find person A. Any help would be cool.
//Just some startup stuff
const { error, timeStamp } = require('console'),
client = new Discord.Client(),
client.login('How About No?')
var command, role, person
//Check if it's alive
client.once('ready', () => {
console.log(`${client.user.tag} is online`)
})
//When a message is sent
client.on('message', message => {
command = message.content.toLowerCase()
if(command === 'test' && message.guild.id === 'the server ID'){
role = message.guild.roles.cache.find(r => r.id === 'the role ID') //Find the correct role
person = role.members.first()
/* I can use ".first()" here, because there's never supposed to be more than one person with this role.
The problem is here. On the second run, it outputs "undefined" even though a person has the role. */
//If a person has the role, remove it from them.
if(typeof person !== 'undefined') person.roles.remove(role).catch(error => console.log(error))
//Give the role
person = message.member
person.roles.add(role).catch(error => console.log(error))
}
})
It can happen sometimes because the cache won't update fast enough.
What you can do is fetch the role instead with API request.
message.guild.roles.fetch('the role ID',true,true)

Message Collector doesn't start when bot DMs user to collect response

So this is moretheless in relation to the previous question, which was answered (the previous one) The bot is no longer spitting out a lot of errors whenever somebody runs the command, and the bot successfully DMs the user the response prompt, but it seems as if the Message Collector isn't starting? The bot DMs the user, nothing spits out in Console, and that's it. You can respond to the bot all day, and it wont collect it and send it to the channel ID. Any pointers?
Here's the code I believe it may revolve around:
collector.on('collect', (message, col) => {
console.log("Collected message: " + message.content);
counter++; ```
And here is all of the code (just in case it actually doesn't revolve around that):
``` if(message.content.toLowerCase() === '&reserveupdate') {
message.author.send('**Thanks for updating us on the reserve. Please enter what you are taking from the reserve below this message:**');
let filter = m => !m.author.bot;
let counter = 0;
let collector = new discord.MessageCollector(message.author, m => m.author.id, filter);
let destination = client.channels.cache.get('my channel id');
collector.on('collect', (message, col) => {
console.log("Collected message: " + message.content);
counter++;
if(counter === 1) {
message.author.send("**Thanks for updating us on the reserve, it is highly appreciated.**");
collector.stop();
}
I think you might be wrong on how you created your message collector.
According to the docs, you should make it this way :
const filter = m => !m.author.bot;
// If you are in an async function :
const channel = await message.author.createDM();
// Paste code here
// Otherwise :
message.author.createDM.then(channel => {
// Paste code here
});
// Code to paste :
const collector = channel.createMessageCollector(filter, { max: 1, time: 60000 });
collector.on('collect', msg => {
// ...
});
Hope this will help you to solve your issue ! :)

Issues awaiting replies in public channel

The following code is resulting in no errors to the console. After I type the command, the first message.reply line executes properly, but the bot doesn't seem to acknowledge someone types 'accept' or 'deny'. Been messing with this for quite a long time. I've done commands like this in private messages and it works. But for some reason since this is in a public channel, it doesn't seem to work.
module.exports.run = async(bot, message, args) => {
//!endbrawl winner [username] loser [username]
let messageArray = message.content.split(" ")
let winner = messageArray[2]
let loser = messageArray[4]
message.reply(`${message.author} wants to close this brawl with ${winner} as the victor and ${loser} as the loser. \n ${winner}, do you accept the result? If yes, type 'accept'. If not, type 'deny'.`);
let winnerUser = message.mentions.users.first();
let filter = m => m.author.id == winnerUser.id;
message.channel.awaitMessages(filter, {
maxMatches: 1,
}).then(collected => {
if (message.author.bot) return;
if (collected.first().content === "accept") {
return message.reply(`${winner} has accepted the proposed result.`)
// put in code asking loser to agree with proposed result
} else if (collected.first().content === "deny") {
return message.reply(`${winner} has denied the proposed result.`)
} else {
return message.reply(`${winner}, your reply was invalid.`)
}
})
}
I have looked for ways to solve this, but most involve private messaging or what was told doesn't work for me. No errors in any of those attempts. It just seems like it isn't even looking at the replies.
Thanks for any and all help! It is greatly appreciated!
message.channel.awaitMessages(filter, {
max: 1,
}).then(...);
That max means that the maximun number of messages that will be processed will be 1: that means that if the next message is not sent by the author the bot will stop listening for new messages. The other message could even be your bot's reply, since you're not waiting for that to be finished before setting the awaitMessages.
Try using maxMatches instead of max.
message.channel.awaitMessages(filter, {
maxMatches: 1,
}).then(...);
Reference: MessageCollectorOptions
With that said, you want the winner to be able to send that message and so you'll need to change your filter function.
You'll first need to get the User object of the winner, then make the filter so that it checks for their id.
let winnerUser = message.mentions.users.first();
let filter = m => m.author.id == winnerUser.id;
You could also match the id from the plain mention, but I find it easier to use the object instead.

Categories

Resources