Complete Instagram MQTT protocol with FULL iOS + Android support. 33 device presets (21 iOS + 12 Android). iPhone 16/15/14/13/12, iPad Pro, Samsung, Pixel, Huawei. Real-time DM messaging, view-once media extraction, sub-500ms latency.
npm install nodejs-insta-private-apiDear users,
First of all, when handling view-once images or videos, please make sure to save the received media in a folder such as /storage/emulated/0/Pictures/, or depending on your device's path. The photos and videos are saved correctly on your phone, but the library currently has some issues with uploading them back to Instagram. This will be resolved as soon as possible.
I post many versions of the project because Instagram changes the protocol almost daily, if you like this project leave a star on github https://github.com/Kunboruto20/nodejs-insta-private-api.git
This project implements a complete and production-ready MQTT protocol client for Instagram's real-time messaging infrastructure. Instagram uses MQTT natively for direct messages, notifications, and real-time presence updates. This library replicates that exact implementation, allowing developers to build high-performance bots and automation tools that communicate with Instagram's backend using the same protocol the official app uses.
By leveraging MQTT instead of Instagram's REST API, this library achieves sub-500ms message latency, bidirectional real-time communication, and native support for notifications, presence tracking, and thread management. The implementation is reverse-engineered from Instagram's mobile app protocol and tested extensively for reliability and compatibility.
- NEW: FULL iOS SUPPORT - iPhone 16/15/14/13/12 + iPad Pro/Air device emulation
- NEW: FULL ANDROID SUPPORT - Samsung, Huawei, Google Pixel, OnePlus, Xiaomi, OPPO
- NEW: 33 Preset Devices - 21 iOS + 12 Android devices ready to use
- NEW: switchPlatform() - Switch between iOS and Android with one line
- NEW: useIOSDevice() - Emulate any iPhone or iPad
- NEW: useAndroidDevice() - Emulate any Android phone
- NEW: getPlatformInfo() - Get current platform and device details
- NEW: downloadContentFromMessage() - Download media from DM messages (like Baileys for WhatsApp)
- NEW: View-Once Media Extraction - Save disappearing photos/videos before they expire
- NEW: downloadMediaBuffer() - Get media as Buffer directly
- NEW: extractMediaUrls() - Extract CDN URLs from any message type
- NEW: Custom Device Emulation - Choose which phone model Instagram sees
- NEW: setCustomDevice() - Set any custom Android device with full control
- NEW: setIOSDevice() - Set any custom iOS device with full control
- FIX: IRIS subscription auto-fetch - Messages now received automatically without manual irisData
- FIX: startRealTimeListener() - Fixed to use correct inbox method for IRIS data retrieval
- NEW: sendPhoto() / sendVideo() - Upload and send photos/videos directly via MQTT
- NEW: Clear message display - Incoming messages shown with Username, ID, Text, Status (no emojis)
- NEW: All message types decoded - Photos, videos, voice, reels, stories, links displayed clearly
- Multi-file auth state - Session persistence like Baileys (WhatsApp library)
- Real-time MQTT messaging - Receive and send DMs with <500ms latency
- Bidirectional communication - Send messages back through the same MQTT connection
- Message management - Send, delete, edit, and reply to messages via MQTT
- Notification subscriptions - Follow, mention, and call notifications via MQTT
- Thread management - Add/remove members from groups via MQTT
- Auto-reply bots - Build keyword-triggered or scheduled response bots
- Session persistence - Avoid repeated logins with saved sessions
- Full Instagram API - Stories, media uploads, search, comments, user info
- Group chat support - Automatic detection with thread-based messaging
- IRIS subscription protocol - Reliable message delivery with compression
- Automatic reconnection - Exponential backoff with connection pooling
- Pure JavaScript - No compilation required, works in Node.js 18+
This library is optimized for Direct Messages and implements the core MQTT protocols used by Instagram for:
- Real-time message delivery and reception
- Presence status tracking
- Typing indicators
- Notifications for follows, mentions, and calls
- Group thread management
For full MQTT coverage analysis, see MQTT_COVERAGE_ANALYSIS.md
``bash`
npm install nodejs-insta-private-api
Requires Node.js 18 or higher.
---
Default Device: Samsung Galaxy S25 Ultra (Android 15) - used automatically if you don't set a custom device.
This feature allows you to choose which phone model Instagram sees when your bot connects. Instead of using a default device, you can emulate any Android phone like Samsung Galaxy S25 Ultra, Huawei P60 Pro, Google Pixel 9, and more.
- Avoid detection - Use realistic, modern device fingerprints
- Match your target audience - Emulate devices popular in specific regions
- Testing - Test how Instagram behaves with different devices
- Reduce bans - Modern devices are less likely to trigger security checks
The easiest way to set a custom device is using the built-in presets:
`javascript
const { IgApiClient } = require('nodejs-insta-private-api');
const ig = new IgApiClient();
// Set device BEFORE login
ig.state.usePresetDevice('Samsung Galaxy S25 Ultra');
// Now login - Instagram will see a Samsung S25 Ultra
await ig.login({
username: 'your_username',
password: 'your_password'
});
console.log('Logged in with device:', ig.state.deviceString);
// Output: 35/15; 505dpi; 1440x3120; samsung; SM-S928B; e3q; qcom
`
| Device Name | Manufacturer | Android Version |
|-------------|--------------|-----------------|
| Samsung Galaxy S25 Ultra | Samsung | Android 15 |
| Samsung Galaxy S24 Ultra | Samsung | Android 14 |
| Samsung Galaxy S23 Ultra | Samsung | Android 14 |
| Samsung Galaxy Z Fold 5 | Samsung | Android 14 |
| Huawei P60 Pro | Huawei | Android 12 |
| Huawei Mate 60 Pro | Huawei | Android 12 |
| Google Pixel 8 Pro | Google | Android 14 |
| Google Pixel 9 Pro | Google | Android 15 |
| OnePlus 12 | OnePlus | Android 14 |
| Xiaomi 14 Ultra | Xiaomi | Android 14 |
| Xiaomi Redmi Note 13 Pro | Xiaomi | Android 14 |
| OPPO Find X7 Ultra | OPPO | Android 14 |
`javascript
const ig = new IgApiClient();
// Get all available preset devices
const presets = ig.state.getPresetDevices();
console.log('Available devices:');
Object.keys(presets).forEach((name, i) => {
console.log(${i + 1}. ${name});`
});
For complete control, use setCustomDevice() with your own configuration:
`javascript
const ig = new IgApiClient();
// Define your custom device
ig.state.setCustomDevice({
manufacturer: 'samsung', // Phone manufacturer
model: 'SM-S928B', // Model code
device: 'e3q', // Device codename
androidVersion: '15', // Android version
androidApiLevel: 35, // Android API level
resolution: '1440x3120', // Screen resolution
dpi: '505dpi', // Screen density
chipset: 'qcom', // Chipset (qcom, kirin, google, etc.)
build: 'UP1A.231005.007' // Build number (optional)
});
console.log('Device string:', ig.state.deviceString);
console.log('User agent:', ig.state.appUserAgent);
`
`javascript
const ig = new IgApiClient();
ig.state.usePresetDevice('Google Pixel 9 Pro');
// Get full device information
const info = ig.state.getCurrentDeviceInfo();
console.log('Device String:', info.deviceString);
console.log('Device ID:', info.deviceId);
console.log('UUID:', info.uuid);
console.log('Phone ID:', info.phoneId);
console.log('Build:', info.build);
console.log('User Agent:', info.userAgent);
`
`javascript
const { IgApiClient, RealtimeClient } = require('nodejs-insta-private-api');
const fs = require('fs');
async function startBot() {
const ig = new IgApiClient();
// Step 1: Set your preferred device BEFORE login
ig.state.usePresetDevice('Samsung Galaxy S25 Ultra');
console.log('Device configured:', ig.state.deviceString);
console.log('User Agent:', ig.state.appUserAgent);
// Step 2: Login
await ig.login({
username: process.env.IG_USERNAME,
password: process.env.IG_PASSWORD
});
console.log('Login successful!');
// Step 3: Save session (device info is included)
const session = await ig.state.serialize();
fs.writeFileSync('session.json', JSON.stringify(session, null, 2));
// Step 4: Connect to real-time messaging
const realtime = new RealtimeClient(ig);
const inbox = await ig.direct.getInbox();
await realtime.connect({
graphQlSubs: ['ig_sub_direct', 'ig_sub_direct_v2_message_sync'],
skywalkerSubs: ['presence_subscribe', 'typing_subscribe'],
irisData: inbox
});
console.log('Bot is online with Samsung Galaxy S25 Ultra emulation!');
realtime.on('message', (data) => {
console.log('New message:', data.message?.text);
});
// Keep running
await new Promise(() => {});
}
startBot().catch(console.error);
`
| Method | Description |
|--------|-------------|
| state.usePresetDevice(name) | Set device from preset list (e.g., 'Samsung Galaxy S25 Ultra') |state.setCustomDevice(config)
| | Set fully custom device configuration |state.getPresetDevices()
| | Get object with all available preset devices |state.getCurrentDeviceInfo()
| | Get current device configuration |state.deviceString
| | Current device string used in requests |state.appUserAgent
| | Full User-Agent header sent to Instagram |
| Property | Type | Description | Example |
|----------|------|-------------|---------|
| manufacturer | string | Phone manufacturer | 'samsung', 'HUAWEI', 'Google' |model
| | string | Phone model code | 'SM-S928B', 'Pixel 9 Pro' |device
| | string | Device codename | 'e3q', 'husky', 'caiman' |androidVersion
| | string | Android version | '15', '14', '13' |androidApiLevel
| | number | Android API level | 35, 34, 33 |resolution
| | string | Screen resolution | '1440x3120', '1080x2340' |dpi
| | string | Screen density | '505dpi', '480dpi', '420dpi' |chipset
| | string | Chipset identifier | 'qcom', 'kirin', 'google' |build
| | string | Build number (optional) | 'UP1A.231005.007' |
---
This feature provides Baileys-style multi-file session persistence for Instagram. Instead of storing everything in a single session.json, the session is split across multiple files for better organization, security, and reliability.
``
auth_info_instagram/
├── creds.json # Authorization tokens (Bearer token, claims)
├── device.json # Device information (device ID, UUID, phone ID)
├── cookies.json # HTTP cookies for API requests
├── mqtt-session.json # MQTT real-time session data
├── subscriptions.json # GraphQL and Skywalker subscriptions
├── seq-ids.json # Sequence IDs for message sync
└── app-state.json # Application state and preferences
`javascript
const { IgApiClient, RealtimeClient, useMultiFileAuthState } = require('nodejs-insta-private-api');
async function main() {
// Initialize multi-file auth state
const authState = await useMultiFileAuthState('./auth_info_instagram');
const ig = new IgApiClient();
// Check if we have a saved session
if (authState.hasSession()) {
console.log('Loading saved session...');
// Load credentials from files
await authState.loadCreds(ig);
// Validate session with Instagram
const isValid = await authState.isSessionValid(ig);
if (isValid) {
console.log('Session valid! Connecting to MQTT...');
// Connect using saved MQTT session
const realtime = new RealtimeClient(ig);
await realtime.connectFromSavedSession(authState);
realtime.on('message', (data) => {
console.log('New DM:', data.message.text);
});
console.log('Bot is running!');
} else {
console.log('Session expired, need fresh login');
await freshLogin(ig, authState);
}
} else {
console.log('No session found, logging in...');
await freshLogin(ig, authState);
}
}
async function freshLogin(ig, authState) {
// Login with credentials
await ig.login({
username: 'your_username',
password: 'your_password'
});
// Save credentials to files
await authState.saveCreds(ig);
console.log('Credentials saved!');
// Connect to MQTT
const realtime = new RealtimeClient(ig);
const inbox = await ig.direct.getInbox();
await realtime.connect({
graphQlSubs: ['ig_sub_direct', 'ig_sub_direct_v2_message_sync'],
skywalkerSubs: ['presence_subscribe', 'typing_subscribe'],
irisData: inbox
});
// Save MQTT session
await authState.saveMqttSession(realtime);
console.log('MQTT session saved!');
realtime.on('message', (data) => {
console.log('New DM:', data.message.text);
});
}
main();
`
`javascript`
const authState = await useMultiFileAuthState(folderPath);
#### Methods
| Method | Description |
|--------|-------------|
| hasSession() | Returns true if saved credentials exist |hasMqttSession()
| | Returns true if saved MQTT session exists |loadCreds(ig)
| | Loads saved credentials into IgApiClient |saveCreds(ig)
| | Saves current credentials to files |isSessionValid(ig)
| | Validates session with Instagram API |loadMqttSession()
| | Returns saved MQTT session data |saveMqttSession(realtime)
| | Saves MQTT session from RealtimeClient |clearSession()
| | Deletes all saved session files |
`javascript
const { IgApiClient, RealtimeClient, useMultiFileAuthState } = require('nodejs-insta-private-api');
const AUTH_FOLDER = './auth_info_instagram';
const USERNAME = process.env.IG_USERNAME;
const PASSWORD = process.env.IG_PASSWORD;
async function startBot() {
console.log('Starting Instagram Bot...');
const authState = await useMultiFileAuthState(AUTH_FOLDER);
const ig = new IgApiClient();
let realtime;
if (authState.hasSession()) {
console.log('Found saved session, attempting to restore...');
const loaded = await authState.loadCreds(ig);
if (loaded) {
const valid = await authState.isSessionValid(ig);
if (valid) {
console.log('Session is valid! Connecting to MQTT...');
realtime = new RealtimeClient(ig);
realtime.on('connected', () => console.log('MQTT Connected!'));
realtime.on('error', (err) => console.error('MQTT Error:', err.message));
await realtime.connectFromSavedSession(authState);
setupMessageHandler(realtime);
console.log('Bot is now listening for messages!');
return;
}
}
console.log('Session invalid or expired, clearing...');
await authState.clearSession();
}
// Fresh login required
console.log('Performing fresh login...');
await ig.login({ username: USERNAME, password: PASSWORD });
console.log('Login successful!');
await authState.saveCreds(ig);
realtime = new RealtimeClient(ig);
const inbox = await ig.direct.getInbox();
await realtime.connect({
graphQlSubs: ['ig_sub_direct', 'ig_sub_direct_v2_message_sync'],
skywalkerSubs: ['presence_subscribe', 'typing_subscribe'],
irisData: inbox
});
await authState.saveMqttSession(realtime);
setupMessageHandler(realtime);
console.log('Bot is now listening for messages!');
}
function setupMessageHandler(realtime) {
realtime.on('message', async (data) => {
const msg = data.message;
if (!msg?.text) return;
console.log(New message from ${msg.from_user_id}: ${msg.text});
// Auto-reply example
if (msg.text.toLowerCase().includes('hello')) {
await realtime.directCommands.sendTextViaRealtime(
msg.thread_id,
'Hi there! Thanks for your message!'
);
}
});
}
startBot().catch(console.error);
`
---
This library now supports full iOS device emulation alongside Android. You can connect to Instagram as any iPhone or iPad model, giving you more flexibility for testing and avoiding detection.
- Avoid detection - iOS devices have different fingerprints than Android
- More realistic - Many real users use iPhones
- Testing - Test how Instagram behaves with iOS vs Android clients
- Reduce bans - Vary your device types to appear more natural
`javascript
const { IgApiClient } = require('nodejs-insta-private-api');
const ig = new IgApiClient();
// Switch to iOS platform with iPhone 16 Pro Max
ig.state.useIOSDevice('iPhone 16 Pro Max');
console.log('Platform:', ig.state.platform); // 'ios'
console.log('User-Agent:', ig.state.appUserAgent);
// Output: Instagram 347.0.0.36.89 (iPhone17,1; iOS 18.1; en_US; en_US; scale=3.00; 1320x2868; 618023787) AppleWebKit/420+
`
| Device Name | Model ID | iOS Version | Resolution |
|-------------|----------|-------------|------------|
| iPhone 16 Pro Max | iPhone17,1 | iOS 18.1 | 1320x2868 |
| iPhone 16 Pro | iPhone17,2 | iOS 18.1 | 1206x2622 |
| iPhone 16 Plus | iPhone17,3 | iOS 18.1 | 1290x2796 |
| iPhone 16 | iPhone17,4 | iOS 18.1 | 1179x2556 |
| iPhone 15 Pro Max | iPhone16,2 | iOS 18.1 | 1290x2796 |
| iPhone 15 Pro | iPhone16,1 | iOS 18.1 | 1179x2556 |
| iPhone 15 Plus | iPhone15,5 | iOS 18.1 | 1290x2796 |
| iPhone 15 | iPhone15,4 | iOS 18.1 | 1179x2556 |
| iPhone 14 Pro Max | iPhone15,3 | iOS 18.1 | 1290x2796 |
| iPhone 14 Pro | iPhone15,2 | iOS 18.1 | 1179x2556 |
| iPhone 14 Plus | iPhone14,8 | iOS 18.1 | 1284x2778 |
| iPhone 14 | iPhone14,7 | iOS 18.1 | 1170x2532 |
| iPhone 13 Pro Max | iPhone14,3 | iOS 17.6 | 1284x2778 |
| iPhone 13 Pro | iPhone14,2 | iOS 17.6 | 1170x2532 |
| iPhone 13 | iPhone14,5 | iOS 17.6 | 1170x2532 |
| iPhone 12 Pro Max | iPhone13,4 | iOS 17.6 | 1284x2778 |
| iPhone 12 Pro | iPhone13,3 | iOS 17.6 | 1170x2532 |
| iPhone 12 | iPhone13,2 | iOS 17.6 | 1170x2532 |
| iPad Pro 12.9 (6th gen) | iPad14,3 | iOS 18.1 | 2048x2732 |
| iPad Pro 11 (4th gen) | iPad14,5 | iOS 18.1 | 1668x2388 |
| iPad Air (5th gen) | iPad13,18 | iOS 18.1 | 2360x1640 |
`javascript
const ig = new IgApiClient();
// Get all devices grouped by platform
const devices = ig.state.listAllDevices();
console.log('iOS Devices:', devices.ios);
// ['iPhone 16 Pro Max', 'iPhone 16 Pro', 'iPhone 16 Plus', ...]
console.log('Android Devices:', devices.android);
// ['Samsung Galaxy S25 Ultra', 'Google Pixel 9 Pro', ...]
`
`javascript
const ig = new IgApiClient();
// Start with Android
ig.state.useAndroidDevice('Samsung Galaxy S25 Ultra');
console.log('Platform:', ig.state.platform); // 'android'
// Switch to iOS
ig.state.switchPlatform('ios', 'iPhone 16 Pro Max');
console.log('Platform:', ig.state.platform); // 'ios'
// Switch back to Android with different device
ig.state.switchPlatform('android', 'Google Pixel 9 Pro');
console.log('Platform:', ig.state.platform); // 'android'
`
`javascript
const ig = new IgApiClient();
// Set a fully custom iOS device
ig.state.setIOSDevice({
iosDeviceModel: 'iPhone17,1',
iosDeviceName: 'iPhone 16 Pro Max',
iosVersion: '18.1',
iosAppVersion: '347.0.0.36.89',
iosAppVersionCode: '618023787'
});
console.log('User-Agent:', ig.state.appUserAgent);
`
`javascript
const ig = new IgApiClient();
ig.state.useIOSDevice('iPhone 15 Pro');
const info = ig.state.getPlatformInfo();
console.log(info);
// {
// platform: 'ios',
// userAgent: 'Instagram 347.0.0.36.89 (iPhone16,1; iOS 18.1; ...) AppleWebKit/420+',
// packageName: 'com.burbn.instagram',
// deviceId: 'ios-A1B2C3D4E5F6...',
// iosDeviceModel: 'iPhone16,1',
// iosDeviceName: 'iPhone 15 Pro',
// iosVersion: '18.1',
// iosAppVersion: '347.0.0.36.89'
// }
`
`javascript
const { IgApiClient, RealtimeClient, useMultiFileAuthState } = require('nodejs-insta-private-api');
async function startIOSBot() {
const authState = await useMultiFileAuthState('./auth_info_instagram');
const ig = new IgApiClient();
// Use iPhone 16 Pro Max for this bot
ig.state.useIOSDevice('iPhone 16 Pro Max');
console.log('Device:', ig.state.iosDeviceName);
console.log('User-Agent:', ig.state.appUserAgent);
if (authState.hasSession()) {
console.log('Loading saved session...');
await authState.loadCreds(ig);
const valid = await authState.isSessionValid(ig);
if (!valid) {
console.log('Session expired, need fresh login');
await authState.clearSession();
}
}
if (!authState.hasSession()) {
console.log('Logging in...');
await ig.login({
username: process.env.IG_USERNAME,
password: process.env.IG_PASSWORD
});
await authState.saveCreds(ig);
}
// Connect to real-time messaging
const realtime = new RealtimeClient(ig);
const inbox = await ig.direct.getInbox();
await realtime.connect({
graphQlSubs: ['ig_sub_direct', 'ig_sub_direct_v2_message_sync'],
skywalkerSubs: ['presence_subscribe', 'typing_subscribe'],
irisData: inbox
});
await authState.saveMqttSession(realtime);
console.log('iOS Bot is online with', ig.state.iosDeviceName);
realtime.on('message', (data) => {
console.log('New DM:', data.message?.text);
});
}
startIOSBot().catch(console.error);
`
| Method | Description |
|--------|-------------|
| state.useIOSDevice(name) | Set iOS device from preset (e.g., 'iPhone 16 Pro Max') |state.setIOSDevice(config)
| | Set fully custom iOS device configuration |state.useAndroidDevice(name)
| | Set Android device from preset |state.switchPlatform(platform, device)
| | Switch between 'ios' and 'android' |state.getPlatformInfo()
| | Get current platform and device details |state.listAllDevices()
| | Get all devices grouped by platform |state.getIOSDevices()
| | Get only iOS device presets |state.getAndroidDevices()
| | Get only Android device presets |state.platform
| | Current platform ('ios' or 'android') |state.iosUserAgent
| | iOS-specific User-Agent string |state.packageName
| | Package name ('com.burbn.instagram' for iOS) |
---
#### 1. Send Text Message
`javascript`
await realtime.directCommands.sendTextViaRealtime(threadId, 'Your message here');
#### 2. Delete Message
`javascript`
await realtime.directCommands.deleteMessage(threadId, messageId);
#### 3. Edit Message
`javascript`
await realtime.directCommands.editMessage(threadId, messageId, 'Updated text');
#### 4. Reply to Message (Quote Reply)
`javascript`
await realtime.directCommands.replyToMessage(threadId, messageId, 'My reply');
#### 5. Send Reaction (Emoji)
`javascript
await realtime.directCommands.sendReaction({
threadId: threadId,
itemId: messageId,
emoji: '❤️',
reactionType: 'like',
reactionStatus: 'created'
});
// Remove reaction
await realtime.directCommands.sendReaction({
threadId: threadId,
itemId: messageId,
emoji: '❤️',
reactionStatus: 'deleted'
});
`
#### 6. Send Media (Share existing Instagram post)
`javascript`
await realtime.directCommands.sendMedia({
threadId: threadId,
mediaId: '12345678',
text: 'Optional caption'
});
#### 6.1 Send Photo (NEW in v5.60.3 - Upload & Send)
Upload and send a photo directly from a Buffer. This method handles the complete upload process automatically.
`javascript
const fs = require('fs');
// Read photo from file
const photoBuffer = fs.readFileSync('./photo.jpg');
// Send photo via realtime
await realtime.directCommands.sendPhoto({
photoBuffer: photoBuffer,
threadId: threadId,
caption: 'Check this out!', // Optional
mimeType: 'image/jpeg' // Optional: 'image/jpeg' or 'image/png'
});
`
Download from URL and send:
`javascript
const axios = require('axios');
const response = await axios.get('https://example.com/image.jpg', {
responseType: 'arraybuffer'
});
const photoBuffer = Buffer.from(response.data);
await realtime.directCommands.sendPhoto({
photoBuffer: photoBuffer,
threadId: threadId
});
`
#### 6.2 Send Video (NEW in v5.60.3 - Upload & Send)
Upload and send a video directly from a Buffer.
`javascript
const fs = require('fs');
const videoBuffer = fs.readFileSync('./video.mp4');
await realtime.directCommands.sendVideo({
videoBuffer: videoBuffer,
threadId: threadId,
caption: 'Watch this!', // Optional
duration: 15, // Optional: duration in seconds
width: 720, // Optional
height: 1280 // Optional
});
`
#### 7. Send Location
`javascript`
await realtime.directCommands.sendLocation({
threadId: threadId,
locationId: '213999449',
text: 'Optional description'
});
#### 8. Send Profile
`javascript`
await realtime.directCommands.sendProfile({
threadId: threadId,
userId: '987654321',
text: 'Optional text'
});
#### 9. Send Hashtag
`javascript`
await realtime.directCommands.sendHashtag({
threadId: threadId,
hashtag: 'instagram',
text: 'Optional text'
});
#### 10. Send Like
`javascript`
await realtime.directCommands.sendLike({ threadId: threadId });
#### 11. Send User Story
`javascript`
await realtime.directCommands.sendUserStory({
threadId: threadId,
storyId: 'story_12345',
text: 'Optional text'
});
#### 12. Mark Message as Seen
`javascript`
await realtime.directCommands.markAsSeen({
threadId: threadId,
itemId: messageId
});
#### 13. Indicate Activity (Typing Indicator)
`javascript
// Show typing indicator
await realtime.directCommands.indicateActivity({
threadId: threadId,
isActive: true
});
// Stop typing
await realtime.directCommands.indicateActivity({
threadId: threadId,
isActive: false
});
`
#### 14. Subscribe to Follow Notifications
`javascript
await realtime.directCommands.subscribeToFollowNotifications();
realtime.on('follow', (data) => {
console.log('New follower:', data.user_id);
});
`
#### 15. Subscribe to Mention Notifications
`javascript
await realtime.directCommands.subscribeToMentionNotifications();
realtime.on('mention', (data) => {
console.log('You were mentioned in:', data.content_type);
});
`
#### 16. Subscribe to Call Notifications
`javascript
await realtime.directCommands.subscribeToCallNotifications();
realtime.on('call', (data) => {
console.log('Incoming call from:', data.caller_id);
});
`
#### 17. Add Member to Thread
`javascript`
await realtime.directCommands.addMemberToThread(threadId, userId);
#### 18. Remove Member from Thread
`javascript`
await realtime.directCommands.removeMemberFromThread(threadId, userId);
---
This feature provides Baileys-style media download for Instagram DM messages. Just like Baileys' downloadContentFromMessage() for WhatsApp, you can now extract and save photos, videos, and voice messages from Instagram DMs - including view-once (disappearing) media.
Instagram's view-once media (photos/videos that disappear after viewing) can now be saved before marking as seen. This works because:
1. Media is received via MQTT with CDN URLs
2. The "view-once" flag is client-side only
3. Media remains on Instagram's CDN until expiry (~24 hours)
`javascript
const {
IgApiClient,
RealtimeClient,
downloadContentFromMessage,
isViewOnceMedia
} = require('nodejs-insta-private-api');
const fs = require('fs');
const ig = new IgApiClient();
// ... login code ...
const realtime = new RealtimeClient(ig);
// ... connect code ...
realtime.on('message', async (data) => {
const msg = data.message;
// Check if it's a view-once message
if (isViewOnceMedia(msg)) {
console.log('View-once media received! Saving before it expires...');
try {
// Download the media as a stream
const stream = await downloadContentFromMessage(msg);
// Collect chunks into buffer
let buffer = Buffer.from([]);
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk]);
}
// Determine file extension
const ext = stream.mediaInfo.type.includes('video') ? 'mp4' : 'jpg';
const filename = viewonce_${Date.now()}.${ext};Saved: ${filename} (${buffer.length} bytes)
// Save to file
fs.writeFileSync(filename, buffer);
console.log();`
console.log('Media info:', stream.mediaInfo);
} catch (err) {
console.error('Failed to download:', err.message);
}
// DO NOT mark as seen if you want to keep the media secret!
// await realtime.directCommands.markAsSeen({ threadId: msg.thread_id, itemId: msg.item_id });
}
});
`javascript
const {
downloadMediaBuffer,
hasMedia,
getMediaType
} = require('nodejs-insta-private-api');
realtime.on('message', async (data) => {
const msg = data.message;
// Check if message contains any media
if (hasMedia(msg)) {
const mediaType = getMediaType(msg);
console.log('Received media type:', mediaType);
// Download as buffer directly
const { buffer, mediaInfo } = await downloadMediaBuffer(msg);
// Save based on type
let filename;
switch (mediaInfo.type) {
case 'image':
case 'raven_image':
filename = photo_${Date.now()}.jpg;video_${Date.now()}.mp4
break;
case 'video':
case 'raven_video':
filename = ;voice_${Date.now()}.mp4
break;
case 'voice':
filename = ;media_${Date.now()}
break;
default:
filename = ;Saved ${mediaType}: ${filename}
}
fs.writeFileSync(filename, buffer);
console.log();`
}
});
`javascript
const { extractMediaUrls } = require('nodejs-insta-private-api');
realtime.on('message', async (data) => {
const msg = data.message;
const mediaInfo = extractMediaUrls(msg);
if (mediaInfo) {
console.log('Media type:', mediaInfo.type);
console.log('Is view-once:', mediaInfo.isViewOnce);
console.log('Dimensions:', mediaInfo.width, 'x', mediaInfo.height);
console.log('Duration (if video):', mediaInfo.duration);
// Get all quality options
console.log('Available URLs:');
mediaInfo.urls.forEach((url, i) => {
console.log( ${i}: ${url.width}x${url.height} - ${url.url.substring(0, 50)}...);`
});
// Best quality URL is always first
const bestUrl = mediaInfo.urls[0].url;
}
});
`javascript
const {
IgApiClient,
RealtimeClient,
useMultiFileAuthState,
downloadMediaBuffer,
hasMedia,
isViewOnceMedia,
MEDIA_TYPES
} = require('nodejs-insta-private-api');
const fs = require('fs');
const path = require('path');
const SAVE_DIR = './saved_media';
async function startMediaBot() {
// Create save directory
if (!fs.existsSync(SAVE_DIR)) {
fs.mkdirSync(SAVE_DIR, { recursive: true });
}
const authState = await useMultiFileAuthState('./auth_info_instagram');
const ig = new IgApiClient();
// Login or restore session
if (authState.hasSession()) {
await authState.loadCreds(ig);
} else {
await ig.login({
username: process.env.IG_USERNAME,
password: process.env.IG_PASSWORD
});
await authState.saveCreds(ig);
}
const realtime = new RealtimeClient(ig);
const inbox = await ig.direct.getInbox();
await realtime.connect({
graphQlSubs: ['ig_sub_direct', 'ig_sub_direct_v2_message_sync'],
skywalkerSubs: ['presence_subscribe', 'typing_subscribe'],
irisData: inbox
});
console.log('Media Bot Active - Saving all received media\n');
realtime.on('message', async (data) => {
const msg = data.message;
if (!hasMedia(msg)) return;
try {
const { buffer, mediaInfo } = await downloadMediaBuffer(msg);
// Generate filename with metadata
const prefix = mediaInfo.isViewOnce ? 'VIEWONCE_' : '';
const ext = getExtension(mediaInfo.type);
const filename = ${prefix}${mediaInfo.type}_${Date.now()}.${ext};[SAVED] ${filename}
const filepath = path.join(SAVE_DIR, filename);
fs.writeFileSync(filepath, buffer);
console.log(); Type: ${mediaInfo.type}
console.log(); Size: ${buffer.length} bytes
console.log(); Dimensions: ${mediaInfo.width}x${mediaInfo.height}
console.log();
if (mediaInfo.isViewOnce) {
console.log(' WARNING: View-once media - do not mark as seen!');
}
console.log('');
} catch (err) {
console.error('Download failed:', err.message);
}
});
await new Promise(() => {});
}
function getExtension(type) {
switch (type) {
case MEDIA_TYPES.IMAGE:
case MEDIA_TYPES.RAVEN_IMAGE:
case MEDIA_TYPES.MEDIA_SHARE:
case MEDIA_TYPES.STORY_SHARE:
return 'jpg';
case MEDIA_TYPES.VIDEO:
case MEDIA_TYPES.RAVEN_VIDEO:
case MEDIA_TYPES.CLIP:
case MEDIA_TYPES.VOICE:
return 'mp4';
default:
return 'bin';
}
}
startMediaBot().catch(console.error);
`
| Function | Description |
|----------|-------------|
| downloadContentFromMessage(message, type?, options?) | Download media as a readable stream (like Baileys) |downloadMediaBuffer(message, type?, options?)
| | Download media directly as Buffer |extractMediaUrls(message)
| | Extract media URLs and metadata without downloading |hasMedia(message)
| | Check if message contains downloadable media |getMediaType(message)
| | Get media type without downloading |isViewOnceMedia(message)
| | Check if message is view-once (disappearing) |
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| quality | number | 0 | Quality index (0 = highest quality) |timeout
| | number | 30000 | Request timeout in milliseconds |headers
| | object | {} | Additional HTTP headers |
`javascript
const { MEDIA_TYPES } = require('nodejs-insta-private-api');
MEDIA_TYPES.IMAGE // Regular photo
MEDIA_TYPES.VIDEO // Regular video
MEDIA_TYPES.VOICE // Voice message
MEDIA_TYPES.RAVEN_IMAGE // View-once photo
MEDIA_TYPES.RAVEN_VIDEO // View-once video
MEDIA_TYPES.MEDIA_SHARE // Shared post
MEDIA_TYPES.REEL_SHARE // Shared reel
MEDIA_TYPES.STORY_SHARE // Shared story
MEDIA_TYPES.CLIP // Clip/Reel
`
1. Download BEFORE marking as seen - For view-once media, download immediately when message is received. Once you call markAsSeen(), Instagram knows you viewed it.
2. Media expiry - View-once media URLs expire after ~24 hours. Regular media URLs may last longer but are not permanent.
3. Rate limiting - Downloading many files quickly may trigger Instagram's rate limits. Add delays between downloads if processing many messages.
4. Legal considerations - This feature is for personal backup purposes. Respect privacy and applicable laws regarding saved media.
---
`javascript
const { IgApiClient, RealtimeClient } = require('nodejs-insta-private-api');
const fs = require('fs');
(async () => {
const ig = new IgApiClient();
const session = JSON.parse(fs.readFileSync('session.json'));
await ig.state.deserialize(session);
const realtime = new RealtimeClient(ig);
const inbox = await ig.direct.getInbox();
await realtime.connect({
graphQlSubs: ['ig_sub_direct', 'ig_sub_direct_v2_message_sync'],
skywalkerSubs: ['presence_subscribe', 'typing_subscribe'],
irisData: inbox
});
console.log('Auto-Reply Bot Active\n');
realtime.on('message', async (data) => {
const msg = data.message;
if (!msg?.text) return;
console.log([${msg.from_user_id}]: ${msg.text});
let reply = null;
if (msg.text.toLowerCase().includes('hello')) {
reply = 'Hey! Thanks for reaching out!';
} else if (msg.text.toLowerCase().includes('help')) {
reply = 'How can I assist you?';
} else if (msg.text.toLowerCase().includes('thanks')) {
reply = 'You are welcome!';
}
if (reply) {
try {
await realtime.directCommands.sendTextViaRealtime(msg.thread_id, reply);
console.log(Replied: ${reply}\n);Failed to send reply: ${err.message}\n
} catch (err) {
console.error();
}
}
});
await new Promise(() => {});
})();
`
`javascript
const { IgApiClient, RealtimeClient } = require('nodejs-insta-private-api');
const fs = require('fs');
(async () => {
const ig = new IgApiClient();
const session = JSON.parse(fs.readFileSync('session.json'));
await ig.state.deserialize(session);
const realtime = new RealtimeClient(ig);
const inbox = await ig.direct.getInbox();
await realtime.connect({
graphQlSubs: ['ig_sub_direct', 'ig_sub_direct_v2_message_sync'],
skywalkerSubs: ['presence_subscribe', 'typing_subscribe'],
irisData: inbox
});
console.log('Smart Bot Started\n');
realtime.on('message', async (data) => {
const msg = data.message;
if (!msg?.text) return;
// Mark as seen immediately
await realtime.directCommands.markAsSeen({
threadId: msg.thread_id,
itemId: msg.item_id
});
// Show typing indicator
await realtime.directCommands.indicateActivity({
threadId: msg.thread_id,
isActive: true
});
// Simulate processing time
await new Promise(r => setTimeout(r, 2000));
// Send reply
if (msg.text.toLowerCase().includes('hi')) {
await realtime.directCommands.sendTextViaRealtime(
msg.thread_id,
'Hello there! How can I help?'
);
// React with emoji
await realtime.directCommands.sendReaction({
threadId: msg.thread_id,
itemId: msg.item_id,
emoji: '👋'
});
}
// Stop typing
await realtime.directCommands.indicateActivity({
threadId: msg.thread_id,
isActive: false
});
});
await new Promise(() => {});
})();
`
---
#### Authentication
`javascript
// Login with credentials
await ig.login({
username: 'your_username',
password: 'your_password',
email: 'your_email@example.com'
});
// Load from saved session
const session = JSON.parse(fs.readFileSync('session.json'));
await ig.state.deserialize(session);
// Save session
const serialized = ig.state.serialize();
fs.writeFileSync('session.json', JSON.stringify(serialized));
`
#### Direct Messages
`javascript
// Get inbox with all conversations
const inbox = await ig.direct.getInbox();
// Get specific thread messages
const thread = await ig.direct.getThread(threadId);
// Send text message (HTTP - slower than MQTT)
await ig.direct.send({
threadId: threadId,
item: {
type: 'text',
text: 'Hello there!'
}
});
// Mark messages as seen
await ig.direct.markMessagesSeen(threadId, [messageId]);
`
#### Connection
`javascript
const realtime = new RealtimeClient(ig);
// Connect to MQTT
await realtime.connect({
graphQlSubs: ['ig_sub_direct', 'ig_sub_direct_v2_message_sync'],
skywalkerSubs: ['presence_subscribe', 'typing_subscribe'],
irisData: inbox // Required: inbox data from ig.direct.getInbox()
});
// Connect from saved session (NEW in v5.60.2)
await realtime.connectFromSavedSession(authState);
`
#### All 18 MQTT Methods via directCommands
`javascript
// 1. Send Text
await realtime.directCommands.sendTextViaRealtime(threadId, 'Text');
// 2. Delete Message
await realtime.directCommands.deleteMessage(threadId, messageId);
// 3. Edit Message
await realtime.directCommands.editMessage(threadId, messageId, 'New text');
// 4. Reply to Message
await realtime.directCommands.replyToMessage(threadId, messageId, 'Reply');
// 5. Send Reaction
await realtime.directCommands.sendReaction({
threadId, itemId, emoji: '❤️'
});
// 6. Send Media
await realtime.directCommands.sendMedia({ threadId, mediaId });
// 7. Send Location
await realtime.directCommands.sendLocation({ threadId, locationId });
// 8. Send Profile
await realtime.directCommands.sendProfile({ threadId, userId });
// 9. Send Hashtag
await realtime.directCommands.sendHashtag({ threadId, hashtag });
// 10. Send Like
await realtime.directCommands.sendLike({ threadId });
// 11. Send Story
await realtime.directCommands.sendUserStory({ threadId, storyId });
// 12. Mark as Seen
await realtime.directCommands.markAsSeen({ threadId, itemId });
// 13. Indicate Activity (Typing)
await realtime.directCommands.indicateActivity({ threadId, isActive: true });
// 14. Subscribe to Follow Notifications
await realtime.directCommands.subscribeToFollowNotifications();
// 15. Subscribe to Mention Notifications
await realtime.directCommands.subscribeToMentionNotifications();
// 16. Subscribe to Call Notifications
await realtime.directCommands.subscribeToCallNotifications();
// 17. Add Member to Thread
await realtime.directCommands.addMemberToThread(threadId, userId);
// 18. Remove Member from Thread
await realtime.directCommands.removeMemberFromThread(threadId, userId);
`
#### Listening for Events
`javascript
// Incoming messages
realtime.on('message', (data) => {
const msg = data.message;
console.log(msg.text); // Message text
console.log(msg.from_user_id); // Sender user ID
console.log(msg.thread_id); // Conversation thread ID
});
// Connection status
realtime.on('connected', () => console.log('Connected'));
realtime.on('disconnected', () => console.log('Disconnected'));
// Notifications
realtime.on('follow', (data) => console.log('New follower:', data.user_id));
realtime.on('mention', (data) => console.log('Mentioned:', data.content_type));
realtime.on('call', (data) => console.log('Call from:', data.caller_id));
// Errors
realtime.on('error', (err) => console.error('Error:', err.message));
`
`javascript
// Get user info by username
const user = await ig.user.info('username');
// Search users
const results = await ig.user.search({ username: 'query' });
// Get followers
const followers = await ig.user.followers('user_id');
// Get following
const following = await ig.user.following('user_id');
`
---
Messages arrive as event data with this structure:
`javascript`
realtime.on('message', (data) => {
const msg = data.message;
console.log({
text: msg.text, // Message content (string)
from_user_id: msg.from_user_id, // Sender's Instagram user ID
thread_id: msg.thread_id, // Conversation thread ID
timestamp: msg.timestamp, // Unix timestamp
item_id: msg.item_id // Unique message ID
});
});
---
| Operation | Latency | Method |
|-----------|---------|--------|
| Receive incoming DM | 100-500ms | MQTT (real-time) |
| Send DM via MQTT | 200-800ms | Direct MQTT publish |
| Send DM via HTTP | 1-3s | REST API fallback |
| Get inbox | 500ms-2s | REST API |
MQTT is significantly faster for both receiving and sending messages.
---
`javascript
// NEW: Use multi-file auth state for better session management
const authState = await useMultiFileAuthState('./auth_info_instagram');
// Check and load existing session
if (authState.hasSession()) {
await authState.loadCreds(ig);
if (await authState.isSessionValid(ig)) {
// Session is valid, proceed
}
}
// Save after login
await authState.saveCreds(ig);
await authState.saveMqttSession(realtime);
`
`javascript`
realtime.on('message', async (data) => {
try {
const msg = data.message;
await realtime.directCommands.sendTextViaRealtime(msg.thread_id, 'Reply');
} catch (err) {
console.error('Error:', err.message);
}
});
`javascript
const userLastSeen = new Map();
if (userLastSeen.has(userId) && Date.now() - userLastSeen.get(userId) < 5000) {
return;
}
userLastSeen.set(userId, Date.now());
`
`javascript
let isConnected = false;
realtime.on('connected', () => {
isConnected = true;
console.log('Connected');
});
realtime.on('disconnected', () => {
isConnected = false;
console.log('Disconnected - will auto-reconnect');
});
`
---
- Instagram account required - No API tokens needed, use your credentials
- Rate limiting - Instagram rate limits automated messaging, implement delays
- Mobile detection - Instagram may detect bot activity and require verification
- Session expiry - Sessions may expire after 60+ days, require re-login
- Message history - Only real-time messages available, no historical message sync
---
`javascript`
// Ensure credentials are correct
// Instagram may require 2FA verification
`javascript
// Check that inbox data is loaded before connecting
const inbox = await ig.direct.getInbox();
// Connection retries automatically with exponential backoff
`
`javascript
// Ensure MQTT is connected
if (!isConnected) {
console.log('Waiting for MQTT connection...');
return;
}
// Check rate limiting - Instagram blocks rapid messaging
`
---
- Download media from DM messages (like Baileys for WhatsApp)
- NEW: downloadMediaBuffer() - Get media as Buffer directly
- NEW: extractMediaUrls() - Extract CDN URLs from any message type
- NEW: hasMedia() - Check if message contains downloadable media
- NEW: getMediaType() - Get media type without downloading
- NEW: isViewOnceMedia() - Check if message is view-once (disappearing)
- NEW: MEDIA_TYPES constant for all supported media types
- Full support for view-once (raven) media extraction
- Support for photos, videos, voice messages, reels, stories, clips$3
- Added Custom Device Emulation with 12 preset devices
- setCustomDevice() and usePresetDevice() methods
- Default device: Samsung Galaxy S25 Ultra (Android 15)$3
- Added sendPhoto() and sendVideo() for media uploads via MQTT$3
- Added useMultiFileAuthState() - Baileys-style multi-file session persistence
- Added connectFromSavedSession()` method for RealtimeClient---
MIT
For issues, bugs, or feature requests: https://github.com/Kunboruto20/nodejs-insta-private-api/issues
Documentation: https://github.com/Kunboruto20/nodejs-insta-private-api
Examples: See repository examples/ directory for working implementations