Passing in list elements in javascript to a different function - javascript

I'm trying to do a web scraping exercise where some values are being retrieved and are being stored in a list variable. I am then passing in the list variable as a parameter in a different function. The problem with my approach is I am getting an error when calling the different function. I believe I'm getting this error because I am not passing in the list elements into the function appropriately. In the function, I am reading from a Yahoo Stock API used to retrieve stock data. If I were to hardcode a stock symbol into the parameter for the function, it works without any issue. Since I am passing in a parameter, I am getting this error. Below is my code and the error I am getting. Any feedback would be helpful.
Code
const cheerio = require('cheerio');
const axios = require('axios');
const yahooStockPrices = require('yahoo-stock-prices');
var stockSymbol = []
async function read_fortune_500() {
try {
const { data } = await axios({ method: "GET", url: "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies", })
const $ = cheerio.load(data)
const elemSelector = '#constituents > tbody > tr > td:nth-child(1)'
$(elemSelector).each((parentIndex, parentElem) => {
let keyIndex = 0
if (parentIndex <= 9){
$(parentElem).children().each((childIndex, childElem) => {
const tdValue = $(childElem).text()
if (tdValue) {
//stockObject[keys[keyIndex]] = tdValue
stockSymbol = tdValue
}
})
console.log(stockSymbol)
}
})
} catch (err) {
console.error(err)
}
return stockSymbol;
}
async function collect_stocks(stockSymbol) {
stockSymbol = read_fortune_500()
const stockResult = await yahooStockPrices.getCurrentData(stockSymbol);
console.log(stockResult);
}
collect_stocks(stockSymbol)
Error
/node_modules/yahoo-stock-prices/yahoo-stock-prices.js:75
.split('regularMarketPrice')[1]
^
TypeError: Cannot read properties of undefined (reading 'split')
at Request._callback (/node_modules/yahoo-stock-prices/yahoo-stock-prices.js:75:21)
at Request.self.callback (/node_modules/request/request.js:185:22)
at Request.emit (node:events:390:28)
at Request.emit (node:domain:475:12)
at Request.<anonymous> (/node_modules/request/request.js:1154:10)
at Request.emit (node:events:390:28)
at Request.emit (node:domain:475:12)
at IncomingMessage.<anonymous> (/node_modules/request/request.js:1076:12)
at Object.onceWrapper (node:events:509:28)
at IncomingMessage.emit (node:events:402:35)

The parameter stockSymbol seems to be empty when you pass it to your desired function therefore, when yahoo-stock-prices try to apply a split on it, it fails.

Related

Error: 3 INVALID_ARGUMENT: Invalid resource field value in the request

