Why "member.add.roles" doesnt work for me? - node.js

I have this code rn
async function role(color) {
let user = message.member
user.roles.cache.map(v => { return v }).filter(v => v.name.startsWith('MerasuMin-Clr-')).forEach(role => {
console.log(role)
user.roles.remove(role)
})
let roleColor = message.guild.roles.cache.find(v => v.name === ("MerasuMin-Clr-"+color))
user.roles.add(roleColor)
user.send('Your name in '+message.guild.name+' has colorized to '+color)
}
Well i console logged the roleColor variable, and it returns the role that i expected
But... the role is not added
I have tried passing the id of role but no luck
What do i need to fix or add?
Full code
const { Client, EmbedBuilder } = require('discord.js')
module.exports = {
name: "color",
type: "customization",
description: "Customize the color of your name",
aliases: ["clr", "cl"],
callback: async(client, message, args, cmd) => {
let emb = new EmbedBuilder()
.setTitle('Colorize Name!')
.setDescription('Colors Available\n\n1⃣ - Black\n2⃣ - Purple\n3⃣ - Pink\n4⃣ - Green\n5⃣ - Orange\n6⃣ - Red\n7⃣ - Blue\n8⃣ - Yellow\n9⃣ - LightBlue')
.setColor(0xADD8E6)
.setFooter({ text: message.author.tag, iconUrl: message.author.displayAvatarURL() })
message.reply({embeds:[emb]}).then((msg) => {
msg.react('1⃣')
msg.react('2⃣')
msg.react('3⃣')
msg.react('4⃣')
msg.react('5⃣')
msg.react('6⃣')
msg.react('7⃣')
msg.react('8⃣')
msg.react('9⃣')
let filter = (reaction, user) => {
return user.id === message.author.id
}
msg.awaitReactions({filter, max: 1, time: 172800000, errors: ['time']})
.then(goods)
.catch(gan)
async function goods(collected) {
let reaction = collected.first()
if(reaction.emoji.name === '1⃣') {
reaction.users.remove(message.author.id)
return role('Black')
} else if(reaction.emoji.name === '2⃣') {
reaction.users.remove(message.author.id)
return role('Purple')
} else if(reaction.emoji.name === '3⃣') {
reaction.users.remove(message.author.id)
return role('Pink')
} else if(reaction.emoji.name === '4⃣') {
reaction.users.remove(message.author.id)
return role('Green')
} else if(reaction.emoji.name === '5⃣') {
reaction.users.remove(message.author.id)
return role('Orange')
} else if(reaction.emoji.name === '6⃣') {
reaction.users.remove(message.author.id)
return role('Red')
} else if(reaction.emoji.name === '7⃣') {
reaction.users.remove(message.author.id)
return role('Blue')
} else if(reaction.emoji.name === '8⃣') {
reaction.users.remove(message.author.id)
return role('Yellow')
} else if(reaction.emoji.name === '9⃣') {
reaction.users.remove(message.author.id)
return role('LightBlue')
}
async function role(color) {
let user = message.member
user.roles.cache.map(v => { return v }).filter(v => v.name.startsWith('MerasuMin-Clr-')).forEach(role => {
console.log(role)
user.roles.remove(role)
})
let roleColor = message.guild.roles.cache.find(v => v.name === ("MerasuMin-Clr-"+color))
user.roles.add(roleColor)
user.send('Your name in '+message.guild.name+' has colorized to '+color)
}
}
async function gan() {
setTimeout(() => {
msg.edit('USED!')
}, 1000)
}
})
}
}

Related

How to check multiconditions to concatenate an observable with rxjs

