Giter VIP home page Giter VIP logo

instagram_mqtt's Introduction

Instagram Realtime and FBNS

This library isn't actively maintained anymore. Only bug fixes are accepted.

Getting started

  • Install the library

    npm i instagram_mqtt
  • Extend the IgApiClient

    import { value IgApiClient } from 'instagram-private-api';
    import { value withFbnsAndRealtime, value withFbns, value withRealtime } from 'instagram_mqtt';
    
    // wrap the client
    // ig is now IgApiClientMQTT for typescript users
    const ig = withFbnsAndRealtime(new IgApiClient());
    
    // OR if you only want fbns/realtime
    const igFbns = withFbns(new IgApiClient());
    const igRealtime = withRealtime(new IgApiClient());
    
    // login like you usually do or load the state
    
    // use ig.realtime and ig.fbns
  • Look at the examples

RealtimeClient

The RealtimeClient is used, as the name implies, for in-app communication. Everything using some kind of event is communicating over this client.

Features

  • Typing Events
  • Presence Events
  • Direct Messaging
  • Live Comments
  • Live Events

Events

Your IDE should be able to auto complete the event names for you as Typescript types are in the npm package.

Name Description Typed?
realtimeSub Any message sent to /ig_realtime_sub partially
direct Direct events yes
iris Any message sent to /ig_message_sync not handled by message partially
message Direct messages yes
clientConfigUpdate Updates to quick experiments (may cause the client to disconnect) yes
appPresence Presence updates yes
<keyof QueryIDs> Messages regarding the specified query id no

FbnsClient

FBNS is for notifications (so it's readonly). You can subscribe to any notification using

ig.fbns.on('push' /* your handler */);

You can subscribe to a specific event using

ig.fbns.on(/* desired collapseKey */, /* your handler */)

Note: this library provides the query (actionPath/Params) as an object (actionParams) so you can use actionParams.YOUR_KEY.

Debugging

In order to debug the clients you can set the environment variable DEBUG. Recommended is setting it to ig:mqtt:*. If you want to debug the entire instagram-private-api, set it to ig:*. Currently, the emitted "channels" are:

  • ig:mqtt:realtime
  • ig:mqtt:fbns
  • ig:mqtt:mqttot

If you want to debug the mqtts library set it either to * or ig:*,mqtts:*.

An example .env file would look like this:

DEBUG=ig:mqtt:*

Extending

Mixins

Since version 1.0, there is support for basic mixins. A mixin is a class with an apply() method (extends Mixin base class). This method is called once the RealtimeClient is constructed. You can use the hook() function to hook into methods (pre and post) and override the return value. By default, the MessageSyncMixin and the RealtimeSubMixin are used.

TODO

  • Proper descriptions for events
  • Error handling
  • Testing... a lot.

Research

All scripts to research the mqtt client are in the /frida/ directory. As the name suggests, you'll need frida for this.

Start frida and connect to the process:

# assume frida is running on remote device...

frida -U -n com.instagram.android -l PATH_TO_SCRIPT

# com.instagram.threadsapp is also valid
Script Description
mqttListen.js Prints all outgoing Realtime-MQTT messages

Architecture

MQTToT

MQTToT is the underlying connection. It uses a modified version of MQTT 3. The modifications are small, but (at least for javascript) may not work with regular MQTT libraries (or at least without core modification).

Changes

  • The connect packet doesn't contain a clientId. Instead, it contains a zipped thrift-payload. The flags are set to contain a username and password which are in the payload and not as strings in the packet.
  • The connack packet can contain a payload. Regular clients would throw an error as the remaining length should be equal to 0 but in this case it's intended (the MQTT 3 standard doesn't specify a payload).

RealtimeClient

In earlier versions, the realtime client used an old method (built on the MQTT standard) to connect (it's still being used in mgp25's library), but thr RealtimeClient is using MQTToT to connect. In contrast to FBNS it doesn't use a device-auth, it uses cookie-auth as it was the case with the old method.

The RealtimeClient communicates on different MQTT-Topics 8most of the time one for requesting and one for a response).

FbnsClient

FBNS uses MQTToT to connect with a device-auth. A successful auth will return a payload in the CONNACK packet with values used for future connections. And a response containing a token, that gets sent to an instagram api endpoint (/api/v1/push/register/), is sent to /fbns_reg_resp. This completes the auth.

Now, push notifications are sent to /fbns_msg.

Collaborating

Setting up the environment

If you're using x86, make sure to install ARM translations for yor device in order to get ProxyDroid to work.

Instructions are here.

Thanks

Thanks to valga for providing and maintaining the PHP library. This library integrates with the instagram-private-api.

instagram_mqtt's People

Contributors

