JS node issue with for and foreach loops - javascript

This is really puzzling me, until 4 days ago everything was working fine and no problems were occurring, but then an issue started when two of my cron daemon jobs stopped working.
I thought nothing of it and decided to rebuild the code and improve it a little as I have gained more insight since the files were coded the first time around.
Here is the problem:
this one works as expected on local machine
Object.keys(res).forEach(function(key) {
const row = res[key];
client.channels.get(row.forchannel).send({ embed });
console.log(row.forchannel);
});
and so does this one:
res.forEach(function(row) {
client.channels.get(row.forchannel).send({ embed });
console.log(row.forchannel);
});
and also this one:
for (let i = 0; i < res.length; i++) {
console.log(res[i]);
client.channels.get(res[i].forchannel).send({ embed });
}
The issue I have is that non of them work when I upload to live server, the results from a MySQL query are there when I console log out of the loop on live, console logging inside the loop on live shows nothing except for the last block of code I posted and this returns one result.
Local machine is windows running Node v11.6 and live is Ubuntu running a v11.12 of node.
So to summary:
On the live server those loops above are not working, I can return arrays when console logging data outside of the loops but on only the last one does any data show when console logging inside the loop.
On local machine everything works as expected, In both cases error catching reports null so there are no errors.

res.map((result) => {
client.channels.get(result.forchannel).send({ embed });
});
It might help you.

I discovered what the problem was, although my bot has both a subscribe and an unsubscribe option my code does not cater for the obvious: A discord server Admin deleting a channel, this then leaves a row in the database that when fed into the loop comes back false as the channel no longer exists and stops the auto-posting.
Working code first checks if the channel does actually exist before processing through the array.
res.map((result) => {
if (client.channels.has(result.forchannel)) {
client.channels.get(result.forchannel).send({ embed });
}
});
client.channels.has checks that the channel exists and because its in an if statement will only proceed to post on channels that return true.

Related

matrix-js-sdk setup and configuration

