π€ An advanced, unofficial Facebook Messenger API library for Node.js By SH AN - Build powerful bots with ease.
- Features
- Installation
- Quick Start
- Authentication
- API Reference
- Event Handling
- Configuration
- Advanced Usage
- Examples
- Troubleshooting
- Security
- License
- Support
- β Email/Password Authentication - Traditional login with credentials
- β AppState Authentication - Session persistence without storing passwords
- β Message Management - Send, edit, delete, and react to messages
- β Real-time Events - Listen to messages, typing indicators, read receipts, and more
- β Media Handling - Support for images, videos, files, stickers, and voice messages
- β Group Management - Create, rename, and manage group chats
- β User Information - Fetch detailed user profiles and thread information
- β Chat Themes - Change chat colors and styles
- β AI Theme Generation - Generate custom themes using AI prompts
- β Message Reactions - Add/remove emoji reactions to messages
- π End-to-End Encryption (E2EE) - Secure messaging for encrypted chats
- π Proxy Support - Route traffic through proxy servers
- π Auto-Reconnection - Automatic reconnection with exponential backoff
- π Presence Detection - Track user online/offline status
- β‘ High Performance - Native bindings for critical operations
- π― Event Streaming - Real-time message streaming via MQTT
- πΎ Session Management - Persistent sessions across restarts
- π‘οΈ Error Recovery - Robust error handling and recovery mechanisms
- π¨ Theme Customization - Predefined themes and custom color support
- π± Multi-Account Support - Run multiple bot instances simultaneously
- Node.js >= 12.0.0
- npm >= 6.0.0 or yarn >= 1.22.0
npm install shan-fcayarn add shan-fcanode -e "const login = require('shan-fca'); console.log('β
ShAn-FCA installed successfully!');"const login = require('shan-fca');
login(
{
email: 'your.email@gmail.com',
password: 'your-password'
},
(err, api) => {
if (err) return console.error('β Login failed:', err);
console.log('β
Successfully logged in!');
// Send a test message
api.sendMessage('Hello from ShAn-FCA! π€', '123456789', (err) => {
if (err) console.error(err);
else console.log('β
Message sent!');
});
}
);const login = require('shan-fca');
(async () => {
try {
const api = await login({
email: 'your.email@gmail.com',
password: 'your-password'
});
console.log('β
Logged in!');
// Send message
await api.sendMessage('Hello!', '123456789');
console.log('β
Message sent!');
// Listen to messages
api.listenMqtt((err, event) => {
if (event.type === 'message') {
console.log(`π¨ ${event.senderName}: ${event.body}`);
}
});
} catch (err) {
console.error('β Error:', err);
}
})();login({
email: process.env.FB_EMAIL,
password: process.env.FB_PASSWORD
}, (err, api) => {
if (err) return console.error(err);
console.log('β
Logged in!');
});const appState = JSON.parse(fs.readFileSync('appState.json'));
login({ appState }, (err, api) => {
if (err) return console.error('β Session expired');
console.log('β
Logged in with saved session!');
});login({
email: process.env.FB_EMAIL,
password: process.env.FB_PASSWORD
}, {
forceLogin: true
}, (err, api) => {
if (err?.error === 'login-approval') {
const code = prompt('Enter 2FA code: ');
err.continue(code)
.then(api => console.log('β
Logged in with 2FA!'))
.catch(err => console.error('β Invalid 2FA code'));
}
});// Basic text
api.sendMessage('Hello World!', threadID, (err, info) => {
if (err) console.error(err);
});
// With attachments
api.sendMessage({
body: 'Check this!',
attachment: fs.createReadStream('image.png')
}, threadID);
// With mentions
api.sendMessage({
body: 'Hey {{User}}, check this!',
mentions: [{ tag: 'User', id: '123456789' }]
}, threadID);
// With sticker
api.sendMessage({ sticker: 'STICKER_ID' }, threadID);// Get thread info
api.getThreadInfo(threadID, (err, info) => {
console.log('Name:', info.threadName);
console.log('Participants:', info.participantIDs);
});
// Rename thread
api.changeThreadSubject('New Name', threadID, callback);
// Change color
api.changeThreadColor('#0084FF', threadID, callback);
// Add user
api.addUserToGroup(userID, threadID, callback);
// Remove user
api.removeUserFromGroup(userID, threadID, callback);
// Mute/Unmute
api.muteThread(threadID, 3600000, callback); // 1 hour
api.muteThread(threadID, 0, callback); // Unmute// Get user info
api.getUserInfo(userID, (err, info) => {
console.log('Name:', info[userID].name);
console.log('Photo:', info[userID].photo);
});
// Search users
api.searchForUser('John', (err, results) => {
results.forEach(user => console.log(user.name));
});
// Current user ID
const myID = api.getCurrentUserID();// Edit
api.editMessage('Updated!', messageID, callback);
// Delete
api.unsendMessage(messageID, callback);
// React
api.setMessageReaction('π', messageID, callback);api.listenMqtt((err, event) => {
if (err) return console.error(err);
switch(event.type) {
case 'message':
console.log(`π¨ ${event.senderName}: ${event.body}`);
break;
case 'typing':
console.log(`β¨οΈ ${event.senderName} is typing...`);
break;
case 'reaction':
console.log(`π ${event.senderName} reacted with ${event.reaction}`);
break;
}
});| Event | Description | Data |
|---|---|---|
message |
New message | body, senderID, threadID, attachments |
messageEdit |
Message edited | messageID, body, senderID |
messageUnsend |
Message deleted | messageID, senderID |
reaction |
Reaction added | messageID, reaction, userID |
typing |
User typing | isTyping, userID, threadID |
readReceipt |
Message read | reader, time, threadID |
presence |
Online status | userID, statuses |
login(loginData, {
online: true,
selfListen: false,
listenEvents: true,
autoMarkDelivery: true,
autoMarkRead: false,
listenTyping: true,
autoReconnect: true,
logLevel: 'info', // silly, debug, verbose, info, warn, error
userAgent: 'Mozilla/5.0...',
proxy: 'http://proxy:port'
}, (err, api) => {
// ...
});const commands = {
'!help': (args, api, event) => {
api.sendMessage('π Commands available', event.threadID);
},
'!ping': (args, api, event) => {
api.sendMessage('π Pong!', event.threadID);
}
};
api.listenMqtt((err, event) => {
if (err || event.type !== 'message') return;
const [cmd, ...args] = event.body.split(' ');
if (commands[cmd]) {
commands[cmd](args, api, event);
}
});const responses = {
'hello': 'π Hi there!',
'how are you': 'π Great!',
'bye': 'π See you!'
};
api.listenMqtt((err, event) => {
if (err || event.type !== 'message') return;
const body = event.body?.toLowerCase() || '';
Object.entries(responses).forEach(([trigger, response]) => {
if (body.includes(trigger)) {
api.sendMessage(response, event.threadID);
}
});
});const userLimits = {};
const LIMIT = 10;
api.listenMqtt((err, event) => {
if (event.type !== 'message') return;
const userID = event.senderID;
userLimits[userID] = (userLimits[userID] || 0) + 1;
if (userLimits[userID] > LIMIT) {
console.warn(`β οΈ Rate limit for ${userID}`);
return;
}
});const quotes = [
"The only way to do great work is to love what you do. - Steve Jobs",
"Stay hungry, stay foolish. - Steve Jobs"
];
api.listenMqtt((err, event) => {
if (err || event.type !== 'message') return;
if (event.body?.includes('!quote')) {
const quote = quotes[Math.floor(Math.random() * quotes.length)];
api.sendMessage(`π ${quote}`, event.threadID);
}
});const ADMINS = ['123456789', '987654321'];
api.listenMqtt((err, event) => {
if (err || !ADMINS.includes(event.senderID)) return;
const { body, threadID } = event;
if (body?.startsWith('!mute')) {
api.muteThread(threadID, 3600000, () => {
api.sendMessage('π Muted for 1 hour', threadID);
});
}
});// Check credentials
// Try 2FA if enabled
// Verify account isn't locked// Verify thread ID is valid
api.getThreadInfo(threadID, (err, info) => {
if (err) console.error('Thread not found');
});let attempts = 0;
function reconnect() {
if (attempts >= 5) return;
const delay = Math.pow(2, attempts) * 1000;
setTimeout(() => {
login({ appState }, (err, api) => {
if (err) {
attempts++;
reconnect();
} else {
attempts = 0;
console.log('β
Reconnected!');
}
});
}, delay);
}login({ appState }, {
logLevel: 'silly'
}, (err, api) => {
// Full logging enabled
});- Use Environment Variables
# .env
FB_EMAIL=your@email.com
FB_PASSWORD=your_password- Use AppState in Production
// Don't store passwords
const appState = require('./appState.json');
login({ appState }, callback);- Add to .gitignore
appState.json
.env
*.log
- Validate Input
function sanitize(text) {
return text
.replace(/[&<>"']/g, m => ({
'&': '&', '<': '<',
'>': '>', '"': '"',
"'": '''
}[m]))
.trim();
}- Use HTTPS for Proxies
login(data, {
proxy: 'https://secure-proxy:8080'
}, callback);# Install dotenv
npm install dotenvrequire('dotenv').config();
login({
email: process.env.FB_EMAIL,
password: process.env.FB_PASSWORD
}, {
logLevel: process.env.LOG_LEVEL
}, callback);This is an unofficial library. Not endorsed by Facebook/Meta.
β οΈ Use responsibly and comply with Facebook's ToSβ οΈ Unauthorized bots may face account restrictionsβ οΈ Don't spam, harass, or abuse the platformβ οΈ Respect user privacy and data protectionβ οΈ For educational purposes onlyβ οΈ Developers not responsible for misuse
MIT License - See LICENSE file
- Issues: Report bugs
- Discussions: Ask questions
- GitHub: @Sh4nDev
- Facebook: SH AN
- Messenger: SH AN
- WhatsApp: SH AN
Built with β€οΈ by the ShAn Development Team
β If you find this helpful, please give it a star! β
Built with β€οΈ for the Facebook Bot community