andresespinosapc avatar debanjan-san avatar dependabot-preview[bot] avatar dependabot[bot] avatar f0rr0 avatar nerixyz avatar thenekochan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

instagram_mqtt's Issues

How to get Receiver Information on direct Messages

Hey Everyone,

I am facing a problem while using multiple accounts is that when a new message receives i don't know which account belongs to this message. I have message data as follows

{ event: 'patch',
  message_type: 1,
  seq_id: 1035,
  mutation_token: '8217812-21121-1221-3133-1213314411',
  realtime: true,
  message:
   { path:
      '/direct_v2/threads/87218787218721721878721/items/7832878728737327972792397',
     op: 'add',
     thread_id: '87218787218721721878721',
     item_id: '7832878728737327972792397',
     user_id: 12345678910,
     timestamp: 1596013005121808,
     item_type: 'text',
     text: 'This is maessage',
     client_context: '76126-212121-1212-122112-21324214',
     show_forward_attribution: false,
     is_shh_mode: false } }

Thanks You
@Nerixyz @TheNeKochan

write EPIPE app crash

 events.js:292
       throw er; // Unhandled 'error' event
       ^

 Error: write EPIPE
     at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:92:16)
     at handleWriteReq (internal/stream_base_commons.js:51:26)
     at writeGeneric (internal/stream_base_commons.js:143:15)
     at TLSSocket.Socket._writeGeneric (net.js:786:11)
     at TLSSocket.Socket._write (net.js:798:8)
     at doWrite (_stream_writable.js:403:12)
     at clearBuffer (_stream_writable.js:542:7)
     at onwrite (_stream_writable.js:454:7)
     at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:101:10)
 Emitted 'error' event on TLSSocket instance at:
     at errorOrDestroy (internal/streams/destroy.js:108:12)
     at TLSSocket.onerror (_stream_readable.js:753:7)
     at TLSSocket.emit (events.js:315:20)
     at TLSSocket.EventEmitter.emit (domain.js:482:12)
     at emitErrorNT (internal/streams/destroy.js:92:8)
     at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
     at processTicksAndRejections (internal/process/task_queues.js:84:21) {
   errno: 'EPIPE',
   code: 'EPIPE',
   syscall: 'write'
 }

I receive error like this, and it crashes my app. Where I need to make error handler for this?
@Nerixyz

how to connect to the web

Could you tell me how to make a connection to the web socket that is used in the web version of instagram wss: //edge-chat.instagram.com/chat. When I try to establish a connection using ws, a 502 response is received.

2��/ig_send_message�{"client_context":"555","device_id":"D3","action":"indicate_activity","thread_id":"340282366841710300949128139948363445088","activity_status":0}

2��/ig_send_message�{"client_context":"555","device_id":"D3","action":"send_item","item_type":"text","mutation_token":"555","text":"test\n","thread_id":"340282366841710300949128139948363445088"}

Sometimes data comes in the form

kAMADgA=

Legal question

Hello ,
Using libraries such as this library that are making reverse engineering on instagram is legal ? can we make applications for our customers using these libraries or not ?

thanks

Invalid state requested

I sometimes get this error:

(node:60) Error: Invalid state requested (current: 3, requested: 3)
    at MQTToTClient.next (/usr/ig_chatbot/node_modules/instagram_mqtt/node_modules/mqtts/src/mqtt.base-client.ts:61:19)
    at MQTToTClient.setDisconnected (/usr/ig_chatbot/node_modules/instagram_mqtt/node_modules/mqtts/src/mqtt.base-client.ts:100:14)
    at MQTToTClient.setDisconnected (/usr/ig_chatbot/node_modules/instagram_mqtt/node_modules/mqtts/src/mqtt.client.ts:408:15)
    at /usr/ig_chatbot/node_modules/instagram_mqtt/node_modules/mqtts/src/mqtt.client.ts:210:28
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

I don't know how to reproduce it yet, but I'm trying to.

Have anyone got this error too?

Experiencing breakages in other packages based on Instagram API

Hi.

As Instagram moves closer to completely shutting off access to its public API endpoints, I am experiencing breakages in some of the other packages that relied on the Instagrams API, such as 'Instagram-profile-picture'. It's now dead.

Is this currently package experiencing any problems or downtime? Will it possibly experience any problems once Instagram's hard cut-off date of March 31st arrives?

How can I listen to multiple accounts?

Hi all,

I want to listen to messages sent to multiple accounts. The method below works but I'm not sure it's the right solution.

const ig = withRealtime(new IgApiClient());
const ig2 = withRealtime(new IgApiClient());

ig.realtime.on('message', (data) => console.log(data));
ig2.realtime.on('message', (data) => console.log(data));

