How to compare member id and bots id on the server - discord.js

I get the ids of all bots on the server but I can't compare them with the user id
How do I do this?
-- Comment --
I know that I can't compare the user id with the id of all bots just by writing this, but I don't know how to compare the user id with each id in the list
-- Part of the code --
module.exports = {
data: new SlashCommandBuilder()
.setName("pay")
.setDescription("🥁│Дать деньги другому пользователю")
.addNumberOption((option) => option.setName("amount").setDescription("🧩│Кол-во денег которое хочешь перевести").setRequired(true))
.addUserOption((option) => option.setName("target").setDescription("🎯│Выбрать кому перевести деньги").setRequired(true))
.setDefaultMemberPermissions(PermissionFlagsBits.SendMessages),
async execute(interaction) {
const target = interaction.options.getUser("target")
const member = await interaction.guild.members.cache.get(target.id)
const bots = await interaction.guild.members.cache.filter(m => m.user.bot).map(i => i.user.id)
if (!member) {
await interaction.reply({ content: "**🧩│The user is not identified or he has left the server**" }).then(() => {
setTimeout(async () => {
await interaction.deleteReply().catch((error) => {
if (error.code !== RESTJSONErrorCodes.UnknownMessage) {
return
} else {
return
}
})
}, ms("3s"))
})
} else if (member.user.id == interaction.user.id) {
await interaction.reply({ content: "**🧩│You can't transfer money to yourself**" }).then(() => {
setTimeout(async () => {
await interaction.deleteReply().catch((error) => {
if (error.code !== RESTJSONErrorCodes.UnknownMessage) {
return
} else {
return
}
})
}, ms("3s"))
})
} else if (member.user.id == bots || member.user.id == interaction.guild.members.me.id) {
await interaction.reply({ content: "**🧩│You can't transfer money to a bot**" }).then(() => {
setTimeout(async () => {
await interaction.deleteReply().catch((error) => {
if (error.code !== RESTJSONErrorCodes.UnknownMessage) {
return;
} else {
return;
}
})
}, ms("3s"))
})
}
}
}

There is a .bot property on the User Class which you can use like this:
if(member.user.bot) {
// Do something if bot
}
Using this, will be easier to check whether the user is a bot or not.

Related

Asynchronous Function In NextAuth Completing Before Value Returned

On signin, I'm attempting to query FirestoreDB and then return the user data or null.
I'm trying to do this with async await, but the dependent code runs before the db query has been completed. This can be seen when "CORRECT," (right credentials) is console logged after the empty user details (not complete).
Thanks,
This is my code:
let data = await db.collection('users').where("email", "==", email).get().then(querySnapshot => {
console.log("SOMETHING")
let arr = []
querySnapshot.docs.map(doc => arr.push(doc.data()))
console.log(arr)
// console.log(sc.decrypt(arr[0].password))
if (arr[0].email == email) {
bcrypt.compare(password, arr[0].password, (err, match) => {
if (match) {
console.log("CORRECT")
return arr[0]
} else {
if (err) {
console.log(err)
}
console.log("INCORRECT")
return null
}
})
}
})
console.log("DATA " + data)
return data ? data : null
An hour of searching, but 2 minutes after I post I figure it out.
Here is the working code for anyone in the same boat:
let data = new Promise((resolve, reject) => {
db.collection('users').where("email", "==", email).get().then(querySnapshot => {
console.log("SOMETHING")
let arr = []
querySnapshot.docs.map(doc => arr.push(doc.data()))
console.log(arr)
// console.log(sc.decrypt(arr[0].password))
if (arr[0].email == email) {
bcrypt.compare(password, arr[0].password, (err, match) => {
if (match) {
console.log("CORRECT")
resolve(arr[0])
} else {
if (err) {
console.log(err)
}
console.log("INCORRECT")
resolve(null)
}
})
}
})
})
Promise.all([data]).then(async () => {
console.log(await data)
})
return data ? data : null

How to send a notification instead of a message when user is offline using socket.io

