HakkaTjakka/facebook-chat-api2

Changes

Opened this issue · 0 comments

Same as the original repo.

I did not managed to get the api.listenMqtt() function to get the messages from a chat.
My solution was to set the following:

    api.setOptions({
        logLevel: "warn",   
        listenEvents: true,
        selfListen: true,
        forceLogin: true
    });

selfListen to true. This way the messages from the chat get to the listen function.

However, because when sending a message to a chat, the listen ALSO will receive those messages.
However by checking the messageID you can check if its the message was send by the user login, because it will be the same.
On sending a message you can get this messageID.

In this example if in a chat somebody says something, which also could be the chatbot, the listen picks it up, and when the messageID is different than the last message send by the chatbot, its NOT the chatbot.
If the messageID is the same, its also a signal that the message was delivered.

When selfListen is set to false or not set, nothing comes in on the listen function, except the type 'presence'.

For me this works...

const fs = require("fs");
const login = require("facebook-chat-api");
//const { execSync } = require('child_process');

let botCredentials = { appState : JSON.parse( fs.readFileSync( 'appstate.json', 'utf-8'))  }

login(botCredentials, (err, api) => {

    if(err) return console.error(err);

//    fs.writeFileSync("appstate.json", JSON.stringify(api.getAppState()));

    var messageID = "";

    api.setOptions({
        logLevel: "warn",   
        listenEvents: true,
        selfListen: true,
        forceLogin: true
    });

    api.listenMqtt((err, message) => {
        if(message) {
            console.log(message);
        }
        if (message.messageID != messageID) {
            if (message.type === "message") {
                api.sendMessage("MAFKLAPPER ZEGT: " + message.body, message.threadID, (err, messageInfo) => {
                    if(err) return console.error(err);
                    messageID = messageInfo.messageID;
                    console.log("messageID=" + messageID);
                });
            }
        } else {
            console.log("messageID=" + messageID + " recieved ok!");
        }
    });
});