What could be your solution for connecting to 10 separate accounts? How do I refactor this code?

Not getting message reply data

I'm not receiving text replies when new direct messages arrive through realtime. I have already upgraded the APP_VERSION in the instagram-private-api package and I receive these messages when requesting them from there.

Here's my code:

const ig = withRealtime(new IgApiClient());
ig.realtime.on('message', data => console.log(data));
await ig.realtime.connect({ irisData: await ig.feed.directInbox().request() });

Listen for new messages in cli script - patch event

I'm using this code into a cli script to listen for new messages:

const { IgApiClient } = require('instagram-private-api');
const { withRealtime } = require('instagram_mqtt');
const chalk = require('chalk');
const ora = require('ora');

const ig = withRealtime(new IgApiClient());
ig.state.generateDevice(process.env.IGUSER);

( async () => {
    await ig.simulate.preLoginFlow();
    await ig.account.login(process.env.IGUSER, process.env.IGPASS);
    
    ora({
        color: 'magenta', 
        text: chalk.magenta(`Listening for incoming messages\n`)
    }).start();

    await ig.realtime.connect({ irisData: await ig.feed.directInbox().request() });
// using setInterval to mantain the script running
    setInterval( () => {}, 1000);

    ig.realtime.on('message', (message) => console.log(message) );

})();

I'm not suer if I'm doing it in the right way. I have two question about this library.

  1. Is necessary to call the ig.realtime.connect({ irisData: await ig.feed.directInbox().request() }); method to listen for new messages?

  2. Is this the right method to get new messages from DM inbox?

 ig.realtime.on('message', (message) => console.log(message) );

In my console log I've found this log about an event, but it's not a new message., why it will be logged from the on('message') event listener?

{
 event: 'patch',
 message_type: 1,
 seq_id: 3016,
 mutation_token: '6779103590224992045',
 realtime: true,
 message: {
   path: '/direct_v2/threads/340282366841710300949128156071872279562/participants/7285039631/has_seen',
   op: 'replace',
   thread_id: '340282366841710300949128156071872279562',
   item_id: '29814791532328000641606257215537152',
   client_context: '',
   timestamp: 1616264245837932,
   created_at: 1616263087577622,
   shh_seen_state: {}
 }

problem with fbns_msg topic

Hello. I had trouble implementing mqtt to receive notifications. This problem has nothing to do with your library, and I make a issue so in the hope that you will have an answer for me.
I did all the steps correctly and did the Push Register with token and got the right answer, but I don't get the notifications.
Do you have any idea how I can fix this problem?

I didn't use your library because I wanted to implement it for ios/android platform

Skip patch event notification

Using the message event, is possible to skip notifications about patch events? Is there any code example?

I'm trying with this code but not sure if will work as expected:

    ig.realtime.on('message', (message) => { 
       if(  message.event === 'patch' ){
          return;
       }
       ....
    });

Is there any documentations about the events that are provided with message object? How is the correct way to get informations about the thread and the users that is emitting the patch event?

Error: Cannot find module 'node-cint64'

Hi,

I just installed this repo using
npm install instagram_mqtt

but i'm getting this error : Cannot find module 'node-cint64'

node version: v12.13.1

package.json:

  "dependencies": {
    "bluebird": "^3.7.1",
    "inquirer": "^7.0.0",
    "instagram-private-api": "^1.33.0",
    "instagram_mqtt": "^0.1.7"
  }

Note: still didn't do anything with library just requiring it throw this error

Problem by module re2

i can't get the instagram_mqtt module to install correctly. when i do npm install it freezes with this message

> [email protected] install /home/n01pham/Desktop/insta-api/fbns/node_modules/re2
> install-from-cache --artifact build/Release/re2.node --host-var RE2_DOWNLOAD_MIRROR || npm run rebuild

Trying https://github.com/uhop/node-re2/releases/download/1.15.9/linux-x64-83.br ...

My operating system is Ubuntu 18.04.

Client network socket disconnected before secure TLS connection

Have you seen this kind of error before?

ERROR	Error: Client network socket disconnected before secure TLS connection was established
    at connResetException (internal/errors.js:570:14)
    at TLSSocket.onConnectEnd (_tls_wrap.js:1361:19)
    at Object.onceWrapper (events.js:299:28)
    at TLSSocket.emit (events.js:215:7)
    at TLSSocket.EventEmitter.emit (domain.js:476:20)
    at endReadableNT (_stream_readable.js:1183:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'ECONNRESET',
  path: undefined,
  host: 'edge-mqtt.facebook.com',
  port: 443,
  localAddress: undefined
}

ConnectionFailedError while trying to login the client

For me the repo somehow stopped working. I have multiple bots running and all of them consistently show the following error when trying to log in:

(node:27822) UnhandledPromiseRejectionWarning: ConnectionFailedError: CONNACK returnCode: 3 errorName: Server unavailable
at Object.next (/home/dcts/code/insta.js/node_modules/instagram_mqtt/dist/mqttot/mqttot.client.js:72:23)
at MQTToTClient.continueFlows (/home/dcts/code/insta.js/node_modules/mqtts/dist/mqtt.client.js:212:104)
at MQTToTClient.handlePacket (/home/dcts/code/insta.js/node_modules/mqtts/dist/mqtt.client.js:291:19)
at /home/dcts/code/insta.js/node_modules/mqtts/dist/mqtt.client.js:247:43
at Array.forEach ()
at MQTToTClient.parseData (/home/dcts/code/insta.js/node_modules/mqtts/dist/mqtt.client.js:247:25)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:27822) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:27822) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Cannot connect from different IP's at the same time

