npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

tanvir143-api

v1.0.7

Published

Instagram messaging API with cookie-based account sessions, real-time MQTT messaging, and bot-friendly utilities.

Readme

Tanvir143 API


Overview

Tanvir143 API is a Node.js library for Instagram messaging automation using an authenticated Instagram web session. It provides a practical, event-driven interface for account-based messaging, conversation management, user lookups, media sending, reactions, and real-time message events over Instagram's internal messaging infrastructure.

The package is designed around a persistent cookie session, a shared CookieJar, and a real-time MQTT client so that the same authenticated session is reused across HTTP requests and live events.

Important: This package uses Instagram's private/unofficial endpoints and account-session authentication. Instagram can change these endpoints without notice. Use the package only with accounts and permissions you control.

Highlights

  • Cookie-based Instagram account login
  • Netscape cookies.txt support
  • JSON array, cookie-object, and Cookie header parsing
  • tough-cookie session management
  • Authenticated session validation
  • Real-time Instagram MQTT event listener
  • Text and attachment messaging
  • Thread and user information helpers
  • Message reactions, read status, typing indicator, and unsend support
  • Promise and callback-friendly methods throughout the API
  • Configurable user-agent, reconnect, and listener behavior
  • Node.js 14+ runtime support

Installation

npm install tanvir143-api

Authentication

Tanvir143 API authenticates using an Instagram account cookie session. The recommended format is a Netscape cookie file exported as account.txt.

Recommended project layout

your-project/
├── account.txt
├── index.js
├── package.json
└── node_modules/

Login from account.txt

const fs = require('fs');
const login = require('tanvir143-api');

const cookies = fs.readFileSync('./account.txt', 'utf8');

login({ appState: cookies }, (err, api) => {
  if (err) {
    console.error('Login failed:', err.message);
    return;
  }

  console.log('Logged in as:', api.getUserID());
});

Login directly from a cookie string

const login = require('tanvir143-api');

login(`sessionid=YOUR_SESSION_ID; ds_user_id=YOUR_USER_ID; csrftoken=YOUR_CSRF_TOKEN`, (err, api) => {
  if (err) return console.error(err);
  console.log('Login successful:', api.getUserID());
});

Supported cookie formats

The authentication layer accepts:

  1. Netscape cookies.txt
  2. JSON cookie arrays
  3. Cookie objects ({ sessionid, ds_user_id, ... })
  4. HTTP Cookie header strings

A valid account session should include at least sessionid and ds_user_id. The package validates the session against Instagram before exposing the authenticated API.

Real-time Messaging

Once login succeeds, start the MQTT listener:

const fs = require('fs');
const login = require('tanvir143-api');

login({ appState: fs.readFileSync('./account.txt', 'utf8') }, (err, api) => {
  if (err) return console.error(err);

  api.listen((err, event) => {
    if (err) {
      console.error('Listener error:', err.message);
      return;
    }

    console.log('Event:', event);

    if (event.type === 'message' && event.body === 'ping') {
      api.sendMessage('pong!', event.threadID);
    }
  });
});

api.listen() is the primary real-time interface and maps to api.listenMqtt().

To stop the listener:

api.stopListenMqtt();

Message Events

The event system can emit common event types such as:

  • message
  • message_reaction
  • read_receipt
  • delivery

Example:

api.on('message', message => {
  console.log('New message:', message.body);
});

api.on('error', error => {
  console.error('API error:', error.message);
});

Sending Messages

Text

api.sendMessage('Hello from Tanvir143!', threadID, (err, info) => {
  if (err) return console.error(err);
  console.log('Sent:', info);
});

FCA-style object

api.sendMessage({
  body: 'Hello!'
}, threadID);

Attachment

const fs = require('fs');

api.sendMessage({
  body: 'Image',
  attachment: fs.createReadStream('./image.jpg')
}, threadID);

Reply

api.sendMessage(
  'This is a reply.',
  threadID,
  callback,
  originalMessageID
);

Conversation APIs

User information

api.getUserInfo(userID, (err, info) => {
  if (err) return console.error(err);
  console.log(info);
});