I would like to make check condition on message which is an observable and to costumize the output like this scenerio :
check if the messsage is to me or from me and concatenate 20 first caracters with the name of friend or if it is my message with you
chech the type of message if it is a photo or file to make a message you sent an attament for example
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
let message: Observable<string>;
const messageModel = this.allDirectMessages$
.pipe(
map((x) =>
x.filter(
(f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
)
)
)
.pipe(map((data) => data[data.length - 1].messageModel))
.pipe(
map((item) => {
if (item.to.userName == onlineUserModel.userName) {
message = concat("You", item.content, "...");
}
else (item.to.userName == onlineUserModel.userName) {
message = concat("You", item.content, "...");
}
})
);
return message;
}
If you want to return the message as an Observable<string> you can do something like this:
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
return this.allDirectMessages$
.pipe(
filter((f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
),
map((data) => {
const item = data[data.length - 1].messageModel;
if (item.to.userName == onlineUserModel.userName) {
return `You ${item.content}...`;
}
else (item.from.userName == onlineUserModel.userName) {
return `Them ${item.content}...`;
}
})
);
}
I try to share you my result, just I added the map operator before filter:
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
return this.allDirectMessages$
.pipe(
filter((f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
),
map((data) => {
const item = data[data.length - 1].messageModel;
if (item.to.userName == onlineUserModel.userName) {
return `You ${item.content}...`;
}
else (item.from.userName == onlineUserModel.userName) {
return `Them ${item.content}...`;
}
})
);
}

Migrating from background page to service worker

In January 2023 the extensions with the Manifest V2 will stop working, and I try to migrate to V3 but I have the problem that I have to migrate to service worker
With the V2 manifest I had my background.js file
const browser = chrome || browser
const tabQuery = (options, params = {}) => new Promise(res => {
if (!options.countPinnedTabs) params.pinned = false
browser.tabs.query(params, tabs => res(tabs))
})
const windowRemaining = options =>
tabQuery(options, { currentWindow: true })
.then(tabs => options.maxWindow - tabs.length)
const totalRemaining = options =>
tabQuery(options)
.then(tabs => options.maxTotal - tabs.length)
const updateBadge = options => {
if (!options.displayBadge) {
browser.browserAction.setBadgeText({
text: "" })
return;
}
Promise.all([windowRemaining(options), totalRemaining(options)])
.then(remaining => {
browser.browserAction.setBadgeText({
text: Math.min(...remaining).toString()
});
chrome.browserAction.setBadgeBackgroundColor({
color: "#7e7e7e"
})
})
}
const detectTooManyTabsInWindow = options => new Promise(res => {
tabQuery(options, { currentWindow: true }).then(tabs => {
if (options.maxWindow < 1) return;
if (tabs.length > options.maxWindow) res("window");
});
})
const detectTooManyTabsInTotal = options => new Promise(res => {
tabQuery(options).then(tabs => {
if (options.maxTotal < 1) return;
if (tabs.length > options.maxTotal) res("total");
});
})
const getOptions = () => new Promise((res, rej) => {
browser.storage.sync.get("defaultOptions", (defaults) => {
browser.storage.sync.get(defaults.defaultOptions, (options) => {
res(options);
})
})
})
const displayAlert = (options, place) => new Promise((res, rej) => {
if (!options.displayAlert) { return res(false) }
const replacer = (match, p1, offset, string) => {
switch (p1) {
case "place":
case "which":
return place === "window" ?
"one window" : "total";
break;
case "maxPlace":
case "maxWhich":
return options[
"max" + capitalizeFirstLetter(place)
];
break;
default:
return options[p1] || "?";
}
};
const renderedMessage = options.alertMessage.replace(
/{\s*(\S+)\s*}/g,
replacer
)
alert(renderedMessage);
})
let tabCount = -1
let previousTabCount = -1
let amountOfTabsCreated = -1
const updateTabCount = () => new Promise(res => browser.tabs.query({}, tabs => {
if (tabs.length == tabCount) {
return res(amountOfTabsCreated);
}
previousTabCount = tabCount
tabCount = tabs.length
amountOfTabsCreated =
~previousTabCount ? tabCount - previousTabCount : 0
res(amountOfTabsCreated)
}))
let passes = 0;
const handleExceedTabs = (tab, options, place) => {
console.log(place)
if (options.exceedTabNewWindow && place === "window") {
browser.windows.create({ tabId: tab.id, focused: true});
} else {
browser.tabs.remove(tab.id);
}
}
const handleTabCreated = tab => options => {
return Promise.race([
detectTooManyTabsInWindow(options),
detectTooManyTabsInTotal(options)
])
.then((place) => updateTabCount().then(amountOfTabsCreated => {
if (passes > 0) {
console.log("passed with pass no. ", passes)
passes--;
return;
}
console.log("amountOfTabsCreated", amountOfTabsCreated)
displayAlert(options, place)
if (amountOfTabsCreated === 1) {
handleExceedTabs(tab, options, place);
app.update()
} else if (amountOfTabsCreated > 1) {
passes = amountOfTabsCreated - 1
} else if (amountOfTabsCreated === -1) {
handleExceedTabs(tab, options, place);
app.update()
} else {
throw new Error("weird: multiple tabs closed after tab created")
}
}))
}
const app = {
init: function() {
browser.storage.sync.set({
defaultOptions: {
maxTotal: 20,
maxWindow: 20,
exceedTabNewWindow: false,
displayAlert: true,
countPinnedTabs: false,
displayBadge: true,
alertMessage: chrome.i18n.getMessage("string_7")
}
});
browser.tabs.onCreated.addListener(tab =>
getOptions().then(handleTabCreated(tab))
)
console.log("init", this)
browser.windows.onFocusChanged.addListener(app.update)
browser.tabs.onCreated.addListener(app.update)
browser.tabs.onRemoved.addListener(app.update)
browser.tabs.onUpdated.addListener(app.update)
},
update: () => {
updateTabCount();
getOptions().then(updateBadge)
}
};
app.init();
app.update();
function capitalizeFirstLetter(string) {
return string[0].toUpperCase() + string.slice(1);
}
Any suggestions on how to convert it for service worker to work with Manifest V3?
Thank you and I look forward to your comments

