skip to Main Content

I’m using Facebook chat api to create a simple cli script that will reply to messages that are sent to my facebook account. I’m trying to assign and get the user name and my name to use them inside the reply but they are always undefined. I think that the object property aren’t assigned correctly. Is there a fix for this?

require('dotenv').config();
const fs = require('fs');
const fb = require('facebook-chat-api'); 
const path = require('path');
const appStateFile = path.format({ dir: __dirname, base: 'appstate.json' });
let currentUser = null;

if( !fs.existsSync(appStateFile) ){
    //debug .env
    console.log(process.env);

    fb({email: process.env.FB_EMAIL, password: process.env.FB_PWD}, (err, api) => {
        if(err){ 
            return console.log(err);
        }
        console.log(api);
        api.setOptions({
            listenEvents: true
        });
        fs.writeFileSync(appStateFile, JSON.stringify(api.getAppState()));
        let id = api.getCurrentUserID();
        api.getUserInfo(id, (err, profile) => {
            console.log(profile); // profile is logged correctly
            currentUser = profile;
        });
        api.listenMqtt( (err, event) => {
            if(err){ 
                return console.log(err);
            }
            if(event.type === 'message'){
                console.log(event.body)
                api.getUserInfo(event.senderID, (err, user) => {
                    if(err){
                        return console.log(err);
                    }
                    console.log(user); // user object is logged correctly
                    api.sendMessage('...', event.threadID)
                });
            }
        });
    });
}else{
    fb({appState: JSON.parse(fs.readFileSync(appStateFile))}, (err, api) => {
        if(err){ 
            return console.log(err);
        }
        console.log(api);
        api.setOptions({
            listenEvents: true
        });

        let id = api.getCurrentUserID();
        api.getUserInfo(id, (err, profile) => {
            console.log(profile);
            currentUser = profile;
        });
        api.listenMqtt( (err, event) => {
            if(err){ 
                return console.log(err);
            }
            if(event.type === 'message'){
                console.log(event.body)
                api.getUserInfo(event.senderID, (err, user) => {
                    if(err){
                        return console.log(err);
                    }
                    console.log(user)
                    api.sendMessage(`FB Pager v1.0.nHi ${user.name}!Your message was forwarded with an email to ${currentUser.name}.`, event.threadID)
                });
            }
        });
    });
}

2

Answers


  1. Chosen as BEST ANSWER

    After a lot of debug I've found the correct way to access the needed informations. Since the user informations after that are retrived are mapped to another object that is the userId, the only way to access to each property is to use a for loop. Initially I was thinking that this can be avoided but unfortunately it's necessary otherwise using only dot notation will result in undefined. This is how I've solved

    api.getUserInfo(userId, (err, user) => {
      let username;
      if(err){
       return console.log(err);
      }
      for(var prop in user){
       username = user[prop].name;
      }
      api.sendMessage(`Hello ${username!}`, event.threadID);   
    });
    

  2. I think the problem here is that api.getUserInfo is asynchronous.
    So you would need to nest them to get it to work.

    Or you can try this, since getUSerInfo allows you to add an array of user ids to get the data for:

    api.listenMqtt((err, event) => {
      if (err) {
        return console.log(err);
      }
    
      if (event.type === "message") {
        const currentUserId = api.getCurrentUserID();
        const senderId = event.senderID;
    
        api.getUserInfo([currentUserId, senderId], (err, ret) => {
          if(err) return console.error(err);
    
          // Ret should contain the two users
          // See: https://github.com/Schmavery/facebook-chat-api/blob/master/DOCS.md#getUserInfo
          console.log(ret);
        });
      }
    });
    

    Nesting user calls method:

    api.listenMqtt((err, event) => {
      if (err) {
        return console.log(err);
      }
    
      if (event.type === "message") {
        let currentUserId = api.getCurrentUserID();
        api.getUserInfo(currentUserId, (err1, signedInUser) => {
          if (err1) {
            return console.log(err);
          }
          api.getUserInfo(event.senderID, (err2, userInMessage) => {
            if (err2) {
              return console.log(err);
            }
    
            console.log(signedInUser, userInMessage)
    
            api.sendMessage("...", event.threadID);
          });
        });
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search