So whenever another user is offline and an online user tries to send a message, it returns an error. The error is caused because it didn't find a socket where the user is in, but I can console.log something from the error response, since I put it in if/else block. So i was wondering how could I send a response to the client and push a notification for the user who is offline. The explanation is probably confusing, so here is the code:
index.js(socket):
const io = require('socket.io')(8900, {
cors: {
origin: 'http://localhost:3000',
},
});
let users = [];
const addUser = (userId, socketId) => {
!users.some((user) => user.userId === userId) &&
users.push({ userId, socketId });
};
const removeUser = (socketId) => {
users = users.filter((user) => user.socketId !== socketId);
};
const getUser = (userId) => {
return foundUser = users.find((user) => user.userId === userId)
};
io.on('connection', (socket) => {
//when ceonnect
console.log('a user connected.');
//take userId and socketId from user
socket.on('addUser', (userId) => {
addUser(userId, socket.id);
io.emit('getUsers', users);
});
//send and get message
socket.on('sendMessage', ({ senderId, recieverId, text }) => {
const user = getUser(recieverId);
console.log('RECIEVERRRR', user);
if (user) {
io.to(user.socketId).emit('getMessage', {
senderId,
text,
});
} else {
// IMPORTANT: This is where I can console.log the error, but can't figure out how to send the response to the client
}
});
//when disconnect
socket.on('disconnect', () => {
console.log('a user disconnected!');
removeUser(socket.id);
io.emit('getUsers', users);
});
});
dashboard.js (I cut out most of the code, but this is where i'm sending request to socket):
const handleSubmit = async (e) => {
e.preventDefault();
const message = {
sender: user._id,
text: newMessage,
conversationId: currentChat._id,
};
const recieverId = currentChat.members.find(
(member) => member !== user._id
);
console.log('REC from FRONT END', recieverId);
socket.current.emit('sendMessage', {
senderId: user._id,
recieverId,
text: newMessage,
});
try {
const { data } = await axios.post('/api/messages/addMessage', message);
setMessages([...messages, data]);
setNewMessage('');
} catch (err) {
console.log(err);
}
};
Any help would be appreciated. Thanks.
You can emit a new event sendMessageFailed:
//send and get message
socket.on('sendMessage', ({ senderId, recieverId, text }) => {
const user = getUser(recieverId);
console.log('RECIEVERRRR', user);
if (user) {
io.to(user.socketId).emit('getMessage', {
senderId,
text,
});
} else {
io.to(user.socketId).emit('sendMessageFailed', "Your friend is offline");
}
});
At the client side listen to the event:
socket.current.on('sendMessageFailed', (err) => {
//Sending message has failed!
});

Discord.js code isn't working. I should give a the member a role but it says add is undefined

Here is my code:
let userlist = [];
let reactedlist = [];
client.on('message', msg=> {
const filter = () => {
return true
};
const collector = msg.createReactionCollector(filter, { time: 86400000 });
collector.on('collect', (a,reaction) => {
console.log(reaction.id);
if(!userlist.includes(reaction.id) && !reactedlist.includes(reaction.id)){
userlist.push(reaction.id)
}
console.log(userlist);
userlist.forEach(id => {
const userReactions = msg.reactions.cache.filter(reaction => reaction.users.cache.has(id));
try {
let duo = '';
for (const reaction of userReactions.values()) {
duo+=reaction.emoji.id;
}
if(duo.includes('854754738956664901') && duo.includes('854754766609055764')){
userlist.shift();
const member = client.users.fetch(id);
let role = msg.guild.roles.cache.find(i => i.id === '854756696965644319')
member.roles.add(role);
if(!reactedlist.includes(id)){
reactedlist += id;
}
}
} catch (error) {
console.error(error);
}
});
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} items`);
});
});
client.login('');
Users cannot have roles added to them.
To get the GuildMember, you should be going into the guild and fetching from the GuildMemberManager.
const member = await msg.guild.members.fetch(id);
member.roles.add(role);

action is triggering a series of remote methods and returning rejected

I have an action that is getting dispatched that is triggering multiple remote methods and returning'TALK_SUBMIT_REJECTED' The strange thing however, is that all of the data that I am getting is still returned and updating the store as expected.
I am however getting these two errors in the process:
xhr.js:178 POST http://localhost:3000/api/talks/talkSubmit 500
(Internal Server Error)
createError.js:16 Uncaught (in promise) Error: Request failed with
status code 500
at e.exports (createError.js:16)
at e.exports (settle.js:18)
at XMLHttpRequest.m.(:3000/anonymous function)
(http://localhost:3000/bundle.js:6:2169)
I have thrown in two dozen console.logs recording all of the data I am sending and receiving and everything returning as expected.
I apologize in advance for the long post but I have been struggling with this bug for a while.
to give a brief summery of what my code is doing:
I have a form that upon submission, triggers an action that starts a chain of remote methods.
This is the first method:
function talkSubmit(speakerInfo, talkInfo, date) {
return new Promise((resolve, reject) => {
const { Talk, Speaker, Event } = app.models;
return Speaker.create(speakerInfo)
.then(response => {
let speakerId = response.id
return getMeetups()
.then(meetups => {
const index = meetups.findIndex((item) =>
item.date == date);
let name = meetups[index].name;
let details = meetups[index].description;
let meetupId = meetups[index].meetupId;
if (index === -1)
return reject(new Error('NO meetup with that
date found!'));
return Event.findOrCreate({ date, name, details,
meetupId })
.then(event => {
let eventId = event[0].id
return Talk.create({ ...talkInfo,
speakerId, eventId })
.then(talk => resolve(talk))
.catch(err => console.log(err))
})
.catch(err => reject(err))
})
.catch(err => reject(err))
})
.catch(err => reject(err))
})
}
module.exports = { talkSubmit };
//this is the get meetups function that is called by talkSubmit
function getMeetups() {
return new Promise((resolve, reject) => {
let currentDate = new Date();
currentDate.setMonth(currentDate.getMonth() + 3);
const date ='${ currentDate.getFullYear() } -${
currentDate.getMonth() } -${
currentDate.
getDay()
} ';
axios.get(`https://api.meetup.com/sandiegojs/events?
no_later_than = ${ date } `)
return resolve(response.data.map(event => ({
meetupId: event.id,
name: event.name,
date: event.local_date,
time: event.local_time,
link: event.link,
description: event.description,
})))
.catch(err => reject(new Error('getMeetups failed to get SDJS
meetups')))
})
}
module.exports = { getMeetups };
//This is the after remote method that is triggered when talkSubmit is
//completed.
Talk.afterRemote('talkSubmit', function (ctx, modelInstance, next) {
const speakerId = ctx.result.speakerId;
const eventId = ctx.result.eventId;
const approved = false;
const pending = true;
formatTalkForEmail(speakerId, eventId)
.then((response) => {
const speakerName = response.speakerName;
const speakerEmail = response.speakerEmail;
const meetupTitle = response.meetupTitle;
const meetupDate = response.meetupDate;
sendEmailToSpeaker(process.env.ADMIN_EMAIL, approved,
pending, speakerEmail, speakerName, meetupTitle, meetupDate)
.then(() => next())
.catch(err => next(err));
})
.catch(err => next(err));
});
//this is the formatTalkForEmail method called in the remote method
function formatTalkForEmail(speakerId, eventId) {
return new Promise((resolve, reject) => {
if (speakerId == undefined) {
return reject(new Error('speakerId is undefined'));
}
if (eventId == undefined) {
return reject(new Error('eventId is undefined'));
}
const { Speaker, Event } = app.models;
Speaker.findById(speakerId)
.then(speaker => {
const speakerName = speaker.speakerName;
const speakerEmail = speaker.speakerEmail
return Event.findById(eventId)
.then(selectedEvent => {
const meetupTitle = selectedEvent.name;
const meetupDate = selectedEvent.date;
resolve({
speakerName,
speakerEmail,
meetupTitle,
meetupDate
})
})
.catch(err => reject( err ))
})
.catch(err => reject(err))
})
}
module.exports = { formatTalkForEmail };
//and finally this is the sendEmailToSpeaker method:
function sendEmailToSpeaker(adminEmail, approved, pending,
speakerEmail, speakerName, meetupTitle, meetupDate) {
return new Promise((resolve, reject) => {
let emailContent;
if (approved && !pending) {
emailContent = `Congratulations! Your request to speak at
${ meetupTitle } on ${ meetupDate } has been approved.`
}
if (!approved && !pending) {
emailContent = `We're sorry your request to speak at
${ meetupTitle } on ${ meetupDate } has been denied.`
}
if (pending) {
emailContent = `Thank you for signing up to speak
${ meetupTitle } on ${ meetupDate }.You will be notified as soon as
a
SDJS admin reviews your request.`
sendEmailToAdmin(adminEmail, meetupDate, meetupTitle,
speakerEmail, speakerName)
.catch(err => console.log(err));
}
const email = {
to: speakerEmail,
from: adminEmail,
subject: 'SDJS Meetup Speaker Request',
templateId: process.env.ADMIN_SPEAKER_EMAIL_TEMPLATE,
dynamic_template_data: {
emailContent: emailContent,
sdjsBtn: false,
title: 'SDJS Meetup Speaker Request'
}
}
sgMail.send(email)
.then(() => resolve({ email }))
.catch(err => {
console.log(err);
reject(err);
});
})
}
in conclusion I have no clue what part of talkSubmit is throwing those two errors and yet both emails are getting automatically sent and the store is updating with all the proper data despite the initial action creator returning rejected. I appreciate any help anyone can offer.
Ok so I think the main problem is here:
axios.get(`https://api.meetup.com/sandiegojs/events?no_later_than = ${ date } `)
return resolve(response.data.map(event => ({
meetupId: event.id,
name: event.name,
date: event.local_date,
time: event.local_time,
link: event.link,
description: event.description,
})))
it should look like that (I recommend to extract mapping method):
axios.get(`https://api.meetup.com/sandiegojs/events?no_later_than = ${ date} `)
.then( response => resolve(response.data.map(event => ({
meetupId: event.id,
name: event.name,
date: event.local_date,
time: event.local_time,
link: event.link,
description: event.description,
}))))
.catch(err => reject(new Error('getMeetups failed to get SDJS meetups')))
and a few words about Promises. You can chain them like that:
method()
.then(method2())
.then(method3())
.then(method4())
...
.catch(err =>...
also I don't understand why you wrap content of method in return new Promise((resolve, reject) => { I think is not needed in your case
so you can change talkSubmit method to something like that (this is just a draft, I recommend to extract methods from then blocks)
function talkSubmit(speakerInfo, talkInfo, date) {
const { Talk, Speaker, Event } = app.models;
return getMeetups()
.then(meetups => {
const index = meetups.findIndex((item) => item.date == date);
let name = meetups[index].name;
let details = meetups[index].description;
let meetupId = meetups[index].meetupId;
if (index === -1)
return reject(new Error('NO meetup with that date found!'));
return Promise.all([
Event.findOrCreate({
date, name, details,
meetupId
}),
Speaker.create(speakerInfo)])
})
.then(([event, speaker]) => {
let eventId = event[0].id
let speakerId = speaker.id
return Talk.create({
...talkInfo,
speakerId, eventId
})
})
}

How to post with Axios in React?

This my first time in React and Axios. I have a login form and sign up form and don't have any database. I want any mock API to simulate a login and sign up which provides a token in the response, in order to save it in a local storage in order to keep the user logged in. Also how do I prevent the user to go the home page (login/logout screen). When they type for example www.blabla.com, I want, if the token exists they still in the app, otherwise the token will be erased.
I tried to fetch data from mock API by axios.get(), it worked but it still static
componentDidMount() { // this For Testing Until Now
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => {
console.log(res);
this.setState({
users: res.data
}, () => {
console.log('state', this.state.users)
})
});
}
I want to communicate with API that allows my to fetch data and post data to it. This is my login function
handleLogin(e) {
e.preventDefault();
const email = e.target.elements.email.value;
const password = e.target.elements.password.value;
let userData = {};
if(validator.isEmpty(email) || validator.isEmpty(password) || !validator.isEmail(email)) {
this.setState({
error: 'You Have To Complete Your Data Correctly'
}, () => {
console.log('failed');
});
} else {
userData = {email, password};
const { users } = this.state;
if(users.find(item => item.email === userData.email)) {
const index = users.findIndex(item => item.email === userData.email);
this.props.history.push(`./create/${users[index].username}`);
}
}
}
and this is my signup function
handleAddNewUser(e) {
e.preventDefault();
const name = e.target.elements.userName.value.toLowerCase().trim();
const email = e.target.elements.userEmail.value.toLowerCase().trim();
const password = e.target.elements.pass.value;
const repassword = e.target.elements.re_pass.value;
let userInfo = {};
const { users } = this.state;
console.log(name, email);
if (validator.isEmpty(name) || validator.isEmpty(email) ||
validator.isEmpty(password) || validator.isEmpty(repassword) ||
!validator.isEmail(email) || !validator.equals(password, repassword)) {
this.setState({
error: 'You Have to enter valid data, Make Sure That The Fields are Complete',
open: true
});
} else {
userInfo = { name, email, password };
if (
users.find(item => item.name === userInfo.name) ||
users.find(item => item.email === userInfo.email)
) {
this.setState({
error: 'This username or email is used',
open: true
});
} else {
this.setState({
users: this.state.users.concat(userInfo),
success: true
}, () => {
// this.props.history.push(`./create/${userInfo.name}`);
// console.log(users)
});
console.log(users)
}
}
}
You can use axios.post() to send post request.
// POST
const userData = {
email: 'demouser#gmail.com',
username: 'demouser',
password: '1a2b3c4d5e' //This should be encoded
}
axios.post('https://example.com/createUser', userData)
.then(res => {
responseData = res.data
if (responseData.status == 'success') {
const user = responseData.user
...
} else {
alert('Something went wrong while creating account')
}
})

Resources