I am following a List Queues sample to lists all the queues. But, I get below error:
Error: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
at Object.callErrorFromStatus (/workspace/node_modules/#grpc/grpc-js/build/src/call.js:31:19)
at Object.onReceiveStatus (/workspace/node_modules/#grpc/grpc-js/build/src/client.js:190:52)
at Object.onReceiveStatus (/workspace/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:365:141)
at Object.onReceiveStatus (/workspace/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:328:181)
at /workspace/node_modules/#grpc/grpc-js/build/src/call-stream.js:188:78
at processTicksAndRejections (node:internal/process/task_queues:78:11)
Some code snippet:
const parent = client.locationPath(project, location);
const [queues] = await client.listQueues({parent});
if (queues.length > 0) {
  console.log('Queues:');
  queues.forEach(queue => {
    console.log(` ${queue.name}`);
  });
} else {
  console.log('No queues found!');
}
I am not very sure whether the error is derived from this line:
const [queues] = await client.listQueues({parent});
Appreciate if someone can advise. Thank you in advance!
I just change
const [queues] = await client.listQueues({parent});
to
const [queues] = await client.listQueues({parent: parent});
and the problem is solved.

i getting error Cannot read property 'channels' of undefined

I'm getting an error Cannot read property 'channels' of undefined
(node:2632) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property 'channels' of undefined
at updateMembers (C:\Users\Asus\Desktop\Episode 50\commands\Main-Commands\Mod\member-count.js:5:31)
at module.exports (C:\Users\Asus\Desktop\Episode 50\commands\Main-Commands\Mod\member-count.js:13:5)
at Client. (C:\Users\Asus\Desktop\Episode 50\index.js:48:5)
at Object.onceWrapper (events.js:421:28)
at Client.emit (events.js:315:20)
at WebSocketManager.triggerClientReady (C:\Users\Asus\Desktop\Episode
50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:431:17)
at WebSocketManager.checkShardsReady (C:\Users\Asus\Desktop\Episode
50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:415:10)
at WebSocketShard. (C:\Users\Asus\Desktop\Episode 50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:197:14)
at WebSocketShard.emit (events.js:315:20)
at WebSocketShard.checkReady (C:\Users\Asus\Desktop\Episode 50\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
Here is my code:
module.exports = (client) => {
const membercountchannel = '811119579580465182'
const updateMembers = (guild) => {
const channel = guild.channels.cache.get(membercountchannel)
channel.setName(`Member:- ${guild.memberCount.toLocaleString()}`)
}
client.on('guildMemberAdd', (member) => updateMembers(member.guild))
client.on('guildMemberRemove', (member) => updateMembers(member.guild))
const guild = client.guilds.cache.get('787083837833871400')
updateMembers(guild)
}
If you check the stack trace, you can see that your updateMembers function receives a guild that is undefined (member-count.js:5:31). On the next line you can see that it's coming from the last line (member-count.js:13:5): updateMembers(guild).
As you define guild one line above, it means client.guilds.cache.get('787083837833871400') returns undefined. Make sure the guild ID is correct. If it is correct, you can try to fetch the guild instead.
One more thing, you should never add event handlers inside event handlers. I think you're already in client.on('message'). Every time someone's using your command to update the member count, you create two new event listeners (client.on('guildMemberAdd') and client.on('guildMemberRemove')) and it will cause issues (memory leaks). You need to handle these somewhere else, outside of your commands.
module.exports = async (client) => {
const updateMembers = (guild) => {
const memberCountChannel = '811119579580465182';
const channel = guild.channels.cache.get(memberCountChannel);
channel.setName(`Member:- ${guild.memberCount.toLocaleString()}`);
};
try {
const guild = await client.guilds.fetch('787083837833871400');
updateMembers(guild);
} catch (error) {
console.log(error);
}
};

TypeError: value.split is not a function

I'm creating a discord.js bot v12 and I get this error on line 2 when I use the purge command in discord and I'm assuming value.split is not a function and wondering if I should be doing something else since I'm using v12 of discord.js:
Uncaught Promise Error:
TypeError: args.split is not a function or its return value is not iterable
at Object.module.exports.run (c:\Users\Kazzu\Desktop\src\commands\prune.js:2:34)
at module.exports (c:\Users\Kazzu\Desktop\src\events\message.js:33:9)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (c:\Users\Kazzu\Desktop\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:311:20)
This is my code:
module.exports.run = async (client, message, args) => {
let [ userId, limit ] = args.split(/\s+/);
if(!userId && !limit) {
let deletedMessages = await message.channel.bulkDelete();
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
if(!userId || !limit) return message.channel.send('Please provide the correct arguments.');
let r = new RegExp(/^\d+$/);
if(!r.test(userId)) return message.channel.send('Please provide a valid user id.');
if(isNaN(limit)) return message.channel.send('Please provide a numeric value for limit');
if(limit > 100) return message.channel.send('Limit must be less than or equal to 100.');
try {
let fetchedMessages = await message.channel.messages.fetch({ limit });
let filteredMessages = fetchedMessages.filter(message => message.author.id === userId);
let deletedMessages = await message.channel.bulkDelete(filteredMessages);
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
catch(err) {
console.log(err);
}
}
module.exports.help = {
name: "purge",
description: "Deletes a number of messages from a user in a channel."
}
module.exports.requirements = {
userPerms: [],
clientPerms: [],
ownerOnly: false
}
It seems that args is not type of string. When you call .split() for something other than a string, JavaScript runtime cannot find the .split() method for that type. So, make sure you are passing a string to your function or try something like that:
if (typeof string === args) {
var str = args.toString();
}
Turns out I needed to replace value.split to value.slice

How to Retrieve individual JSON values from Firebase Database?

Let's say I have a firebase node that is dbref = firebase.ref('/Transfer_Request/{pushID]/').
And the client writes two values; from_ID and to_ID to dbref. How do I get the individual values of the from_ID and to_ID from Firebase Cloud functions?
My code:
exports.TransferTicket = functions.database.ref('/Transfer_Request/{pushID}').onWrite((event) => {
const original = event.data.val();
const from_ID = original.from_ID;
const to_email_ID = original.to_ID;
//search for to_email ID
return admin.database().set("A transfer request was just made");
});
I'm getting two errors:
1)
TypeError: admin.database(...).set is not a function at
exports.TransferTicket.functions.database.ref.onWrite
(/user_code/index.js:41:25) at Object.
(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
at next (native) at
/user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter
(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction
(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
at /var/tmp/worker/worker.js:716:24 at process._tickDomainCallback
(internal/process/next_tick.js:135:7)
2)
TypeError: Cannot read property 'from' of null at
exports.TransferTicket.functions.database.ref.onWrite
(/user_code/index.js:35:25) at Object.
(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
at next (native) at
/user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter
(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction
(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
at /var/tmp/worker/worker.js:716:24 at process._tickDomainCallback
(internal/process/next_tick.js:135:7)
The first problem comes from the fact that when doing the following you miss a Firebase Reference.
return admin.database().set("A transfer request was just made");
You should do:
admin.database().ref('...the path where you want to write...').set("A transfer request was just made");
For more details, see the doc for Reference and Database .
The second problem comes from the fact that since the new release of the version 1.0.0 of the Firebase SDK for Cloud Functions, the syntax has changed. See this doc item.
You should modify your code as follows:
exports.TransferTicket = functions.database.ref('/Transfer_Request/{pushID}').onWrite((change, context) => {
const original = change.after.val();
const from_ID = original.from_ID;
console.log(from_ID);
const to_email_ID = original.to_ID;
console.log(to_email_ID);
return admin.database().ref('...path...').set("A transfer request was just made")
.catch(error => {
console.log(error);
//...
});
});

Cloud Firestore: TypeError: Cannot read property 'ref' of undefined

Cloud Firestore: TypeError: Cannot read property 'ref' of undefined
I'm using Cloud Functions to update the comments number in the parent collection of Cloud Firestore, so when a comment added the Cloud Functions can automatically update the comment number.
exports.updateCommentNumbers = functions.firestore
.document('postlist/{postlistId}/comments/{commentsID}')
.onCreate(event =>
{
const collectionRef = event.after.ref.parent;
const countRef = collectionRef.parent.child('comment_number');
//const previousValue = event.data.previous.data();
let increment;
if (event.after.exists() )
{
increment = 1;
}
else
{
return null;
}
return countRef.transaction((current) =>
{
return (current || 0) + increment;
}).then(() =>
{
return console.log('Comments numbers updated.');
});
});
I got error which I don't understand. Could you tell me what's wrong?
TypeError: Cannot read property 'ref' of undefined
at exports.updateCommentNumbers.functions.firestore.document.onCreate.event
(/user_code/index.js:46:35)
at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:716:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
As show in this upgrade guide the signature of Cloud Functions for Firebase has changes when it switched to v1.0.
If you used this before v1.0:
exports.dbWrite = functions.firestore.document('/path').onWrite((event) => {
const beforeData = event.data.previous.data(); // data before the write
const afterData = event.data.data(); // data after the write
});
It now is:
exports.dbWrite = functions.firestore.document('/path').onWrite((change, context) => {
const beforeData = change.before.data(); // data before the write
const afterData = change.after.data(); // data after the write
});
Instead of rewriting the code for you, I recommend you update it based on that documentation, or check where you got the code from to see if there's an updated version.

Categories

Resources