Have a role to react discord.js - bots

I am new to this of the Discord.js bots, what I want to do is that you need the "Kuro" role to react to the emoji. If you react and do not have it does nothing
This is the code:
message.awaitReactions(filter, { max: 1, time: 120000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '❌') {
message.edit("**A s d**");
}
})
.catch(collected => {
console.log(`After a minute, only ${collected.size} out of 4 reacted.`);
});

I would recommend using https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-messageReactionAdd
Listen for messageReactionAdd (which gives you the MessageReaction and the User that reacted)

Related

Push notification shows object Object even though i am setting the right value

I am trying to implement push notifications with react and nodejs using service workers.
I am having problem while i am showing notification to the user.
Here is my service worker code:
self.addEventListener('push', async (event) => {
const {
type,
title,
body,
data: { redirectUrl },
} = event.data.json()
if (type === 'NEW_MESSAGE') {
try {
// Get all opened windows that service worker controls.
event.waitUntil(
self.clients.matchAll().then((clients) => {
// Get windows matching the url of the message's coming address.
const filteredClients = clients.filter((client) => client.url.includes(redirectUrl))
// If user's not on the same window as the message's coming address or if it window exists but it's, hidden send notification.
if (
filteredClients.length === 0 ||
(filteredClients.length > 0 &&
filteredClients.every((client) => client.visibilityState === 'hidden'))
) {
self.registration.showNotification({
title,
options: { body },
})
}
}),
)
} catch (error) {
console.error('Error while fetching clients:', error.message)
}
}
})
self.addEventListener('notificationclick', (event) => {
event.notification.close()
console.log(event)
if (event.action === 'NEW_MESSAGE') {
event.waitUntil(
self.clients.matchAll().then((clients) => {
if (clients.openWindow) {
clients
.openWindow(event.notification.data.redirectUrl)
.then((client) => (client ? client.focus() : null))
}
}),
)
}
})
When new notification comes from backend with a type of 'NEW_MESSAGE', i get the right values out of e.data and try to use them on showNotification function but it seems like something is not working out properly because notification looks like this even though event.data equals to this => type = 'NEW_MESSAGE', title: 'New Message', body: , data: { redirectUrl: }
Here is how notification looks:
Thanks for your help in advance.
The problem was i assigned parameters in the wrong way.
It should've been like this:
self.registration.showNotification(title, { body })

Discord.js maximum number of webhooks error

Have this slash command code and turned it into webhook. It worked when I used it once but it stopped working after that. I got this error DiscordAPIError: Maximum number of webhooks reached (10). Does anyone have any idea on how to fix this?
Code:
run: async (client, interaction, args) => {
if(!interaction.member.permissions.has('MANAGE_CHANNELS')) {
return interaction.followUp({content: 'You don\'t have the required permission!', ephemeral: true})
}
const [subcommand] = args;
const embedevent = new MessageEmbed()
if(subcommand === 'create'){
const eventname = args[1]
const prize = args[2]
const sponsor = args[3]
embedevent.setDescription(`__**Event**__ <a:w_right_arrow:945334672987127869> ${eventname}\n__**Prize**__ <a:w_right_arrow:945334672987127869> ${prize}\n__**Donor**__ <a:w_right_arrow:945334672987127869> ${sponsor}`)
embedevent.setFooter(`${interaction.guild.name}`, `${interaction.guild.iconURL({ format: 'png', dynamic: true })}`)
embedevent.setTimestamp()
}
await interaction.followUp({content: `Event started!`}).then(msg => {
setTimeout(() => {
msg.delete()
}, 5000)
})
interaction.channel.createWebhook(interaction.user.username, {
avatar: interaction.user.displayAvatarURL({dynamic: true})
}).then(webhook => {
webhook.send({content: `<#&821578337075200000>`, embeds: [embedevent]})
})
}
}
You cannot fix that error, discord limits webhooks per channel (10 webhooks per channel).
However, if you don't want your code to return an error you can just chock that code into a try catch or add a .catch
Here is an example of how to handle the error:
try {
interaction.channel.createWebhook(interaction.user.username, {
avatar: interaction.user.displayAvatarURL({dynamic: true})
}).then(webhook => {
webhook.send({content: `<#&821578337075200000>`, embeds: [embedevent]})
})
} catch(e) {
return // do here something if there is an error
}

only accept number discord.js

What I would like to eliminate in this code is that the program only reacts to numbers, not other characters, then it says "Not an appropriate value"
Can anyone help me with this?
e.g:
User: -clearr
Bot: How many messages do you want to delete?
User: asd
Bot: asd message successfully deleted!
This code:
module.exports = {
name: 'clearr',
description: "Clear messages!",
async execute(client, message, args) {
if(!args[0]) {
let filter = m => m.author.id === '365113443898097666'
message.channel.send(`How many messages do you want to delete?`).then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 10000,
errors: ['time']
})
.then(message => {
message = message.first()
message.channel.bulkDelete(message);
message.channel.send (`\`${message} message\` successfully deleted!`)
.then(message => {
message.delete({ timeout: 5000 })
})
.catch(console.error);
})
})
}
}
}
Thank you very much in advance for your replies!
You have to use Number.isNaN(+var):
if(Number.isNaN(+args[0])) return message.reply('Please, specify how many messages do you want to delete!')

(discord.js) how to mention the user who react to the bot message?

How can I mention the user who reacted to my bot message?I want to send message like, "#user reacted to my message!", here is my code:
msg.awaitReactions((reaction, user) => user.id == user.id && (reaction.emoji.name == '👍'), { max: 1, time: 30000 }).then(collected => {
if (collected.first().emoji.name == '👍') {
//here I want to send the message with the mention
} else {
//I added it for case that I going to use yes or no react question
}
}).catch(() => {
//maybe I will add here message that says the time passed.
});
After reading articles and troubleshooting I came up with the following solution:
msg.awaitReactions((reaction, user) => user.id == user.id && (reaction.emoji.name == '👍'),
{ max: 1, time: 30000 }).then(collected => {
const reaction = collected.first();
if (collected.first().emoji.name == '👍') {
const member = reaction.users.cache.find((user) => !user.bot);
message.channel.send(`test is ${member}`)
} else {
//I added it for case that I gonna use yes or no react question
}
}).catch(() => {
//maybe I will add here message that says the time passed.
});

How to create a voice channel by reacting on embed?

I'm trying to use this code to create an embed, if you react on it a specific voice channel will be created on the server.
That's very similar to roles menu, but it will not give you a role, it will create a channel.
The code is working, but when you react on the embed the bot do nothing.
module.exports = {
name: 'cc',
description: 'Help!',
execute(message) {
const embed = {"image": {"url": `${message.author.displayAvatarURL}`}}
message.channel.send({embed})
.then((message) => { message.react("❤") })
.then(() => {
const filter = (reaction, user) => reaction.emoji.name === "❤" && user.id === message.author.id;
const collectorForU = message.createReactionCollector(filter, {time: 1000/*time in ms*/});
collectorForU.on("collect", () => {message.guild.createChannel("╔═════ஜ۞ஜ═════╗", "voice")})
})
}
};
There is no error on the console.
The reaction collector expires before anything can be collected; the time option is set to 1 second.

Resources