Problem with library react-native-calendar-strip - javascript

I use the react-native-calendar-strip library. The calendar is displayed but after the date it gets a error.
TEST 4 1675262133340 ERROR ReferenceError: Can't find variable:
setState
Earlier it worked to me, I don't know what I did that it stopped working for me. I am asking for a clue where I did wrong :(
function TermeScreen({ route, navigation }) {
const { id, title } = route.params;
const [selectedDate, setSelectedDate] = useState(new Date());
useEffect(() => {getEmployee()},[])
const hour = () => {
axios.get(`${URL_TERM}/hours`)
.then((response) => {
console.log(response.data)
setHours(response.data)})
.catch(e=> {
console.error(`Get hours error ${e}`);
});
}
const getEmployee = () => {
axios.get(`${URL_TERM}/employee`)
.then((response) => {
console.log(response.data)
setEmployee(response.data)})
.catch(e=> {
console.error(`Get employee error ${e}`);
});
}
moment.locale('pl', momentPL);
let startDate = moment() // today
// Create a week's worth of custom date styles and marked dates.
let customDatesStyles = [];
let markedDates = [];
for (let i = 0; i < 7; i++) {
let date = startDate.clone().add(i, 'days');
const services = {
id: id,
title: title
}
customDatesStyles.push({
startDate: date, // Single date since no endDate provided
dateNameStyle: { color: 'white' },
dateNumberStyle: { color: 'white' },
highlightDateNameStyle: { color: 'white' },
highlightDateNumberStyle: { color: 'white' },
// Random color...
// dateContainerStyle: { backgroundColor: `#${(`#00000${(Math.random() * (1 << 24) | 0).toString(16)}`).slice(-6)}` },
},useEffect(() => {hour()},[]));
let dots = [];
let lines = [];
if (i % 2) {
lines.push({
color: 'white',
selectedColor: 'orange',
});
}
else {
dots.push({
color: 'white',
selectedColor: 'yellow',
});
}
markedDates.push({
date,
dots,
lines
});
state = {
selectedDate: undefined,
customDatesStyles,
markedDates,
startDate,
};
setSelectedDateNextWeek = date => {
console.log("TEST 1");
const selectedDate = moment(state.selectedDate).add(1, 'week');
const formattedDate = selectedDate.format('YYYY-MM-DD');
this.setState({ selectedDate, formattedDate });
}
setSelectedDatePrevWeek = date => {
console.log("TEST 2");
const selectedDate = moment(state.selectedDate).subtract(1, 'week');
const formattedDate = selectedDate.format('YYYY-MM-DD');
this.setState({ selectedDate, formattedDate });
}
datesBlacklistFunc = date => {
console.log("TEST 3");
return date.isoWeekday() === 6; // disable Saturdays
}
onDateSelected = selectedDate => {
// console.log("TEST 4 " + selectedDate.format('YYYY-MM-DD'));
console.log("TEST 4 " + selectedDate)
useEffect(() => {hour()},[]);
setState({ selectedDate });
setState({ formattedDate: selectedDate.format('YYYY-MM-DD') });
}
}
}

Related

date copy stops the loop statement to function as intended