When I connect to realtime, then I connect with the same account (different sessions) from a different IP, I get disconnected from the other session. The error I get is ClientDisconnectedError: MQTToTClient got disconnected.

When I say different IP I really mean it, I'm doing it from localhost and a Heroku server.

What could make Instagram think I'm connecting from the same place or something like that? Maybe some header or device information that is the same for both connections.

Unfortunately, still an issue with module 'chance'

I have been able to set everything successfully, until I go into my serverless infrastructure. I am hoping that you could help me figure out what could be the cause.

{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module 'chance'",
    "trace": [
        "Runtime.ImportModuleError: Error: Cannot find module 'chance'",
        "    at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:45:30)",
        "    at Module._compile (internal/modules/cjs/loader.js:778:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
        "    at Module.load (internal/modules/cjs/loader.js:653:32)",
        "    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
        "    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)",
        "    at startup (internal/bootstrap/node.js:283:19)"
    ]
}

Error while connecting fnbs for a second time for the same account

I am using this commands to stop my Instagram class instance

async stopInstagram() {
   await this.ig.realtime?.direct?.sendForegroundState({ inForegroundApp: false, inForegroundDevice: false, keepAliveTimeout: 900 })
   return this.ig.destroy()
}

But i could not find a way to stop fbns.

Then I try to create a new instance for the same account I connect once again and get this error (using version 0.1.13)

Cannot read property 'toString' of undefined
    at MQTToTClient.<anonymous> (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\instagram_mqtt\src\fbns\fbns.client.ts:283:39) ...

This refers to this code if Im not mistaken

