tanvir143-api
v1.0.7
Published
Instagram messaging API with cookie-based account sessions, real-time MQTT messaging, and bot-friendly utilities.
Maintainers
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.txtsupport - JSON array, cookie-object, and
Cookieheader parsing tough-cookiesession 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-apiAuthentication
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:
- Netscape
cookies.txt - JSON cookie arrays
- Cookie objects (
{ sessionid, ds_user_id, ... }) - HTTP
Cookieheader 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:
messagemessage_reactionread_receiptdelivery
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
.envTroubleshooting
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
httpPostAdditional 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)