What i am trying to do is to display available rooms which are in data
i map the rooms using data.map , check if one is available between a given ( checkin and checkout date ) using availdata[p.roomId][date].i==0 , if not it will display the available room .
the code works fine but as soon as it finds an available room it stops (which means it stops at the else statement ) and won't look for the rest of the rooms .
Any suggestions ?
using break ; doesn't have anything to do with the problem i am facing .
import React,{useState,useEffect} from 'react';
import HotelCards from './HotelCards';
import styles from '../styles/Options/Options.module.css';
import {Checkkout as checkkout} from "./Hero";
import {Checkkin as checkkin} from "./Hero";
import {format} from "date-fns";
let HC=[];
let prices =[];
let notavailableat="";
let rowss=[];
export default function Options({selectedGuest}) {
const [availdata, setavailData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [isLoading2, setIsLoading2] = useState(false);
const [data, setData] = useState([]);
// request Headers
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
};
const requestOptions2 = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
};
//Get the rooms info along with the ID
const fetchData = () => {
fetch('http://localhost:3001/api/rooms', requestOptions)
.then(response => response.json())
.then((result) =>{
console.log("roooms"+result)
setData(result.rooms)
setIsLoading2(true);
}
)
.catch((err) => console.log("error"));
};
useEffect(() => {
fetchData();
}, []);
//get the i and p variables
function fetchData1() {
fetch('http://localhost:3001/api/availability', requestOptions2)
.then(response => response.json())
.then((result) =>{
setavailData(result.availability[0])
console.log('ooooooooooh'+result.availability[0][7264])
setIsLoading(true);
}
)
.catch((err) => console.log("error"));
}
useEffect(() => {
fetchData1();
}, []);
prices.length=0;
var strToDatein = new Date(checkkin)
var strToDateout = new Date(checkkout)
let trys = 0;
data.map((p) =>{
if (isLoading && isLoading2 ){
for (var day = strToDatein; day < strToDateout; day.setDate(day.getDate() + 1)) {
HC.length=0;
console.log(day + "dekhel for");
var diplaydate = format(day,"dd MMM ");
var date = format(day, 'yyyyMMdd');
if (availdata[p.roomId][date].i==0){
rowss.push(<p key={availdata[p.roomId][date]}> not available at {diplaydate} </p>);
notavailableat="not available at "+diplaydate;
console.log(+p.roomId+"not available at "+diplaydate)
break;
}
else
{console.log("dateeee"+ date);
rowss.length=0;
prices.length=0;
prices.push(availdata[p.roomId][date].p1);
var total_price = 0;
if(prices.length!==0){
for (var i=0;i<=prices.length-1;i++){
total_price+=parseFloat(prices[i]);
}
}
console.log("room:"+p.roomId+"price?"+availdata[p.roomId][date].p1)
HC.push(<div key={p.roomId}>
<HotelCards
idroom={p.roomId}
title={p.roomName.toUpperCase()}
status={true}
price={total_price}
img={p.pictures[0].url}
avail={1111}
rows={rowss}
guest={selectedGuest}
/></div>)
}}
}
})
return (
<div className={`${styles.containers}`}>
{HC}
</div>
);
}
The problem in your code is this assignment in the for loop:
var day = strToDatein;
Dates are objects and objects are not copied. The references are copied. day and strToDatein contain references to the same object. day.setDate(day.getDate() + 1) modifies strToDatein. After the first room was found, strToDatein < strToDateout returns false and the for loop is skipped for all other rooms.
You can fix your problem with a real copy of the Date object in the for loop:
const data = [{
roomId: 0,
roomName: '0'
}, {
roomId: 1,
roomName: '1'
}, {
roomId: 2,
roomName: '2'
}];
const isLoading = true;
const isLoading2 = true;
const strToDatein = new Date(2022, 0, 1);
const strToDateout = new Date(2022, 0, 3);
const HC = [];
const availdata = [{
"20220101": {
i: 0,
p1: 100
}
}, {
"20220101": {
i: 2,
p1: 100
},
"20220102": {
i: 2,
p1: 100
},
"20220103": {
i: 2,
p1: 100
}
}, {
"20220101": {
i: 0,
p1: 100
}
}];
const rowss = [];
const prices = [];
function format(date) {
return `${date.getFullYear()}${`${date.getMonth()+1}`.padStart(2, 0)}${`${date.getDate()}`.padStart(2, 0)}`;
}
data.forEach((p) => {
if (isLoading && isLoading2) {
for (var day = new Date(strToDatein); day < strToDateout; day.setDate(day.getDate() + 1)) {
console.log(day + "dekhel for");
var diplaydate = format(day, "dd MMM ");
var date = format(day, 'yyyyMMdd');
if (availdata[p.roomId][date].i == 0) {
rowss.push(`<p key = {
availdata[p.roomId][date]
}> not available at {
diplaydate
}</p>`);
notavailableat = "not available at " + diplaydate;
console.log(+p.roomId + "not available at " + diplaydate)
break;
} else {
console.log("dateeee" + date);
rowss.length = 0;
prices.length = 0;
prices.push(availdata[p.roomId][date].p1);
var total_price = 0;
if (prices.length !== 0) {
for (var i = 0; i <= prices.length - 1; i++) {
total_price += parseFloat(prices[i]);
}
}
console.log("room:" + p.roomId + "price?" + availdata[p.roomId][date].p1)
HC.push(`<div key={${p.roomId}}>` +
'<HotelCards' +
` idroom={${p.roomId}}` +
` title={${p.roomName.toUpperCase()}}` +
` status={true}` +
` price={${total_price}}` +
' img={p.pictures[0].url}' +
' avail={1111}' +
' rows={rowss}' +
' guest={selectedGuest}' +
'/></div>');
}
}
}
});
console.log(HC);