this.client.on('mqttotConnect', async (res) => {
            _fbnsDebug('Connected to MQTT');
            const payload = res.payload.toString('utf8');
...

So I logged the res object this is how it looks:

ConnectResponsePacket {
  packetFlags: 0,
  remainingPacketLength: 2,
  _packetType: 2,
  _flags: 0,
  _returnCode: 2
}

Any ideas how to fix it? Maybe stop fnbs somehow?

Proper way to keep subscriptions working over extended periods of time

During some initial testing (using 0.1.17 version) a noticed that after some time (10-12 hours) realtime subscription (Im using only one) started working slowly, and fbns stopped working at all.
So the idea was to reconnect them after some time. I settle upon around 4-5 hours. It worked fine but after a day or so of heavy use i got this error:

"message": "Got warning in fbns sub",
  "warning": {
    "code": "ERR_STREAM_DESTROYED",
    "name": "Error",
    "message": "Cannot call write after a stream was destroyed",
    "stack": "Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed\n    at doWrite (_stream_writable.js:431:19)\n    at writeOrBuffer (_stream_writable.js:419:5)\n    at TLSSocket.Writable.write (_stream_writable.js:309:11)\n    at MQTToTClient.writePacketToSocket (/usr/backend/node_modules/instagram_mqtt/src/mqtt/mqtt.client.ts:237:21)\n    at MQTToTClient.handleSendingFlows (/usr/backend/node_modules/instagram_mqtt/src/mqtt/mqtt.client.ts:217:22)\n    at MQTToTClient.startFlow (/usr/backen [ ...... ] /mqtt/mqtt.client.ts:238:27\n    at processTicksAndRejections (internal/process/task_queues.js:80:21) [ long string, total length = 552638 ]"
  },

I consider that as a dead subscription so right after that I call

await this.ig.fbns.disconnect()
await this.ig.fbns.connect();

I already saw this portion of code work as intended but this time it followed with these bad boys:

"error": {
    "name": "RangeError",
    "message": "Maximum call stack size exceeded",
    "stack": "RangeError: Maximum call stack size exceeded\n    at MQTToTClient.<anonymous> (/usr/backend/node_modules/instagram_mqtt/src/mqttot/mqttot.client.ts:27:71)\n    at MQTToTClient.emit (events.js:228:7)\n    at MQTToTClient.EventEmitter.emit (domain.js:475:20)\n    at MQTToTClient.MqttClient.emitWarning (/usr/backend/node_modules/instagram_mqtt/src/mqtt/mqtt.client.ts:88:52)\n    at MQTToTClient.startFlow (/usr/backend/node_modules/instagram_mqtt/src/mqtt/mqtt.client.ts:170:18)\n    at MQTToTClient.discon [ ...... ] /mqtt/mqtt.client.ts:238:27\n    at processTicksAndRejections (internal/process/task_queues.js:80:21) [ long string, total length = 561814 ]"
  },

"error": {
    "name": "RangeError",
    "message": "Maximum call stack size exceeded",
    "stack": "RangeError: Maximum call stack size exceeded\n    at new PacketFlow (/usr/backend/node_modules/instagram_mqtt/src/mqtt/flow/packet-flow.ts:33:5)\n    at new OutgoingDisconnectFlow (/usr/backend/node_modules/instagram_mqtt/src/mqtt/flow/outgoing.disconnect.flow.ts:10:9)\n    at MQTToTClient.disconnect (/usr/backend/node_modules/instagram_mqtt/src/mqtt/mqtt.client.ts:132:31)\n    at FbnsClient.disconnect (/usr/backend/node_modules/instagram_mqtt/src/fbns/fbns.client.ts:317:28)\n    at Instagram._callee [ ...... ] al/streams/destroy.js:60:3)\n    at processTicksAndRejections (internal/process/task_queues.js:81:21) [ long string, total length = 550309 ]"
  },

"error": {
    "name": "RangeError",
    "message": "Maximum call stack size exceeded",
    "stack": "RangeError: Maximum call stack size exceeded\n    at new Context (/usr/backend/node_modules/regenerator-runtime/runtime.js:427:5)\n    at Object.wrap (/usr/backend/node_modules/regenerator-runtime/runtime.js:23:19)\n    at Instagram._callee19 (/usr/backend/src/instagramAPI/instagram.js:1072:35)\n    at /usr/backend/src/instagramAPI/instagram.js:32:151\n    at new Promise (<anonymous>)\n    at Instagram.<anonymous> (/usr/backend/src/instagramAPI/instagram.js:32:97)\n    at Instagram.stopFbns (/usr/backe [ ...... ] /mqtt/mqtt.client.ts:238:27\n    at processTicksAndRejections (internal/process/task_queues.js:80:21) [ long string, total length = 560905 ]"
  },

stopFbns() - function that just calls await this.ig.fbns.disconnect()
after thar i got flooded with these errors:

"error": {
    "code": "EPIPE",
    "name": "Error",
    "message": "This socket has been ended by the other party",
    "stack": "Error: This socket has been ended by the other party\n    at TLSSocket.writeAfterFIN [as write] (net.js:447:14)\n    at MQTToTClient.writePacketToSocket (/usr/backend/node_modules/instagram_mqtt/src/mqtt/mqtt.client.ts:237:21)\n    at MQTToTClient.handleSendingFlows (/usr/backend/node_modules/instagram_mqtt/src/mqtt/mqtt.client.ts:217:22)\n    at MQTToTClient.startFlow (/usr/backend/node_modules/instagram_mqtt/src/mqtt/mqtt.client.ts:155:22)\n    at MQTToTClient.registerClient (/usr/backend/node_modules/instagram_mqtt/src/mqttot/mqttot.client.ts:38:28)\n    at Timeout._onTimeout (/usr/backend/node_modules/instagram_mqtt/src/mqttot/mqttot.client.ts:46:18)\n    at listOnTimeout (internal/timers.js:531:17)\n    at processTimers (internal/timers.js:475:7)"
  },

 "error": {
    "name": "IgResponseError",
    "message": "POST /api/v1/push/register/ - 400 Bad Request; failed to acquire pushlock",
    "stack": "IgResponseError: POST /api/v1/push/register/ - 400 Bad Request; failed to acquire pushlock\n    at Request.handleResponseError (/usr/backend/node_modules/instagram-private-api/src/core/request.ts:161:12)\n    at Request.send (/usr/backend/node_modules/instagram-private-api/src/core/request.ts:78:24)\n    at FbnsClient.sendPushRegister (/usr/backend/node_modules/instagram_mqtt/src/fbns/fbns.client.ts:374:26)\n    at FbnsClient.handleMessage (/usr/backend/node_modules/instagram_mqtt/src/fbns/fbns.client.ts:334:21)"
  },

Unfortunatly, i did not have debug running, so this is the info i can provide
This happend in between my reconnect period so after 3 hours all came back to normal.

That could be the cause of such behavior? Is this even the right way to keep subscriptions working?

Mqtt client tries to connect nonstop

Occasionally there is a problem with realtime subscription - it starts spamming EPIPE errors consuming the processor time. Safe disconnect does not work. It happens with fbns too, but extremely rarely the ratio is like 1 to 25.

Is there any way i can just stop listening to incoming packets then this happens? And is it okay to just create a new connection over the old one?

I do not think i can provide the logs on the situation tho. The problem is random so i cant just separate one account like i did last time and the logs from many accounts comsume too much resources.

Is there support for direct messages with post content?

Now when I receive a message with a post content, I get the following error

Error: Expected flags 0 but got 2
    at DisconnectRequestPacket.assertPacketFlags 
    at DisconnectRequestPacket.read 
   at tryCatcher
    at Function.Promise.attempt.Promise.try 
    at MqttParser.parse
    at async MQTToTClient.handleData

Can anyone help me with this issue please?

"Expected flags 2 but got X" error crashes node

This error randomly occurs for 1-2 times a day for one particular instagram account.
X stands for some number, Ive seen 3, 8, 9, 10, 13 so far. So here is the error itself:

"error": {
    "name": "Error",
    "message": "Expected flags 2 but got 3",
    "stack": "Error: Expected flags 2 but got 3
    at UnsubscribeRequestPacket.assertPacketFlags (/usr/backend/node_modules/mqtts/src/mqtt.packet.ts:73:19)
    at UnsubscribeRequestPacket.read (/usr/backend/node_modules/mqtts/src/packets/unsubscribe.request.packet.ts:26:14)
    at /usr/backend/node_modules/mqtts/src/mqtt.parser.ts:102:28
    at tryCatcher (/usr/backend/node_modules/bluebird/js/release/util.js:16:23)
    at Function.Promise.attempt.Promise.try (/usr/backend/node_modules/bluebird/js/release/method.js:39:29)
    at MqttParser.parse (/usr/backend/node_modules/mqtts/src/mqtt.parser.ts:101:35)
    at MQTToTClient.parseData (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:251:29)"
  }

After that there is some combination of these two errors:

"error": {
    "name": "Error",
    "message": "Unexpected packet: TYPE_PUBREC",
    "stack": "Error: Unexpected packet: TYPE_PUBREC
    at MQTToTClient.handlePacket (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:297:40)
    at /usr/backend/node_modules/mqtts/src/mqtt.client.ts:253:43
    at Array.forEach (<anonymous>)
    at MQTToTClient.parseData (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:253:25)
    at runNextTicks (internal/process/task_queues.js:59:5)
    at processImmediate (internal/timers.js:412:9)
    at process.topLevelDomainCallback (domain.js:130:23)"
  }
"error": {
    "name": "Error",
    "message": "Unexpected packet: TYPE_SUBSCRIBE",
    "stack": "Error: Unexpected packet: TYPE_SUBSCRIBE
    at MQTToTClient.handlePacket (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:297:40)
    at /usr/backend/node_modules/mqtts/src/mqtt.client.ts:253:43
    at Array.forEach (<anonymous>)
    at MQTToTClient.parseData (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:253:25)
    at runNextTicks (internal/process/task_queues.js:59:5)
    at processImmediate (internal/timers.js:412:9)
    at process.topLevelDomainCallback (domain.js:130:23)"
  }

After error from above occur several times thie error comes out

"error": {
    "code": "EPIPE",
    "name": "Error",
    "message": "This socket has been ended by the other party",
    "stack": "Error: This socket has been ended by the other party
    at TLSSocket.writeAfterFIN [as write] (net.js:447:14)
    at TlsTransport.send (/usr/backend/node_modules/mqtts/src/transport/tls.transport.ts:8:21)
    at MQTToTClient.sendPacket (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:246:24)
    at MQTToTClient.startFlow (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:197:25)
    at MQTToTClient.handlePacket (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:264:22)
    at /usr/backend/node_modules/mqtts/src/mqtt.client.ts:253:43
    at Array.forEach (<anonymous>)
    at MQTToTClient.parseData (/usr/backend/node_modules/mqtts/src/mqtt.client.ts:253:25)
    at runNextTicks (internal/process/task_queues.js:59:5)
    at processImmediate (internal/timers.js:412:9)
    at process.topLevelDomainCallback (domain.js:130:23)"
  }

And node crashes getting this error:

"error": {
    "cause": {
      "errno": -3,
      "code": "Z_DATA_ERROR",
      "name": "Error",
      "message": "invalid distance too far back",
      "stack": "Error: invalid distance too far back\n    at Zlib.zlibOnError [as onerror] (zlib.js:170:17)"
    },
    "isOperational": true,
    "errno": -3,
    "code": "Z_DATA_ERROR",
    "name": "Error",
    "message": "invalid distance too far back",
    "stack": "Error: invalid distance too far back\n    at Zlib.zlibOnError [as onerror] (zlib.js:170:17)"
  }

Any idea what could be the reason and how to avoid these errors or at least crashes?

Subscribe event?

Hey. First of all, thank you very much for the work you have done, without which I don't know what I would have done 😁
I want to know if it's possible to have a subscribe event when someone starts following you. Actually, I make one request every 5 seconds to compare cache and Instagram values (I check if there is a new person in the followers array). But it will be better to have mqtt support for this feature.
Is it possible actually? Or is it planned?
Thanks again, I don't know how to thank you.

Does the lib work?

Hi.
I launched the main.ts file with my credentials and only message that I receive is:
/t_region_hint [ "FRC" ]
So when any activity is going on my account, I do not receive notifications.
Notifications are enabled and I receive them on my phone.

Can you give any feedback?

Realtime not binding to local address.

In IgApiClient I'm binded to a local address of a hotspot I have, which works as expected.
ig.request.defaults.localAddress = x.x.x.x
Though, ig.realtime.connect({...}) doesn't seem to use that address.

Random issue occurs

I have seen this error occur randomly a few times and working fine for weeks. I am unable to pin point the cause. Any Ideas? Have you seen this before?

Error: This socket has been ended by the other party
at TLSSocket.writeAfterFIN [as write] (net.js:396:12)
at MQTToTClient.writePacketToSocket (/usr/src/app/node_modules/instagram_mqtt/dist/mqtt/mqtt.client.js:179:21)(/usr/src/app/node_modules/instagram_mqtt/dist/mqtt/mqtt.client.js:160:22)
at MQTToTClient.startFlow (/usr/src/app/node_modules/instagram_mqtt/dist/mqtt/mqtt.client.js:96:22)

Using library

Hello,
Sorry to ask stupid question but I'm newbie in node js

I have downloaded the source and Installed modules and using tsc example.ts in command line I have compiled example file 'ts' to ' js' , but when I execute this file using 'node example' I face this error :


(node:3284) UnhandledPromiseRejectionWarning: TypeError: Class constructor IgApiClient cannot be invoked without 'new'
    at new IgApiClientExt (C:\nodejs\realTime\src\extend.js:59:28)
    at assertClient (C:\nodejs\realTime\src\extend.js:176:16)
    at Object.withRealtime (C:\nodejs\realTime\src\extend.js:168:14)
    at C:\nodejs\realTime\realts.js:48:28
    at step (C:\nodejs\realTime\realts.js:33:23)
    at Object.next (C:\nodejs\realTime\realts.js:14:53)
    at C:\nodejs\realTime\realts.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (C:\nodejs\realTime\realts.js:4:12)
    at C:\nodejs\realTime\realts.js:43:23
    at Object.<anonymous> (C:\nodejs\realTime\realts.js:119:7)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11
(node:3284) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3284) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I know it is stupid question but I need some help to work on this project , thanks

Error: MQTToTClient got disconnected

The library is working fine and I appreciate you , but when I connect using command line windows with command

ts-node example.ts

first every thing works fine and all events are printing , but after about one minute I face error

Error: MQTToTClient got disconnected

Please see this image is taken from command line
https://prnt.sc/qxvzji

thanks

[REQUEST] Instagram client version update

Hey, basically when receiving media such as reels in dm I figured out that I was just receiving a message with that text in it “Download the most recent update to view this message”. May you update the client version to the latest one (if possible)? Thanks!

Consistent fbns fail

When calling fbns.connet() there is and unhandeled error and fbns fails to connect. This is consistent and happens every time, but not with every account. Started seeing such behavior 1 day ago.
Here are the logs. Just for sience tried using code from example - same result

ig:state Deserializing state of type object +0ms
  ig:state Deserializing cookies, supportedCapabilities, language, timezoneOffset, radioType, capabilitiesHeader, connectionTypeHeader, isLayoutRTL, adsOptOut, thumbnailCacheBustingValue, clientSessionIdLifetime, pigeonSessionIdLifetime, deviceString, deviceId, uuid, phoneId, adid, build, igWWWClaim, passwordEncryptionKeyId, passwordEncryptionPubKey, authorization +22ms
  ig:request Requesting GET /api/v1/direct_v2/get_presence/ +0ms
  ig:mqtt:fbns Connecting to FBNS... +0ms
  ig:mqtt:fbns Constructing connection +2ms
  ig:mqtt:mqttot mqtt-mini.facebook.com:443: Creating client +0ms
  mqtt:client Connecting... +0ms
  mqtt:client:packet Sent MQTToTConnectRequestPacket +0ms
  mqtt:client:packet Received ConnectResponsePacket +114ms
  mqtt:client Connected! +152ms
  ig:mqtt:fbns Connected to MQTT +176ms
  mqtt:client Starting keep-alive-ping {delay: 59.5} +26ms
  mqtt:client:packet Sent SubscribeRequestPacket id: 1 topic: 76 +35ms
unhandledRejection TypeError: Cannot read property 'toString' of undefined
    at SafeSubscriber._next (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\instagram_mqtt\src\fbns\fbns.client.ts:102:41)
    at SafeSubscriber.__tryOrUnsub (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\mqtts\node_modules\rxjs\src\internal\Subscriber.ts:265:10)    
    at SafeSubscriber.next (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\mqtts\node_modules\rxjs\src\internal\Subscriber.ts:207:14)
    at Subscriber._next (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\mqtts\node_modules\rxjs\src\internal\Subscriber.ts:139:22)
    at Subscriber.next (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\mqtts\node_modules\rxjs\src\internal\Subscriber.ts:99:12)
    at Subject.next (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\mqtts\node_modules\rxjs\src\internal\Subject.ts:70:17)
    at MQTToTClient.handlePacket (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\mqtts\src\mqtt.client.ts:305:31)
    at C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\mqtts\src\mqtt.client.ts:292:43
    at Array.forEach (<anonymous>)
    at MQTToTClient.parseData (C:\Users\mi\Documents\repos\channels-manager-instagram\node_modules\mqtts\src\mqtt.client.ts:292:25)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

the raw res in this.client.$connect.subscribe callback :

ConnectResponsePacket {
  packetFlags: 0,
  remainingPacketLength: 2,
  _packetType: 2,
  _flags: 0,
  _returnCode: 2
}

Something chaneged on isntagram's side?

not getting notification when new follower follow me

I want to receive notification when new follower follow my account but it doesn't seem working
this is my code :

// auth 
  ig.fbns.on("push", logEvent("push"));

  ig.fbns.on("message", logEvent("message"));

  ig.fbns.on("new_follower", notification => {
    console.log("new_follower", notification);
  });
  await ig.fbns.connect();

btw : I am able to receive notification when someone dm me

Examples not working

I tried to run the push example.

  1. I cloned the repository and installed dependencies.
  2. Created .env file (which contains my instagram id and password) in root and examples folders.
  3. Installed ts-node and added a new script in package.json.
    "push": "ts-node examples/push.example"
  4. Run npm run push

I get following error:

(node:60944) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at FbnsDeviceAuth.read (/Users/dev/Downloads/instagram_mqtt-master/src/fbns/fbns.device-auth.ts:36:49)
    at Object.onImport (/Users/dev/Downloads/instagram_mqtt-master/src/extend.ts:60:83)
    at IgApiClientExt.importState (/Users/dev/Downloads/instagram_mqtt-master/src/extend.ts:29:28)
(node:60944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:60944) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Can anyone help me with this issue please?

subscription parameters in java

I implemented this api in the Java project

In the
graphql.subscription
And
skywalker.subscriptio

**I have a problem and I do not receive any notifications from these parts.

I wanted the parameters sent in this section.
Thanks**

Can we receive live direct chat requests ?

Hey Every one, i am building a chat bot service and want to get direct chat requests and approve them so that i can receive messages smoothly ? is there any way ?

What i know is that, direct requests can be get using ig.feed.directPending().items()
@Nerixyz @TheNeKochan

TypeError: Object.fromEntries is not a function

Hello. I'm trying to run the code from the example:

import { IgApiClient } from 'instagram-private-api';
import { withFbnsAndRealtime, withFbns, withRealtime } from 'instagram_mqtt';

// wrap the client
// ig is now IgApiClientMQTT for typescript users
const ig = withFbnsAndRealtime(new IgApiClient());
console.log("init ");

But I get a mistake:

.../node_modules/mqtts/dist/mqtt.constants.js:21
const reverseMapping = Object.fromEntries(Object.entries(PacketType).map(([k, v]) => [v, k]));
                              ^

TypeError: Object.fromEntries is not a function

What to do and how to fix?

typeof EventEmitter error when building with TypeScript

I am getting this error whenever I try to build my code using TypeScript:

node_modules/instagram_mqtt/dist/fbns/fbns.client.d.ts:7:41 - error TS2507: Type 'typeof EventEmitter' is not a constructor function type.

This may be related to this and I think it only happens if you are using (or a package have a dependency of) @types/node > 13.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.