Discord js blacklist - node.js

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

Related

Why "member.add.roles" doesnt work for me?

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

The parameter name '' has already been declared. Parameter names must be unique

I have here an API created in NodeJS. When I run the API, it works on the first time, but if run it again its give me an error The parameter name Username has already been declared. Parameter names must be unique at Request.input. I checked other threads on how to fix this thing. Some answers that it needs to be cleared, but I think there is no function in NodeJS mssql library that clears parameter.(correct me if I'm wrong)
My code:
const res = require("express/lib/response")
const {sql,request} = require("../config/connection")
module.exports = {
checkExist: (data,callBack) => {
if(data.key == process.env.KEY) {
var username = data.username
var firstname = data.firstname
var middlename = data.middlename
var lastname = data.lastname
if(username == "" || firstname == "" || middlename == "" || lastname == "") {
return callBack("Invalid Input")
}
else {
request.input('Username', sql.VarChar(50), username);
request.input('FirstName', sql.VarChar(50), firstname);
request.input('MiddleName', sql.VarChar(50), middlename);
request.input('LastName', sql.VarChar(50), lastname);
request.output('Result', sql.Int);
request.execute('sp_INS_User').then(function(recordsets, returnValue, affected) {
if(recordsets.output.Result == -100) {
return callBack("Player Exist with different Username")
}
else if(recordsets.output.Result == -4) {
return callBack("Something went wrong while processing your request, please try again later.")
}
else {
if(recordsets.output.Result == 1000) {
return callBack(null,recordsets)
}
}
// console.dir(err);
}).catch(function(err) {
//return callBack(err)
return callBack("Something went wrong while processing your request, please try again later.")
});
}
}
else {
return callBack("Invalid Access")
}
}
}
My code in : ../config/connection/
const sql = require("mssql")
require("dotenv").config()
const sqlConfig = {
user: process.env.USER,
password: process.env.PASS,
database: process.env.DB_MAIN,
server: process.env.HOST,
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
},
options: {
encrypt:false,
trustServerCertificate: true
}
}
const con = sql.connect(sqlConfig).then(function() {
console.log(`Database connection successful!`);
}).catch(function(err) {
console.log(`Database connection ${err}!`);
});
const request = new sql.Request();
module.exports = {
sql,request
}
This looks like an issue of reusing the request object so the second time this function gets called, you're using the same request object that was previously used the first time this function was called. As such, you're registering duplicate names with request.input().
Apparently, you will need a new copy of const request = new sql.Request(); each time you want to use it because the error message is telling you that you can't repeat statements like request.input('Username',...) over and over on the same request object. So, export a function to get a new request object rather than exporting just one pre-made object.
You can do that like this:
../config/connection/
const sql = require("mssql")
require("dotenv").config()
const sqlConfig = {
user: process.env.USER,
password: process.env.PASS,
database: process.env.DB_MAIN,
server: process.env.HOST,
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
},
options: {
encrypt:false,
trustServerCertificate: true
}
}
const con = sql.connect(sqlConfig).then(function() {
console.log(`Database connection successful!`);
}).catch(function(err) {
console.log(`Database connection ${err}!`);
});
const getRequest = function() { return new sql.Request(); };
module.exports = {
sql, getRequest
};
And, your other code:
const res = require("express/lib/response")
const { sql, getRequest } = require("../config/connection")
module.exports = {
checkExist: (data, callBack) => {
const request = getRequest();
if (data.key == process.env.CAMS_INPLAY_KEY) {
var username = data.username
var firstname = data.firstname
var middlename = data.middlename
var lastname = data.lastname
if (username == "" || firstname == "" || middlename == "" || lastname == "") {
return callBack("Invalid Input")
} else {
request.input('Username', sql.VarChar(50), username);
request.input('FirstName', sql.VarChar(50), firstname);
request.input('MiddleName', sql.VarChar(50), middlename);
request.input('LastName', sql.VarChar(50), lastname);
request.output('Result', sql.Int);
request.execute('sp_INS_User').then(function(recordsets, returnValue, affected) {
if (recordsets.output.Result == -100) {
return callBack("Player Exist with different Username")
} else if (recordsets.output.Result == -4) {
return callBack(
"Something went wrong while processing your request, please try again later."
)
} else {
if (recordsets.output.Result == 1000) {
return callBack(null, recordsets)
}
}
// console.dir(err);
}).catch(function(err) {
//return callBack(err)
return callBack(
"Something went wrong while processing your request, please try again later."
)
});
}
} else {
return callBack("Invalid Access")
}
}
}

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roleId' of undefined