Discord js blacklist

Hello I just started in computer science and I would like to make a system of blacklist that when a person is blacklisted the person is banned from all servers and present the bot then delete the messages of the blacklisted user and moreover who can send a message that the person is blacklisted and by whom especially
'use strict'
const Command = require('../../structure/Command.js')
class Staff extends Command {
constructor() {
super({
name: 'blacklist',
category: 'anti-raid',
description: 'Allows people who are staff to blacklist one person.',
usage: 'blacklist',
example: ['blacklist <add/remove> <#user/id> <reason>'],
aliases: []
})
}
async run(client, message, args) {
let staff = client.bdd.query('SELECT * FROM user_staff WHERE user_id = ?', [message.author.id])
if (staff) {
if (args[1] === 'add') {
let member = message.mentions.members.first() || client.users.cache.get(args[2])
if (!member) {
let memberId = args[2]
let foundMemberId = false
if (memberId.length === 18) {
foundMemberId = true
} else if (memberId.length > 18) {
memberId = memberId.substring(3)
memberId = memberId.slice(0, -1)
if (memberId.length === 18) {
foundMemberId = true
}
}
if (foundMemberId === true) {
member = {
id: memberId
}
}
if (foundMemberId === false) {
return message.channel.send('Please specify a correct ID or mention correctly.')
}
}
let reason = args[3].slice(' ')
if(!reason) return message.channel.send('Please specify a reason for this blacklist.')
try {
client.bdd.query('SELECT * FROM user_blacklist WHERE user_id = ?', [member.id], function (err, result) {
if (err) throw err
if (result.length === 0) {
const user = message.member.user.tag
const userId = message.member.user.id
const guild = message.guild.name
const guildId = message.guild.id
client.bdd.query('INSERT INTO user_blacklist SET ?', {user_id: member.id, reason: reason, banned_by: user, banning_guild: guild, banning_guild_id: guildId, banned_by_id: userId })
message.channel.send(`The user with the identification number **${member.id}** is now blacklisted for the following reason: **${reason}** !`)
} else {
message.channel.send(`The user with the identification number **${member.id}** is already blacklisted for the following reason: **${result.reason}** !`)
}
})
} catch (err) {
console.log(err)
}
} else if (args[1] === 'remove') {
let member = message.mentions.members.first() || client.users.cache.get(args[2])
if (!member) {
let memberId = args[2]
let foundMemberId = false
if (memberId.length === 18) {
foundMemberId = true
} else if (memberId.length > 18) {
memberId = memberId.substring(3)
memberId = memberId.slice(0, -1)
if (memberId.length === 18) {
foundMemberId = true
}
}
if (foundMemberId === true) {
member = {
id: memberId
}
}
if (foundMemberId === false) {
return message.channel.send('Please specify a correct ID or mention correctly.')
}
}
try {
client.bdd.query('SELECT * FROM user_blacklist WHERE user_id = ?', [member.id], function (err, result) {
if (err) throw err
if (result.length !== 0) {
client.bdd.query('DELETE FROM user_blacklist WHERE user_id = ?', [member.id])
message.channel.send(`The user with the identification number **${member.id}** was successfully removed from the blacklist..`)
} else {
message.channel.send(`The user with the identification number **${member.id}** is not blacklisted.`)
}
})
} catch (err) {
console.log(err)
}
}
} else {
await message.channel.send('You\'re not part of the staff.')
}
}
}
module.exports = new Staff