I am having some issues trying to connect to a matrix server using the matrix-js-sdk in a react app.
I have provided a simple code example below, and made sure that credentials are valid (login works) and that the environment variable containing the URL for the matrix client is set. I have signed into element in a browser and created two rooms for testing purposes, and was expecting these two rooms would be returned from matrixClient.getRooms(). However, this simply returns an empty array. With some further testing it seems like the asynchronous functions provided for fetching room, member and group ID's only, works as expected.
According to https://matrix.org/docs/guides/usage-of-the-matrix-js-sd these should be valid steps for setting up the matrix-js-sdk, however the sync is never executed either.
const matrixClient = sdk.createClient(
process.env.REACT_APP_MATRIX_CLIENT_URL!
);
await matrixClient.long("m.login.password", credentials);
matrixClient.once('sync', () => {
debugger; // Never hit
}
for (const room of matrixClient.getRooms()) {
debugger; // Never hit
}
I did manage to use the roomId's returned from await matrixClient.roomInitialSync(roomId, limit, callback), however this lead me to another issue where I can't figure out how to decrypt messages, as the events containing the messages sent in the room seems to be of type 'm.room.encrypted' instead of 'm.room.message'.
Does anyone have any good examples of working implementations for the matrix-js-sdk, or any other good resources for properly understanding how to put this all together? I need to be able to load rooms, persons, messages etc. and display these respectively in a ReactJS application.
It turns out I simply forgot to run startClient on the matrix client, resulting in it not fetching any data.

Node.js API requests randomly stopping

This is my first project, yes the code is bad, please be nice!
I'm working on a Discord Bot, which requests Game APIs for a whole Guild. First I get all the Ids for a guild into an array and then I make a get request for every Id.
My problem is, that the request just randomly stops after some time (always different), and I don't know why. It's also not giving an error.
I've already tried to run it from another program, change the package I'm using, look that the key can be used, but in the end, everything is the same.
while (guildmembers[i2] != undefined) {
console.log(guildmembers[i2])
let url = 'https://api.hypixel.net/player?key=' + APIkey
let Guildmembersuuid = guildmembers[i2]
let profilelurl = url + '&uuid=' + Guildmembersuuid
const TESTguildPlayerinfos = await axios.get(profilelurl)
console.log(TESTguildPlayerinfos)
i2++
}
If I did anything wrong with the post or didn't give enough information please tell me!
Thanks a lot for the help!
try using Promise.all(),which takes an array of promises and then put a catch block afterwards to see if there is any problem.
It looks like you are hitting the Hypixel throttling limits - you need to be more careful with your requests. As it stands, they will stop you at 120 requests/minute. You either need to manually throttle yourself like one member in the thread mentioned (waiting .5 seconds between any call to the API to ensure you don't overflow the limit) or insert a cache in between so that calls don't actually always land on the Hypixel backend.
https://hypixel.net/threads/api-request-limit.815723/

Discord Bot Development: How do I stop this infinite loop?

This calls and retrieves a dog url from random.dog, when posting the link to log it stops at one, however when using message.channel.send below it runs an infinite loop of the call, what would be the best way to prevent this and to only send one link then stop till it is called again?
const animals = require('relevant-animals')
client.on("message", (message) => {
if(message.content.includes("dog")){
animals.dog().then(s => message.channel.send(s)) ;
animals.dog().then(s => console.log(s)) ;
};
Below is console log after one request it sends one link
Below is after it is sent to the channel, it just posts links non stop rather than just the one as shown in the console
Your bot is responding to itself. You can exclude it for replying to itself by using message.author.bot.
if(!message.author.bot) {
// Do something if message doesn't come from a bot.
}
I hope this code will help you getting on the right path, good luck!
You could just do this:
if(message.author.bot) return;
This wouldn't only stop bot from executing commands etc. on itself, it would prevent any bot from using your bot.
Since it checks for author of message if bot property returns true it would return;.
And if bot property returns false it would work as normally - only for users like you and me, and many others!
You can try this by doing the following code:
console.log(message.author.bot);
It will log the boolean value of bot property of the messages author.
You can read more about booleans (true/false) here.

Mongo document count different from console.logged count

Doing some experimenting to get a grasp of the basics on my road to learning how to code. Been messing around with one aspect all day but can't figure it out. I'm sure it must be something simple and would appreciate any help!
So I've created a Mongo collection:
Posts = new Mongo.Collection('posts');
I then added 3 documents into the collection, with 2 fields each (name and quantity). Now, when in the Google Chrome console I run:
Posts.find().count();
//returns '3' as expected
However, when instead I run the following code from the server (is it called the server if it is the client side code?):
if (Meteor.isClient) {
var c = Posts.find().count();
console.log("The database documents count is " + c);
}
Then it comes up on Chrome console as:
The database documents count is 0
What gives? What's going on here?
Thanks in advance!!
How it works: when you open a page, the client has no data at all. After your JS is loaded, publish functions begin to work and after some time, when publishing is over, you have data on the client.
So at the moment when browser runs:
if (Meteor.isClient) {
console.log(Posts.find().count());
}
You have no data on the client, that's why you see 0 in the console.
But then you open console manually and write Posts.find().count(). It took some time for you to open the console, to write Posts.find().count() and this time was enough for publish functions to send all data to the client, so now you have data on the client and you will see 3 in the console.
You can try this experiment:
if (Meteor.isClient) {
setTimeout(function() {
console.log(Posts.find().count());
}, 2000);
}
It will log posts count not immediately, but with 2 seconds delay, this should be enough for publishing to be over and you will see 3 in the console. You can change timeout delay and find out how much does it take for the server to send posts data to the client.

ASP ADO recordset.NextRecordset() breaks when there is no next recordset

I'm writing a script in ASP with Javascript, and I need to loop through an indeterminate number of records AND recordsets. I have no problem looping through the individual records. The problem arises when I need to move through recordsets. As long as there is another recordset it works fine. If there are no more recordsets the code dies, and there seems to be no way to check for or catch the error. I've done try/catch blocks and every test I can think of, but the code just breaks and gives internal server error. I was hoping there was an isNextRecordset() or isLastRecordset() function I was missing.
My Current Code
do{
//Some Code Stuff
record = record.NextRecordset(); //Dies here when no more recordsets
}while(!!record);
With normal VBScript they show this method working(never tried it though). But I don't want to use VBScript.
VBScript Code
Do Until record = Nothing
set record = record.NextRecordset
Loop
EDIT:
I believe I have made things confusing by adding the loop, If you remove the loop and just call nextrecordset once when there is no next recordset it still dies. No test for null needed. My code doesn't make it to the test for null.
//Get A recordset
//There is only one recordset
record = cmd.Execute();
//Do some stuff with the record set
//Call NextRecordset
//even though there are no more
record = record.NextRecordset(); //<--- Still Dies right here
EDIT:
Just wanted to point out the hidden problem I was having. The answer below is correct but wasn't my actual problem. Some of the tutorials I saw show a structure like below. Close the record and connection. But by the time the record got the bottom it was already null, which was a problem. This is easily solved with correct error messages showing, which I didn't have. My own stupidity, but might help someone.
try{
//Do Some Stuff
record = record.NextRecordset();
//Test Record set
}catch(e){
}finally{
record.Close(); <---- This is where it was actually having a problem.
record = null;
myconn.Close();
myconn = null;
}
Proper syntax would be:
while (record) {
//Some Code Stuff
record = record.NextRecordset();
}
This way the loop would stop when NextRecordset() will return null.

Categories

Resources