My "Boosted Guild On" is getting the wrong date

I have been trying to fix this for a few days and I can't fix it. The problem is my "boosted guild on" part of my userinfo is showing up as a date even for people who haven't boosted the server. Please help. For more information, or to see the problem in depth, contact me on discord via Disown .#7397.
const Discord = require('discord.js');
const moment = require('moment');
const { color } = require("../../config.json");
const { verifiedBotDev } = require("../../emojis.json");
const { bugHunter } = require("../../emojis.json");
const { bugHunterPlus } = require("../../emojis.json");
const { discordPartner } = require("../../emojis.json");
const { discordStaff } = require("../../emojis.json");
const { hypeSquad } = require("../../emojis.json");
const { hypeSquadBravery } = require("../../emojis.json");
const { hypeSquadBril } = require("../../emojis.json");
const { hypeSquadBal } = require("../../emojis.json");
const { verifiedBot } = require("../../emojis.json");
const { earlySupporter } = require("../../emojis.json");
const { discordnitro } = require("../../emojis.json");
const flags = {
DISCORD_EMPLOYEE: `${discordStaff}`,
DISCORD_PARTNER: `${discordPartner}`,
BUGHUNTER_LEVEL_1: `${bugHunter}`,
BUGHUNTER_LEVEL_2: `${bugHunterPlus}`,
HYPESQUAD_EVENTS: `${hypeSquad}`,
HOUSE_BRAVERY: `${hypeSquadBravery}`,
HOUSE_BRILLIANCE: `${hypeSquadBril}`,
HOUSE_BALANCE: `${hypeSquadBal}`,
EARLY_SUPPORTER: `${earlySupporter}`,
VERIFIED_BOT: `${verifiedBot}`,
VERIFIED_DEVELOPER: `${verifiedBotDev}`,
Discord_Nitro : `${discordnitro}`
};
module.exports = {
name: "uitest",
aliases: ["uit", "uinfo", "info"],
run: async (client, message, args) => {
let mentionedMember = await message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args.join(' ').toLocaleLowerCase()) || message.guild.members.cache.find(r => r.displayName.toLowerCase() === args.join(' ').toLocaleLowerCase()) || args[0] || message.member;
const user = await client.users.fetch(client.users.resolveID(mentionedMember)).catch(() => null);
if (!user) user = message.author;
const userFlags = user.flags.toArray();
let nickname = user.nickname
if (nickname) {
nickname = `∙ ${user.nickname}`;
} else {
nickname = ''
}
let flags2 = user.flags2
if (flags) {
flags2 = `∙ ${userFlags.length ? userFlags.map(flag => flags[flag]).join(' ') : ' '}`;
} else {
flags2 = ''
}
let bot;
if (user.bot === true) {
bot = "Discord Bot";
} else {
bot = "N/A";
}
const userPos = message.guild.members.cache
.sort((a, b) => a.joinedTimestamp - b.joinedTimestamp)
.array();
const position = new Promise((fui) => {
for (let i = 1; i < userPos.length + 1; i++) {
if (userPos[i - 1].id === user.id) fui(i);
}
});
const activities = [];
let customStatus;
for (const activity of user.presence.activities.values()) {
switch (activity.type) {
case 'LISTENING':
if (user.bot) activities.push(`Listening to **${activity.name}**`);
else activities.push(`Listening to [**${activity.details}**](https://open.spotify.com//) by **${activity.state}**`);
break;
case 'CUSTOM_STATUS':
customStatus = activity.state;
break;
}
}
const embed = new Discord.MessageEmbed()
.setColor(mentionedMember.displayHexColor || color)
.setThumbnail(user.displayAvatarURL({ format: "png", dynamic: true, size: 2048 }))
.setAuthor(message.author.username, message.author.avatarURL({
dynamic: true
}))
.setTitle(`${user.tag} ${nickname} ${flags2}`)
.setDescription(`${activities.join('\n')}\n\`\`${user.id}\`\` ∙ Join position:`)
.setFooter(`${bot}`)
.setTimestamp()
.addFields(
{
name: "**Joined Discord On**",
value: `${moment(user.createdAt).format("dddd, MMMM Do YYYY, h:mm A")}`,
inline: true
},
{
name: "**Joined Guild On**",
value: `${user.joinedAt === 0
? `N/A`
: `${moment.utc(message.member.joinedAt).format("dddd, MMMM Do YYYY, h:mm A")}`
}`,
inline: true
},
{
name: '**Boosted Guild On**',
value: `${user.premiumSinceTimestamp === 0
? `N/A`
: `${moment(user.premiumSince).format("dddd, MMMM Do YYYY, h:mm A")}`
}`,
inline: true,
},
{
name: `**Role List [${mentionedMember.roles.size || ""}]**`,
value: `${mentionedMember.roles.cache
.filter(r => r.id !== message.guild.id).map(roles => `<#&${roles.id}>`)
.join(", ") || "N/A"}`,
inline: true
})
message.channel.send(embed)
}
}
premiumSinceTimestamp returns null if the member never boosted the guild and null is not the same as 0.
When you check if user.premiumSinceTimestamp === 0 it will always return false because it's either a timestamp or null. You only need to check if the value of premiumSinceTimestamp is truthy like this:
{
name: '**Boosted Guild On**',
value: user.premiumSinceTimestamp
? moment(user.premiumSince).format('dddd, MMMM Do YYYY, h:mm A')
: 'N/A',
inline: true,
};
You currently did the following:
{
name: '**Boosted Guild On**',
value: `${user.premiumSinceTimestamp === 0 ? `N/A` : `${moment(user.premiumSince).format("dddd, MMMM Do YYYY, h:mm A")}`
}`,
inline: true,
},
While the syntax is:
<condition> ? <if condition is true> : <if condition is false>
You used the function the other way around, you should simply change the order of N/A and ${moment(user.....

trouble with displaying data from firestore

I'm having two issues this moment
I am having trouble displaying the data from my firestore document after the user signs in and they do have a document with data
I have a button that lets the user upload a document and I will parse it to extract all important data. That data is then put into the document with Ids, which is basically the userId + what number doc it is belonging to the user. When they upload the data it seems that all data extracted uses the same ID and only the last one extracted gets displayed.
this is my code:
const loansRef = firebase.firestore().collection('goals');
const [ courseGoals, setCourseGoals ] = useState([]);
const [goalCounter, setGoalCounter] = useState(0)
//let the user upload doc, what gets called when they press button
const pickDocument = async () => {
try {
let input = await DocumentPicker.getDocumentAsync({
type: "text/plain",
});
setUserOut(await FileSystem.readAsStringAsync(input.uri));
} catch (error) {
console.log(error);
}
createLoans();
};
//extracts important info and returns array with all info for one loan
const fileParser = () => {
const parsedLoans = [];
var newUserOut = userOut;
if (newUserOut.length == 0) {
return;
}
//remove the grants
var grantPos = newUserOut.search("Grant Type:");
var pos = newUserOut.search("Loan Type:");
//hopefully just the loans now
newUserOut = newUserOut.slice(pos, grantPos);
while (newUserOut.length > 0) {
var lastPos = newUserOut.lastIndexOf("Loan Type:");
parsedLoans.push(newUserOut.slice(lastPos, newUserOut.length));
newUserOut = newUserOut.slice(0, lastPos);
}
//console.log('parsed loans: ' + parsedLoans)
return parsedLoans;
};
//where we actually create loans and get the important data for each loan
const createLoans = () => {
const newLoans = fileParser();
const title= 'Loan Amount:$'
const interest = 'Loan Interest Rate:'
for(let i =0; i < newLoans.length; i++){
let loan = newLoans[i]
let goalTitle=loan.substring(loan.indexOf(title)+title.length,loan.indexOf('Loan Disbursed Amount:'))
//console.log("goalTitle: " + goalTitle)
let interestRate = loan.substring(loan.indexOf(interest)+interest.length,loan.indexOf('Loan Repayment Plan Type'))
//console.log("Interest rate: "+ interestRate)
let years = 0
let paidOff = 0
addGoalHandler(goalTitle,interestRate,years,paidOff)
}
return
};
useEffect(() => {
getPW()
let isMounted = true;
if (isMounted) {
loansRef.doc(userId).onSnapshot(
(docSnapshot) => {
if(!docSnapshot.exists){console.log('doc doesnt exist, start from scratch')}
else{
console.log('loaded successfully '+docSnapshot.data())
setGoalCounter(docSnapshot.data().loans.length)
console.log(goalCounter)
}
},
(error) => {
console.log(error);
}
);
}
return () => {
isMounted = false;
};
}, []);
const addGoalHandler = (goalTitle, interestRate, years, paidOff) => {
//setCourseGoals([...courseGoals, enteredGoal])
setGoalCounter(goalCounter+1)
setCourseGoals((prevGoals) => [
...courseGoals,
{
id:userId.toString() + goalCounter.toString(),
value: goalTitle,
interest: interestRate,
years: years,
paidOff: paidOff
}
]);
addToFB(goalTitle, interestRate,years,paidOff)
//var oldIDS = docIDS
//oldIDS.push(userId.toString() + goalCounter.toString())
//setDocIDS(oldIDS)
setIsAddMode(false);
};
const cancelGoalAdditionHandler = () => {
setIsAddMode(false);
};
const addToFB = async (goalTitle, interestRate, years, paidOff) => {
//adding data to firebase, takes into account if doc exists already
const loadDoc = await loansRef.doc(userId).get()
.then((docSnapshot)=> {
if(docSnapshot.exists){
loansRef.doc(userId).onSnapshot((docu)=>{
const updateLoansArr = loansRef.doc(userId).update({
loans: firebase.firestore.FieldValue.arrayUnion({
id: userId+goalCounter.toString(),
value: goalTitle,
interest: interestRate,
years: years,
paidOff: paidOff
})
})
//setGoalCounter(goalCounter+1)
})
}
else{
const addDoc = loansRef.doc(userId).set({
loans: firebase.firestore.FieldValue.arrayUnion({
id: userId+goalCounter.toString(),
value: goalTitle,
interest: interestRate,
years: years,
paidOff: paidOff
})
})
//setGoalCounter(goalCounter+1)
}})
//setGoalCounter(goalCounter+1)
}
const removeGoalHandler = async (goalId) => {
/*
setCourseGoals((currentGoals) => {
loansRef.doc(goalId).delete().then(console.log('removed correctly'))
return currentGoals.filter((goal) => goal.id !== goalId);
});
setGoalCounter(goalCounter-1)
*/
//need to use the value and not the goalId
const removeGoal = await loansRef.doc(goalId).update({
goals: firebase.firestore.FieldValue.arrayRemove(goalId)
})
setCourseGoals((currentGoals)=> {
return currentGoals.filer((goal)=> goal.id !== goalId)
})
};

Call multiple API with NodeJS and merge them together

I'm changing the question cause I think I explain myself wrong.
I'm using currently 1 API endpoint to receive data which I need. I need to add a second end point to receive data from both end points in the same time, merge them together and store in Database.
First endpoint -
https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1
Second endpoint - https://api.binance.com/api/v3/ticker/24hr?symbol=${symbol}
Here is how I receive Data from first endpoint
const getBTCData = async symbol => {
let data = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1`).then(res => res.json());
const btcusdtdata = data.map(d => {
return {
Open: parseFloat(d[1]),
High: parseFloat(d[2]),
Low: parseFloat(d[3]),
Close: parseFloat(d[4]),
Timespan: 30,
}
});
console.log(btcusdtdata);
saveToDatebase(symbol, btcusdtdata);
};
Im returning 4 parameters from this endpoint
And I need to take one parameter from second endpoint and combine it with parameters from first one.
I need this parameter from second endpoint - "quoteVolume": "15.30000000"
I founded that Promise.all can be a solution but I don't understand it properly on how I can return data from 2 api and merge them together in a single object to save in MongoDB.
FULL CODE
Small explanation - goal is to take data from both endpoints and store it in MongoDB as well as calculating the average for quoteVolume on last 200 days.
const { MongoClient } = require('mongodb');
const schedule = require('node-schedule');
const fetch = require("node-fetch");
require('dotenv').config()
"use strict"; // This is ES6 specific. Help's to run code faster(IMPORTANT FOR NOTIFICATION SYSTEM)
const nodemailer = require("nodemailer");
const symbols = ["ADABTC", "AEBTC","AIONBTC"];
//a descriptive name helps your future self and others understand code easier
const getBTCData = async symbol => {
let data = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=30m&limit=1`).then(res => res.json());
const btcusdtdata = data.map(d => {
return {
Open: parseFloat(d[1]),
High: parseFloat(d[2]),
Low: parseFloat(d[3]),
Close: parseFloat(d[4]),
Volume: parseFloat(d[5]),
Timespan: 30,
}
});
console.log(btcusdtdata);
saveToDatebase(symbol, btcusdtdata);
//recursive functions are complicated, we can get rid of it here
//by moving the responsibility to the caller
};
//helper function for an awaitable timeout
const sleep = ms => new Promise(res => setTimeout(res, ms));
const j = schedule.scheduleJob('* * * * * *', async() => {
//expand this function to be responsible for looping the data
for (let symbol of symbols) {
await getBTCData(symbol);
await sleep(8000);
}
});
const getDateTime = () => {
let today = new Date();
let date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
return date + ' ' + time;
};
const saveToDatebase = async(symbol, BTCdata) => {
try {
const url = 'mongodb://username:password#ip.adress.com:port/dbname?retryWrites=true&w=majority';
let dateTime = getDateTime();
let db = await MongoClient.connect(url, { useUnifiedTopology: true });
const dbo = db.db('Crypto');
const myobj = Object.assign({ Name: symbol, Date: dateTime }, BTCdata[0]);
await dbo.collection(symbol).insertOne(myobj);
const average = await dbo.collection(symbol).aggregate([{
$addFields: {
DateObj: {
$regexFindAll: { input: "$Date", regex: "\\d+" }
}
}
},
{
$set: {
DateObj: {
$dateFromParts: {
year: { $toInt: { $arrayElemAt: ["$DateObj.match", 0] } },
month: { $toInt: { $arrayElemAt: ["$DateObj.match", 1] } },
day: { $toInt: { $arrayElemAt: ["$DateObj.match", 2] } },
hour: { $toInt: { $arrayElemAt: ["$DateObj.match", 3] } },
minute: { $toInt: { $arrayElemAt: ["$DateObj.match", 4] } },
second: { $toInt: { $arrayElemAt: ["$DateObj.match", 5] } },
timezone: "Europe/London"
}
}
}
},
{
$match: {
$expr: {
$gte: ["$DateObj", { $subtract: ["$$NOW", 201 * 60 * 60 * 24 * 1000] }]
}
}
},
{
"$group": {
_id: null,
"Volume": {
"$avg": "$Volume"
}
}
}
]).toArray();
console.log('1 document inserted');
console.log(BTCdata[0].Volume);
console.log(average[0].Volume);
const RealTimeDataVolume = parseInt(BTCdata[0].Volume);
const HistoricalTimeDataVolume = parseInt(average[0].Volume); // 201 DAYS VOLUME HERE 3286033.4285714286
const DayTimesRealAverage = RealTimeDataVolume * 48; // 1 DAY REAL TIME DATA HERE 196579344
const Previous200dVolume = (HistoricalTimeDataVolume - DayTimesRealAverage) / 200;
const MultiplePrevious200dVolume = Previous200dVolume * 5;
if (MultiplePrevious200dVolume < DayTimesRealAverage) {
async function main() {
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: process.env.DB_USER, // OUR ALARM EMAIL
pass: process.env.DB_PASS, // OUR ALARM PASSWORD
},
});
let info = await transporter.sendMail({
from: process.env.DB_USER, // sender address
to: process.env.DB_RECEIVER, // list of receivers
subject: symbol + 'Is UP', // Subject line
text: symbol + " IS UP", // plain text body
});
console.log("Message sent: %s", info.messageId, symbol);
}
main().catch(console.error);
} else {
console.log('false');
}
console.log(DayTimesRealAverage);
console.log(MultiplePrevious200dVolume);
} catch (e) {
console.error(e)
}
};
You can do it in the same way.
In response you are getting a son object.
You need to do res["quoteVolume"] to get the data.

Take data from yesterday

So I need to take data only from the day before. Example: today is 2018/9/25, I need the data to be taken on 2018/9/24 only. But from my code below, it takes from 23 until 25. Which is more than one day, and it took also two days before from the date I need. I don't know which code that make a wrong result. Anyone can help me with this? I really appreciate it.
Api.js
const TO_DAYS = 4194304 * 1000 * 60 * 60 * 24; // this part that might be the cause
const ROOT_DATE = moment([2018, 3, 30]); // this part that might be the cause
const ROOT_DATE_ID = 440557948108800000; // this part that might be the cause
const DATE_ID = function(date) {
return ROOT_DATE_ID + date.diff(ROOT_DATE, "days") * TO_DAYS;
}; // this part that might be the cause
class discordApi {
constructor() {
this.lock = new AsyncLock();
}
get(momentDate, authorId, offset = 0) {
const url =
config.endpoint +
querystring.stringify({
min_id: DATE_ID(momentDate),
author_id: authorId
});
return fetch(url, {
headers: {
method: "GET",
Authorization: config.auth
}
}).then(res => {
// console.log(res.url);
return res.json();
});
}
async getAllData(momentDate) {
const allData = config.targets.map(author_id =>
this.get(momentDate, author_id)
);
return Promise.all(allData);
}
index.js
var yesterday = moment().subtract(1, "days"); // this part that might be the cause
async function sendEmail() {
const data = await discordApi.getAllData(yesterday);
const unfilteredMessages = data.reduce(
(prev, current) => [...prev, ...current.messages],
[]
);
const filteredMessages = unfilteredMessages.reduce((prev, current) => {
if (prev.length === 0) {
return [...prev, current];
}
const currentConversationIsDuplicated = isConversationDuplicated(
prev[prev.length - 1],
current
);
if (currentConversationIsDuplicated) {
return prev;
}
ret
urn [...prev, current];
}, []);
const convo = await discordApi.AllConvo(filteredMessages);
const mailOptions = {
from: "lala#gmail.com",
to: maillist,
subject: "Discord-Bot Daily Data",
html: convo
};
transporter.sendMail(mailOptions, function(err, info) {
if (err) console.log(err);
else console.log("Message Sent!");
});
}

Categories