Add Users Who React To Reaction To Embed

Trying to make a bot that when the users click on the reaction there discord id goes into an embed Field and if they un click or click another emoji they end up in the field. This is gonna be used for a voting bot that once a certain number of users click yes or no a decision will be made to accept a user or deny a user. Any help?
exports.run = async (client, message, args) => {
message.delete({ timeout: 100 });
if (!args[0]) return message.reply('You need to supply the question');
let embed = new Discord.MessageEmbed()
.setTitle(args.join(' '))
.setDescription('Poll created by ' + message.author.tag)
.addField('Status', 'Voting is currently open.')
.setColor('#ffd700')
.attachFiles(new Discord.MessageAttachment('https://i.imgur.com/QUmbq9o.png', 'thumbnail.png'))
.setThumbnail('attachment://thumbnail.png')
.setFooter('Bot created by James (Rock)₇₇₇');
message.channel.send(embed).then(async msg => {
await msg.react('👍');
await msg.react('👎');
await msg.react('🤷');
await msg.react('🗑️');
const threshold = 6;
async function stop(result) {
collector.stop();
const newEmbed = new Discord.MessageEmbed(msg.embeds[0]);
newEmbed.title = newEmbed.title + ' [CLOSED]';
newEmbed.fields[0] = { name: 'Status', value: 'Voting is now closed.\n' + result };
newEmbed.setThumbnail('attachment://thumbnail.png');
await msg.edit(newEmbed);
msg.reactions.removeAll();
}
async function update() {
const newEmbed = new Discord.MessageEmbed(embed);
const userYes = (votes['👍'].size === 0)? '-' : [...votes['👍']];
const userNo = (votes['👎'].size === 0)? '-' : [...votes['👎']];
const userUnsure = (votes['🤷'].size === 0)? '-' : [...votes['🤷']];
newEmbed.addFields(
{ name: `User Yes (${votes['👍'].size}/${threshold})`, value: userYes, inline: true },
{ name: `User No (${votes['👎'].size}/${threshold})`, value: userNo, inline: true },
{ name: 'User Unsure', value: userUnsure, inline: true }
);
await msg.edit(newEmbed);
if (votes['👍'].size >= threshold) {
await stop('This answer is good enough to get accepted and an upvote.');
// do something
} else if (votes['👎'].size >= threshold) {
await stop('This answer is not good enough to get accepted and an upvote.');
// do something
}
}
const votes = {
'👍': new Set(),
'👎': new Set(),
'🤷': new Set(),
'🗑️': new Set()
};
update();
const collector = msg.createReactionCollector((reaction, user) => !user.bot , { dispose: true });
collector.on('collect', async (reaction, user) => {
if (['👍', '👎', '🤷', '🗑️'].includes(reaction.emoji.name)) {
const userReactions = msg.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));
for (const userReaction of userReactions.values()) {
if (userReaction.emoji.name !== reaction.emoji.name || reaction.emoji.name === '🗑️') {
userReaction.users.remove(user.id);
votes[userReaction.emoji.name].delete(user);
}
}
votes[reaction.emoji.name].add(user);
} else {
reaction.remove();
}
update();
});
collector.on('remove', (reaction, user) => {
votes[reaction.emoji.name].delete(user);
update();
});
});
};
module.exports.help = {
name: "poll"
}
You can read this page from the discord.js guide about reaction collectors, it tells you everything you need to know. You can read this for more info about the .createReactionCollector() method.
There are multiple ways to acheive what you want once you make the reaction collector but I beleive the easiest would look something like this:
message.channel.send('your_message_here')
.then(async function(message) {
await message.react('👍');
await message.react('👎');
await message.react('🤷‍');
const filter = (reaction, user) => {
return ['👍', '👎', '🤷‍'].includes(reaction.emoji.name) && user.id === ogauthor
}
const collector = message.createReactionCollector(filter)
collector.on('collect', (reaction, user) => {
async function collect() {
if (!user.bot) {
if (reaction.emoji.name === '👍') {
//code here
}
//repeat this for the rest of your reactions
reaction.users.remove(user.id) //you can remove the reaction once they react to it and their name is added.
}
}
collect()
});
})
One problem is that this will run forever so you should add a timer to it.
You can use Reaction Collectors for this case to listen to reactions and list them depending on it.
I've made the code below, it works as expected:
message.delete({ timeout: 100 });
if (!args[0]) return message.reply('You need to supply the question');
let embed = new Discord.MessageEmbed()
.setTitle(args.join(' '))
.setDescription('Poll created by ' + message.author.tag)
.setColor('#ffd700')
.setThumbnail("https://i.imgur.com/QUmbq9o.png")
.addFields({name: "User Yes", value: 'None'}, {name: "User No", value: 'None'}, {name: "User Hum", value: 'None'})
.setFooter("Bot created by James (Rock)₇₇₇");
message.channel.send(embed).then(async msg => {
await msg.react('👍');
await msg.react('👎');
await msg.react('🤷');
const filter = (reaction, user) => {
return ["👍", "👎", "🤷"].includes(reaction.emoji.name);
};
const collector = await msg.createReactionCollector(filter);
collector.on('collect', (reaction, user) => {
const reactionsList = ["👍", "👎", "🤷"];
const fieldTitle = ["User Yes", "User No", "User Hum"];
var reactions = reaction.message.reactions.cache.array();
for(var reactionID in reactions) {
for (var i = 0; i < reactionsList.length; i++) {
if(reactionsList[i] === reaction.emoji.name){
let fieldDescription = user.id + "\n";
var users = reactions[reactionID].users.cache.array();
for(var userID in users){
if(users[userID].id === client.user.id || users[userID].id === user.id) continue;
fieldDescription += users[userID].id + "\n";
}
embed.spliceFields(i, 1, {name: fieldTitle[i], value: fieldDescription})
}
}
}
msg.edit(embed);
});
})
I have slightly modified your code and added code to track votes, edit the embed and check when the votes reach the threshold.
Demonstration
Code
message.delete({ timeout: 100 });
if (!args[0]) return message.reply('You need to supply the question');
let embed = new Discord.MessageEmbed()
.setTitle(args.join(' '))
.setDescription('Poll created by ' + message.author.tag)
.addField('Status', 'Voting is currently open.')
.setColor('#ffd700')
.attachFiles(new Discord.MessageAttachment('https://i.imgur.com/QUmbq9o.png', 'thumbnail.png'))
.setThumbnail('attachment://thumbnail.png')
.setFooter('Bot created by James (Rock)₇₇₇');
message.channel.send(embed).then(async msg => {
await msg.react('👍');
await msg.react('👎');
await msg.react('🤷');
await msg.react('🗑️');
const threshold = 1;
async function stop(result) {
collector.stop();
const newEmbed = new Discord.MessageEmbed(msg.embeds[0]);
newEmbed.title = newEmbed.title + ' [CLOSED]';
newEmbed.fields[0] = { name: 'Status', value: 'Voting is now closed.\n' + result };
newEmbed.setThumbnail('attachment://thumbnail.png');
await msg.edit(newEmbed);
msg.reactions.removeAll();
}
async function update() {
const newEmbed = new Discord.MessageEmbed(embed);
const userYes = (votes['👍'].size === 0)? '-' : [...votes['👍']];
const userNo = (votes['👎'].size === 0)? '-' : [...votes['👎']];
const userUnsure = (votes['🤷'].size === 0)? '-' : [...votes['🤷']];
newEmbed.addFields(
{ name: `User Yes (${votes['👍'].size}/${threshold})`, value: userYes, inline: true },
{ name: `User No (${votes['👎'].size}/${threshold})`, value: userNo, inline: true },
{ name: 'User Unsure', value: userUnsure, inline: true }
);
await msg.edit(newEmbed);
if (votes['👍'].size >= threshold) {
await stop('This answer is good enough to get accepted and an upvote.');
// do something
} else if (votes['👎'].size >= threshold) {
await stop('This answer is not good enough to get accepted and an upvote.');
// do something
}
}
const votes = {
'👍': new Set(),
'👎': new Set(),
'🤷': new Set(),
'🗑️': new Set()
};
update();
const collector = msg.createReactionCollector((reaction, user) => !user.bot , { dispose: true });
collector.on('collect', async (reaction, user) => {
if (['👍', '👎', '🤷', '🗑️'].includes(reaction.emoji.name)) {
const userReactions = msg.reactions.cache.filter(reaction => reaction.users.cache.has(user.id));
for (const userReaction of userReactions.values()) {
if (userReaction.emoji.name !== reaction.emoji.name || reaction.emoji.name === '🗑️') {
userReaction.users.remove(user.id);
votes[userReaction.emoji.name].delete(user);
}
}
votes[reaction.emoji.name].add(user);
} else {
reaction.remove();
}
update();
});
collector.on('remove', (reaction, user) => {
votes[reaction.emoji.name].delete(user);
update();
});
});

I need to remove user reaction after reacting

I have a command which allows me to go and query an API to retrieve images and then display them in discord.
Currently I come to search from my API 10 images, I want to set up a navigation system thanks to the discord reactions. Everything works but the problem is that once the user has clicked the reaction remains active. I need to delete the reaction to improve the user experience. Currently it is therefore necessary to double click which is not very practical. Here's the method that doesn't work for deletion :
const removeReaction = (m, msg, emoji) => {
try {
m.reactions.find(r => r.emoji.name == emoji).users.remove(msg.author.id);
} catch(err) {
console.log('err: ', err)
}
}
here is all my code
bot.on('message', async msg => {
if (msg.content.startsWith('!test')) {
const args = msg.content.slice('!test').split(' ')
console.log('args :', args[1])
axios(`https://json-api.example.com/posts?tags=${args[1]}&limit=10`, {
method: 'GET',
})
.then((response) => {
if (response.status === 500) {
msg.channel.send('error')
} else {
if (response.data.posts.length === 0) {
msg.channel.send(`No result for ${args[1]}`)
}
if (response.data.posts.length > 0) {
const resultsLength = response.data.posts.length
const options = {
limit: 60000,
min: 1,
max: resultsLength - 1,
page: 1
}
const pages = []
response.data.posts.map((i, index) => {
pages.push({
"title": `Result page number ${index} for ${args[1]}`,
"url": `${response.data.posts[index].sample_url}`,
"color": 43333,
"footer": {
"icon_url": "https://cdn.discordapp.com/app-icons/708760465999790244/228b2993e942a361518b557ee4511b26.png?size=32",
"text": "Cool footer"
},
"image": {
"url": `${response.data.posts[index].url}`
},
"fields": [
{
"name": "tags",
"value": `${response.data.posts[index].tags[0] || '/'}, ${response.data.posts[index].tags[1] || '/'}, ${response.data.posts[index].tags[2] || '/'}, ${response.data.posts[index].tags[3] || '/'}`
}
]
})
})
const m = msg.channel.send({ embed: pages[options.page] }).then((el) => {
el.react('⬅️')
el.react('➡️')
el.react('🗑️')
})
const filter = (reaction, user) => {
return ['⬅️', '➡️', '🗑️'].includes(reaction.emoji.name) && user.id == msg.author.id
}
const awaitReactions = (msg, m, options, filter) => {
const { min, max, page, limit } = options
m.awaitReactions(filter, { max: 1, time: limit, errors: ['time'] })
.then((collected) => {
const reaction = collected.first()
const removeReaction = (m, msg, emoji) => {
try { m.reactions.find(r => r.emoji.name == emoji).users.remove(msg.author.id); } catch(err) { console.log('err: ', err) }
}
if (reaction.emoji.name === '⬅️') {
removeReaction(m, msg, '⬅️')
if (page != min) {
page = page - 1
m.edit({ embed: pages[page] })
}
awaitReactions(msg, m, options, filter)
}
else if (reaction.emoji.name === '➡️') {
removeReaction(m, msg, '➡️');
if (page != max) {
page = page + 1
m.edit({ embed: pages[page] })
}
awaitReactions(msg, m, options, filter);
}
else if (reaction.emoji.name === '➡️') {
removeReaction(m, msg, '➡️');
if (page != max) {
page = page + 1
m.edit({ embed: pages[page] })
}
awaitReactions(msg, m, options, filter);
}
else if (reaction.emoji.name === '🗑️') {
return m.delete()
}
else {
awaitReactions(msg, m, options, filter)
}
}).catch((err) => { console.log('err: ', err) })
}
awaitReactions(msg, m, options, filter)
Thanks in advance for your help
so, after much research I finally found. I share the answer here.
With the 12+ version of discord.js package a lot has evolved including my problem:
m.reactions.find(r => r.emoji.name == emoji).users.remove(msg.author.id);
must become :
m.reactions.cache.find(r => r.emoji.name == emoji).users.remove(msg.author);
I have made this code a while ago.
It is for an older version of Discord.js but according to docs it should still work.
Basically what you want to do is to use Discord.js createReactionCollector function after you send the picture, then inside this.reactionCollector.on('collect', (reaction, reactionCollector) => {//do your work here}) you can change the picture then call reaction.remove(user); which immediately removes the reaction for that user.
Here's my code:
Note: I have made a class for this command so it might look a bit different for you.
Also in my version, only the user who initially called the command can change the picture. So you will need to modify that part if you want to let anyone change the picture. (It might be a pretty bad idea if your bot is in a large server.)
this.channel.send({embed}).then(msg => {
this.message = msg;
this.message.react('⬅️').then(x => {
this.message.react('➡️');
})
const filter = (reaction, user) => {
return (reaction.emoji.name === '➡️' || reaction.emoji.name === '⬅️') && user.id === this.user.id;
};
this.reactionCollector = this.message.createReactionCollector(filter, { time: 600000 });
this.reactionCollector.on('collect', (reaction, reactionCollector) => {
if(reaction.emoji.name === '➡️') {
if(this.index + 1 < result.length) {
this.index++;
var embed = this.makeEmbed(result[this.index].img);
this.message.edit({embed});
}
}
else if(reaction.emoji.name === '⬅️') {
if(this.index - 1 > -1) {
this.index--;
var embed = this.makeEmbed(result[this.index].img);
this.message.edit({embed});
}
}
reaction.remove(this.user);
});
});

Resources