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

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

Related

Chaining async/await calls in react

I have an application that can add NYT bestseller items to a database. Currently, users can add a bestseller to the db even if it already exists in the db. I want to be able to chain API calls such that if a user tries to save an item, the application first checks if that item is in the db, and only if it isn't proceed to save the item.
Here is my existing code:
const [currentInDb, setCurrentInDb] = useState(false);
interface bookInt {
title: string;
author: string;
}
const handleDbCheck = async(book: bookInt) => {
setCurrentInDb(false);
let targetObj = {
title: book.title,
author: book.author,
list: selectedCategory
}
try {
let url = baseURL + "/read-all";
axios.get(url).then((res) => {
for (let i = 0; i < res.data.length; i++){
let current = res.data[i]
if (current.title === targetObj.title && current.list === targetObj.list){
setCurrentInDb(true);
}
}
});
} catch (error) {
console.log(error);
}
}
const handleSaveBook = async (book: bookInt) => {
if (currentInDb){
console.log('handleSaveBook stopped early because item in db');
return;
}
try {
let newObj = {
title: book.title,
author: book.author,
list: selectedCategory,
};
let postURL = baseURL + "/create";
axios.post(postURL, newObj).then((response) => {
console.log('new item added');
});
} catch (error) {
console.log("error: ", error);
}
};
const handleCheckAndSave = async(book: bookInt): Promise<any> => {
await handleDbCheck(book)
.then(res => handleSaveBook(book))
}
Oddly, upon page reload, the first time I try to add an item to the db that is already there, I CAN add a duplicate. Then if I try to add it again, it correctly does not allow me to add it. Ideas?
There is no need to use .then in the async function. you can simply use await & chain your asynchornous requests.
const [currentInDb, setCurrentInDb] = useState(false);
interface bookInt {
title: string;
author: string;
}
const handleDbCheck = async(book: bookInt) => {
setCurrentInDb(false);
let targetObj = {
title: book.title,
author: book.author,
list: selectedCategory
}
try {
let url = baseURL + "/read-all";
const res = await axios.get(url)
for (let i = 0; i < res.data.length; i++){
let current = res.data[i]
if (current.title === targetObj.title && current.list === targetObj.list){
setCurrentInDb(true);
}
}
} catch (error) {
console.log(error);
}
}
const handleSaveBook = async (book: bookInt) => {
if (currentInDb){
console.log('handleSaveBook stopped early because item in db');
return;
}
try {
let newObj = {
title: book.title,
author: book.author,
list: selectedCategory,
};
let postURL = baseURL + "/create";
const response = await axios.post(postURL, newObj)
console.log(response)
} catch (error) {
console.log("error: ", error);
}
};
const handleCheckAndSave = async(book: bookInt): Promise<any> => {
await handleDbCheck(book)
await handleSaveBook(book)
}

Unable to add array to firebase-firestore in reactjs?

I am trying to send a list of arrays to Firestore using a variable called array_list but when I check my firebase console the array is present but the value inside of it is empty.
let array_list = [];
let user_id = localStorage.getItem("userId");
function add_data() {
let i = 0;
for(i;i<10;i++){
array_list.push(i);
}
}
add_data()
let db = firebase.firestore();
if (user_id !== null) {
var doc = db.collection("users").doc(user_id);
}
const sendHistData = () => {
console.log("Creating Database...");
doc
.set({
browsingHistory: array_list,
})
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.log(error);
});
};
if(user_id!==null){
add_data();
sendHistData();
}
Here is the link to the full code
Here is the screenshot
The var "doc" seems to be undefined in your sendHistData function. Try refactoring the function:
let db = firebase.firestore();
const sendHistData = () => {
// if (!user_id) return null // user not logged in
const db = firebase.firestore().collection("users").doc(user_id)
console.log("Creating Database...");
doc
.set({
browsingHistory: array_list,
})
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.log(error);
});
};
Also you are checking if user_id is null or not before calling the function so verifying that again inside of the function is redundant.

this discord.js event doesn't work needs adaptation

I was wanting to adapt this code to work within my discord.js bot project.
As an event, it starts as soon as the bot comes online, but this way it isn't coming online, not even a console.log returns a log about that event.
this code below would have to run inside this event code.
and all my events start from a:
client.on("ready", () => { // event of my project starts like this
// code
});
module.exports = class {
constructor(client) {
this.client = client;
}
async run() {
this.client.on("ready", async () => {
await this.VipFilter();
});
}
async VipFilter() {
setInterval(async () => {
const list_vips = await require("mongoose")
.connection.collection("users")
.find({ "vip.date": { $gt: 1 } })
.toArray();
const filter_members = Object.entries(list_vips).filter(
([, x]) => x.vip.date <= Date.now()
);
const VIPS = filter_members.map(([, x]) => x.idU);
await this.VipRemove(VIPS);
}, 60000);
}
async VipRemove(VIPS) {
let totalPessoas = VIPS.length;
let size = 0;
const interval = setInterval(async () => {
if (totalPessoas <= 0) clearInterval(interval);
else {
let members = VIPS[size++];
const user = await this.client.users.fetch(members);
await this.client.database.users.findOneAndUpdate(
{ idU: user.id },
{ $set: { "vip.date": 0, "vip.hasVip": false } }
);
}
totalPessoas--;
}, 5000);
}
}; ```

'useEffect', which lacks return-type annotation, implicitly has an 'any' return type.ts(7010)

useEffect(() => {
const cont = async () => {
const { status } = await Contacts.requestPermissionsAsync();
if (status === 'granted') {
const { data } = await Contacts.getContactsAsync({
fields: [Contacts.Fields.Emails],
});
if (data.length > 0) {
const contact = data[0];
console.log(contact);
}
}
}();
}, []);
please help im relatively new to typescript and im not sure why this error is occuring
You invoke the function like this:
(() => {
const { status } = await Contacts.requestPermissionsAsync();
if (status === 'granted') {
const { data } = await Contacts.getContactsAsync({
fields: [Contacts.Fields.Emails],
});
if (data.length > 0) {
const contact = data[0];
console.log(contact);
}
}
})();

Nested async function with array map, empy response

The problem is that the variable arrV is empty when sent to res. I've tried to insert .then() function after the first async or calling return new Promise after (async () => { but the result is the same. I will paste main and other functions:
router.get('/telegram/chats', (req,res,next) => {
let arrV = [];
(async () => {
let q = await Telegram.getChats();
Object.keys(q).map(async (k, v) => {
let search = await MTel.getChatById(q[k].id,(r) => {
if(!r){
MTel.insertChat([q[k].id,q[k].title,q[k].last_message,0], (p) => {
arrV.push(p);
})
}
});
});
})();
res.send(arrV);
});
Telegram.getChats():
async function getChats(options) {
let ret = [];
let ok = await client.getChats();
for(var k in ok["chat_ids"]){
let ch = await client.getChat(ok["chat_ids"][k]);
ret.push({id: ch.id, title: ch.title, last_message: ch["last_message"].id});
}
return ret;
}
Mtel.getChatById() and Mtel.insertChat():
const getChatById = (id,callback) => {
let qq = db.select(table,{id_chat: id},"LIMIT 0,1", (r) => {
return callback(r);
})
}
const insertChat = (obj,callback) => {
let qq = db.insert(table,["id_chat","title","last_message","active"],[obj], (r) => {
return callback(r);
})
}
Thank you.

Resources