I have a requirement that requires me to validate if a user is selecting a correct manager. The association between them is the group id each belongs to. A user can be associated to one group id and a manager can be associated to more than one group id. When allowing a user to select his manager, I need to validate if the user's group id exists in the manager's list of group ids. Here is the code i have implemented below but I get UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roleId' of undefined
My route file account.ts has the following codeblock
let promise = accountController.update(user);
promise.then(function(data) {
if (data.IsSuccessful == true)
{
result.IsSuccessful = true;
result.SuccessMessage = process.env.USER_UPDATED || "User changed";
return res.status(200).json(result);
}
else
{
result.IsSuccessful = false;
result.ReasonForFailure = data.ReasonForFailure;
res.status(200).json(result);
}
}).catch(function(err){
result.IsSuccessful = false;
result.ReasonForFailure = err.message;
res.status(200).json(result);
});
My controller file account.ts has the following code block for the update method
update = (account: Account) : Promise<Result<Account>> => {
var thisObj = this;
return new Promise<Result<Account>>(function (resolve, reject){
let result = new Result<Account>();
result.Data = account;
MongoClient.connect(config.database.uri, { useUnifiedTopology: true } , async function(err: any, db: any) {
if (err) {
// throw err;
result.IsSuccessful = false;
result.ReasonForFailure = err.message;
reject(result);
}
var dbo = db.db(config.database.name);
var newvalues = { $set:
{
name: account.name,
title: account.title,
organization: account.organization,
reportingTo: account.reportingTo,
workNumber: account.workNumber,
mobileNumber: account.mobileNumber,
allowNotification: account.allowNotification,
allowEmail: account.allowEmail,
groups: account.groups,
updatedDate: account.updatedDate,
isProfileSetupComplete: true,
photo:account.photo
}
};
let existingUser: any;
var query = {email:account.email};
var resultArray = await dbo.collection("users").find(query).toArray();
if (resultArray.length > 0) {
existingUser = resultArray[0];
} else {
db.close();
result.ReasonForFailure = process.env.INVALID_USER_ID || "Invalid User Id";
result.IsSuccessful = false;
reject(result);
}
console.log(existingUser);
if (existingUser.roleId == "1") { //roleId="1" means user
//validate manager id. reportingTo id must be a manager
var queryReporting = { _id: account.reportingTo };
let managerUser: any;
var resultManagerArray = await dbo.collection("users").find(queryReporting).toArray();
if (resultManagerArray.length > 0) {
console.log("managerUser in");//<--This is not printing in the console log
managerUser = resultManagerArray[0];
} else {
db.close();
result.ReasonForFailure = "Invalid reporting id.";// process.env.INVALID_USER_ID || "Invalid User Id";
result.IsSuccessful = false;
resolve(result);
}
//validate manager user
console.log("managerUser out");
console.log(managerUser);
if (managerUser.roleId !== "2"){//<--UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roleId' of undefined
result.IsSuccessful = false;
result.ReasonForFailure = "Reporting to must be a Manager";
reject(result);
}
//manager and user must be associated with same group
if (!managerUser.groups.includes(account.groups)) {
result.IsSuccessful = false;
result.ReasonForFailure = "Incorrect Manager selection. Employee must be associated with a group the manager is associated with."
reject(result);
}
}
dbo.collection("users").updateOne(query, newvalues, function(err: any, resultSet: any) {
if (err) {
//throw err;
db.close();
result.IsSuccessful = false;
result.ReasonForFailure = err.message;
reject(result);
} else {
result.SuccessMessage = oldImage;
result.IsSuccessful = true;
db.close();
resolve(result);
}
});
});
});
}
managerUser.roleId !== "2" in the above code is the place where I get the UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roleId' of undefined
I have put await in first call to the find query and it worked as expected waiting for the call to finish but the next await has no effect it seems. The execution didn't wait for the call to finish.
Can you please assist what I'm missing here?
Thanks,
Hemant.
You're probably missing return statements after all the resolve(result);/reject(result); calls. Unlike return and throw, they're ordinary function calls and do not terminate the execution of the function.
Additionally you shouldn't pass an async function as a callback to a function that doesn't handle the returned promise. You should only promisify the connect call alone, wait for its result, and continue the rest of your function after await or in a then callback to ensure errors are handled appropriately.
update = async (account: Account) : Promise<Result<Account>> => {
let result = new Result<Account>();
result.Data = account;
try {
const db = await MongoClient.connect(config.database.uri, { useUnifiedTopology: true });
try {
const dbo = db.db(config.database.name);
const newvalues = {
$set: {
name: account.name,
title: account.title,
organization: account.organization,
reportingTo: account.reportingTo,
workNumber: account.workNumber,
mobileNumber: account.mobileNumber,
allowNotification: account.allowNotification,
allowEmail: account.allowEmail,
groups: account.groups,
updatedDate: account.updatedDate,
isProfileSetupComplete: true,
photo:account.photo
}
};
var resultArray = await dbo.collection("users").find({email: account.email}).toArray();
if (resultArray.length == 0) {
result.ReasonForFailure = process.env.INVALID_USER_ID || "Invalid User Id";
result.IsSuccessful = false;
return result;
}
const existingUser = resultArray[0];
console.log(existingUser);
if (existingUser.roleId == "1") {
var resultManagerArray = await dbo.collection("users").find({ _id: account.reportingTo }).toArray();
if (resultManagerArray.length == 0) {
result.ReasonForFailure = "Invalid reporting id.";// process.env.INVALID_USER_ID || "Invalid User Id";
result.IsSuccessful = false;
return result;
}
console.log("managerUser in");
const managerUser = resultManagerArray[0];
console.log("managerUser out");
console.log(managerUser);
if (managerUser.roleId !== "2") {
result.IsSuccessful = false;
result.ReasonForFailure = "Reporting to must be a Manager";
return result;
}
//manager and user must be associated with same group
if (!managerUser.groups.includes(account.groups)) {
result.IsSuccessful = false;
result.ReasonForFailure = "Incorrect Manager selection. Employee must be associated with a group the manager is associated with."
return result;
}
}
const resultSet = await dbo.collection("users").updateOne(query, newvalues);
result.SuccessMessage = oldImage;
result.IsSuccessful = true;
return result;
} finally {
db.close()
}
} catch(err) {
result.IsSuccessful = false;
result.ReasonForFailure = err.message;
return result;
}
};

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

