Skip to content

Latest commit

Β 

History

178 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”₯ ShAn-FCA - Facebook Chat API

GitHub Language License Status npm version Node Version

πŸ€– An advanced, unofficial Facebook Messenger API library for Node.js By SH AN - Build powerful bots with ease.


πŸ“‹ Table of Contents


πŸš€ Features

Core Features

  • βœ… 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

Advanced Features

  • πŸ” 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

πŸ“¦ Installation

Prerequisites

  • Node.js >= 12.0.0
  • npm >= 6.0.0 or yarn >= 1.22.0

Install via npm

npm install shan-fca

Install via yarn

yarn add shan-fca

Verify Installation

node -e "const login = require('shan-fca'); console.log('βœ… ShAn-FCA installed successfully!');"

πŸ”Œ Quick Start

Simplest Example

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!');
    });
  }
);

Using Promise/Async-Await

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);
  }
})();

πŸ” Authentication

Method 1: Email & Password

login({
  email: process.env.FB_EMAIL,
  password: process.env.FB_PASSWORD
}, (err, api) => {
  if (err) return console.error(err);
  console.log('βœ… Logged in!');
});

Method 2: AppState (Recommended for Production)

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!');
});

Method 3: Two-Factor Authentication (2FA)

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'));
  }
});

πŸ“š API Reference

Send Message

// 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);

Thread Management

// 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

User Information

// 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 & Delete Messages

// Edit
api.editMessage('Updated!', messageID, callback);

// Delete
api.unsendMessage(messageID, callback);

// React
api.setMessageReaction('πŸ‘', messageID, callback);

πŸ‘‚ Event Handling

Listen to Messages

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 Types

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

βš™οΈ Configuration

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) => {
  // ...
});

🎯 Advanced Usage

Command Bot

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);
  }
});

Auto-Reply Bot

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);
    }
  });
});

Rate Limiting

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;
  }
});

πŸ’‘ Examples

Example 1: Quote Bot

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);
  }
});

Example 2: Admin Commands

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);
    });
  }
});

πŸ› Troubleshooting

Login Issues

// Check credentials
// Try 2FA if enabled
// Verify account isn't locked

Messages Not Sending

// Verify thread ID is valid
api.getThreadInfo(threadID, (err, info) => {
  if (err) console.error('Thread not found');
});

Reconnection

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);
}

Debug Mode

login({ appState }, {
  logLevel: 'silly'
}, (err, api) => {
  // Full logging enabled
});

πŸ”’ Security

Best Practices

  1. Use Environment Variables
# .env
FB_EMAIL=your@email.com
FB_PASSWORD=your_password
  1. Use AppState in Production
// Don't store passwords
const appState = require('./appState.json');
login({ appState }, callback);
  1. Add to .gitignore
appState.json
.env
*.log
  1. Validate Input
function sanitize(text) {
  return text
    .replace(/[&<>"']/g, m => ({
      '&': '&amp;', '<': '&lt;', 
      '>': '&gt;', '"': '&quot;',
      "'": '&#039;'
    }[m]))
    .trim();
}
  1. Use HTTPS for Proxies
login(data, {
  proxy: 'https://secure-proxy:8080'
}, callback);

πŸ“ Environment Variables

# Install dotenv
npm install dotenv
require('dotenv').config();

login({
  email: process.env.FB_EMAIL,
  password: process.env.FB_PASSWORD
}, {
  logLevel: process.env.LOG_LEVEL
}, callback);

⚠️ Disclaimer

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

πŸ“„ License

MIT License - See LICENSE file


πŸ“ž Support


πŸŽ‰ Acknowledgments

Built with ❀️ by the ShAn Development Team


⭐ If you find this helpful, please give it a star! ⭐

Built with ❀️ for the Facebook Bot community

↑ Back to Top

About

This is a facebook chat api unofficial for Facebook bot and ShAn.s-Bot

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages