skip to Main Content

I’m creating a simple Messenger bot, using unofficial Facebook Chat API (https://github.com/Schmavery/facebook-chat-api) and Node.js.

For now, I’m working on sending messages to specific users, on a specific time. Here’s part of my code:

if(msgdate.getTime() <= currdate.getTime()){

    console.log(alarms[i].message);
    // output: test

    api.getUserID(alarms[i].user, (err, users) => {
        if(err) return console.error(err);

        api.sendMessage(alarms[i].message, users[0].userID);
        // TypeError: Cannot read property 'message' of undefined
    });
}

And, my question is: how could I pass alarms array to this callback, so I’d be able to send message to a specific user?

2

Answers


  1. Looks like that you change i variable somewhere, and because of that when callback is called alarms[i] is undefined. You need to store alarms[i] in a new variable and use it in callback:

    let alarm = alarms[i];
    api.getUserID(alarm.user, (err, users) => {
      if(err) {
        return console.error(err);
      }
      api.sendMessage(alarm.message, users[0].userID);
    });
    
    Login or Signup to reply.
  2. Appear that you are using for loop outside. Try pass your var that way:

    var alarm = alarm[i];
    (function (alarm) {
        if(msgdate.getTime() <= currdate.getTime()){
    
        console.log(alarm.message);
        // output: test
    
        api.getUserID(alarm.user, (err, users) => {
            if(err) return console.error(err);
    
            api.sendMessage(alarm.message, users[0].userID);
            // TypeError: Cannot read property 'message' of undefined
        });
    })(alarm);
    

    Maybe you need to pass other vars too. Just put a comma and other var, example:

    (function (alarm, user){
        // your code here
    })(alarm, user);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search