display 2 two table records in nodejs

I have tow MongoDB collection.
1) users
2) reviews.
at the first collection, I have stored username and id. and 2nd table I have stored user_id and comments and star rating.
I want to display on listing page users and his reviews.
I have written below code but it is not working.
var getTopSellers = function () {
var defer = Q.defer();
User.find({ isRegistered: true }).sort({ updatedAt: -1 }).limit(10).exec(function (err, sellers) {
if (!err) {
if (sellers && sellers.length > 0) {
for (var i = 0; i < sellers.length; i++) {
var sellerDetails = {};
var tempObj = {};
try {
tempObj.reviews = getreviews(sellers[i]._id);
sellerArr.push(tempObj);
} catch (e) {
// console.log("catch error:-", e);
}
}
out = U.getJson(C.SUCCESS_CODE, C.SUCCESS, sellerArr);
defer.resolve(out);
} else {
out = U.getJson(C.KNOWN_ERROR_CODE, 'No data found');
defer.reject(out);
}
} else {
console.log("Error:-", err);
out = U.getJson(C.ERROR_CODE, C.INETRNAL_SERVER_ERROR, b, err);
defer.reject(out);
}
})
return defer.promise;
};
var getreviews = function (user_id) {
var defer = Q.defer();
Review.find({ user_type: user_id }).sort({ updatedAt: -1 }).limit(10).exec(function (err, reviews) {
if (!err) {
if (reviews && reviews.length > 0) {
out = U.getJson(C.SUCCESS_CODE, C.SUCCESS, reviews);
defer.resolve(out);
} else {
out = U.getJson(C.KNOWN_ERROR_CODE, 'No data found');
defer.reject(out);
}
} else {
console.log("Error:-", err);
out = U.getJson(C.ERROR_CODE, C.INETRNAL_SERVER_ERROR, b, err);
defer.reject(out);
}
})
return defer.promise;
};
Please suggest

Resources