Thread information

api.getThreadInfo(threadID, (err, info) => {
  if (err) return console.error(err);
  console.log(info);
});

Thread history

api.getThreadHistory(threadID, 20, null, (err, messages) => {
  if (err) return console.error(err);
  console.log(messages);
});

Thread list

api.getThreadList(20, null, [], (err, threads) => {
  if (err) return console.error(err);
  console.log(threads);
});

Message Controls

// Mark read
api.markAsRead(threadID);

// Typing indicator
const stopTyping = await api.sendTypingIndicator(threadID);
stopTyping();

// Reaction
api.setMessageReaction('❤️', messageID, threadID);

// Unsend/delete message
api.unsendMessage(messageID, threadID);

Group & Thread Utilities

Depending on Instagram-side availability, the API exposes helpers for:

  • Adding/removing participants
  • Admin status management
  • Group image changes
  • Thread title changes
  • Nickname changes
  • Thread color and emoji changes
  • Pin/mute/delete thread helpers
  • Follow/unfriend and user utilities

Availability of individual actions depends on the current Instagram account, conversation type, and Instagram-side API behavior.

Session & Utility Methods

api.getUserID();
api.getCurrentUserID();
api.getAppState();
api.getHeaders();
api.setOptions({ autoReconnect: false });

Logout and listener lifecycle:

api.stopListenMqtt();
api.logout();

Configuration

The login function accepts optional runtime settings:

login({ appState: cookies }, {
  autoReconnect: true,
  listenEvents: true,
  autoMarkDelivery: true,
  autoMarkRead: false,
  updatePresence: false,
  logLevel: 'info'
}, (err, api) => {
  // ...
});

The API also exposes api.setOptions() after login for supported runtime options.

Error Handling

Always handle both login and listener errors:

login({ appState: cookies }, (err, api) => {
  if (err) {
    console.error('[LOGIN]', err.message);
    return;
  }

  api.listen((err, event) => {
    if (err) {
      console.error('[MQTT]', err.message);
      return;
    }

    console.log('[EVENT]', event.type);
  });
});

If login fails, verify that the cookie file is complete, current, and contains a valid sessionid and ds_user_id pair. Expired or revoked Instagram sessions cannot be repaired by the library.

Runtime Requirements

  • Node.js 14 or newer
  • A valid Instagram account session
  • Internet access from the hosting environment
  • Persistent storage when you want to keep exported session data locally

Security Notes

Treat account.txt, sessionid, csrftoken, and related cookie values as passwords.

Do not:

  • Commit account cookies to Git
  • Publish cookies inside issues or chat messages
  • Share a live sessionid
  • Store credentials in client-side/public code

Recommended .gitignore entry:

account.txt
session.json
.env

Troubleshooting

Missing sessionid cookie

Your cookie source does not contain sessionid or it was not parsed correctly. Re-export the account cookies in Netscape format and try again.

Missing ds_user_id cookie

The account cookie set is incomplete. Export a full Instagram cookie set containing ds_user_id.

Session validation fails

The session may be expired, revoked, incomplete, or blocked by Instagram. Export a fresh cookie set and test again.

MQTT connection fails after login

Check that the same authenticated cookie session is still available to the MQTT client and that the host allows persistent outbound WebSocket/TLS connections.

API Surface

The package exposes the following core methods:

login
setOptions
getAppState
getCurrentUserID
getUserID
sendMessage
listen
listenMqtt
stopListenMqtt
getUserInfo
getThreadInfo
getThreadList
getThreadHistory
markAsRead
markAsDelivered
sendTypingIndicator
setMessageReaction
unsendMessage
deleteMessage
changeNickname
changeThreadColor
changeThreadEmoji
setTitle
addUserToGroup
removeUserFromGroup
changeAdminStatus
logout
getHeaders
httpGet
httpPost

Additional helpers are available under the src/ implementation modules.

Project Information

Tanvir143 API

Maintained by Tanvir Ahmed (Tanvir143)
WhatsApp: +8801750079773
GitHub: www.github.com/143tanvir

License

MIT License.

© Tanvir Ahmed (Tanvir143)