UNPKG

fca-priyansh

Version:

Facebook-chat-api made by Priyanshu Rajput

440 lines (318 loc) • 15.6 kB
# FCA Priyansh - Facebook Chat API | Ultimate Facebook Messenger Bot Framework **Maintained by:** [Priyanshu Rajput](https://priyanshuapi.xyz) **GitHub:** [@priyanshfsdev](https://github.com/priyanshfsdev) | **GitLab:** [@priyanshufsdev](https://gitlab.com/priyanshufsdev) | **Instagram:** [@pri_yanshu12](https://instagram.com/pri_yanshu12) | **Telegram:** [@Priyanshrajput](https://t.me/Priyanshrajput) --- ## šŸ“± What is FCA Priyansh? **FCA-Priyansh** is an advanced Facebook Chat API (FCA) library - a powerful Node.js module that enables you to build **Facebook Messenger bots**, **automated chat systems**, and **messaging automation tools** without relying on Facebook's official Bot Platform. This is a community-maintained fork with **faster feature updates** and enhanced functionality. ### šŸ”‘ SEO Keywords Facebook Chat API | Facebook Messenger Bot | FCA | Facebook Bot Framework | Messenger Automation | Chat API Node.js | Facebook API | Automated Messaging | Facebook Messenger API | Bot Development | Node.js Facebook Integration | Priyansh | FCA-Priyansh --- ## šŸŽÆ Key Features & Use Cases - **Automate Facebook Messenger Conversations** - Build intelligent chatbots for customer service, notifications, and engagement - **Send & Receive Messages** - Full message automation with text, images, stickers, and files - **User Account Integration** - Work directly with user accounts (not pages) - **Real-time Listening** - Listen to incoming messages and events in real-time using MQTT - **Session Management** - Save and restore sessions without re-authentication - **Group Chat Automation** - Manage group conversations, members, and settings - **Message Features** - Reactions, typing indicators, read receipts, and more - **File & Media Handling** - Send and receive images, videos, and documents - **Event Listening** - Detect user changes, group updates, and custom events --- ## āš ļø Important Disclaimer This is a **community-maintained library** for educational and authorized use. We are not responsible if your account gets banned for spammy activities such as: - Sending unsolicited messages to strangers - Rapid bulk messaging - Sharing suspicious URLs - Frequent account logins/logouts **Use responsibly and ethically.** Always ensure you have proper authorization before automating conversations. --- ## šŸ“¦ Getting Started This repository is a fork from the main FCA repo with **newer features, faster updates, and enhanced stability**. See [projects using this API](#projects-using-this-api) for real-world examples and use cases. ## šŸš€ Installation ### Quick Start - NPM Installation To install **fca-priyansh** from NPM repository: ```bash npm install fca-priyansh ``` This will download the latest stable version from the official NPM registry. Recommended for production use. ### Bleeding Edge - Direct from Repository To get the latest features and bug fixes directly from GitLab (may include new features before npm release): ```bash npm install https://gitlab.com/priyanshufsdev/fca-priyansh.git ``` Or using GitHub: ```bash npm install https://github.com/priyanshfsdev/fca-priyansh.git ``` ### Requirements - **Node.js 12.0+** or higher - **Facebook Account** (for testing and authentication) - **Internet Connection** - For advanced features: basic knowledge of JavaScript/Node.js ### Recommended for Testing If you want to test your bots without creating another account on Facebook, use [Facebook Whitehat Accounts](https://www.facebook.com/whitehat/accounts/) - perfect for developers and testing automation. --- ## šŸ’” Quick Examples - Build Your First Bot ### 1ļøāƒ£ Simple Echo Bot (Basic Message Automation) Create a simple echo bot that replies to every message: ```javascript const login = require("fca-priyansh"); // Create simple echo bot - Automated Response System login({email: "FB_EMAIL", password: "FB_PASSWORD"}, (err, api) => { if(err) return console.error(err); // Listen for incoming messages in real-time api.listen((err, message) => { // Auto-reply with received message api.sendMessage(message.body, message.threadID); }); }); ``` **Use Case:** Customer support automation, message testing, chat monitoring **Result:** <img width="517" alt="Facebook Messenger Echo Bot" src="https://cloud.githubusercontent.com/assets/4534692/20023545/f8c24130-a29d-11e6-9ef7-47568bdbc1f2.png"> --- ## šŸ“š Complete Documentation ## šŸ› ļø Main Functionality & API Methods ### šŸ“¤ Sending Messages (Complete Guide) #### **api.sendMessage(message, threadID[, callback][, messageID])** Master the art of sending different types of messages through Facebook Messenger: **Supported Message Types:** * **Regular Text Messages:** Set `body` field to your text message * **Sticker Messages:** Set `sticker` field to sticker ID for emoji/image stickers * **File & Image Uploads:** Set `attachment` field to readable stream or array of streams * **Link Sharing:** Set `url` field to share web links with preview * **Emoji Messages:** Set `emoji` field with emoji character and `emojiSize` (small/medium/large) šŸ’” **Pro Tip:** A message can be a regular message (can be empty) plus ONE optional: sticker, attachment, or URL. šŸ’” **Find Your ID:** Look in Facebook cookies, the `userID` is stored as `c_user`. #### **Example 1: Basic Text Message (Simple Chat)** ```js const login = require("fca-priyansh"); login({email: "FB_EMAIL", password: "FB_PASSWORD"}, (err, api) => { if(err) return console.error(err); var userID = "000000000000000"; var message = "Hey! This is an automated message from FCA-Priyansh bot"; api.sendMessage(message, userID); }); ``` **Use Cases:** Customer notifications, alerts, reminders, automated responses --- #### **Example 2: Image/File Upload (Media Sharing)** ```js const fs = require("fs"); const login = require("fca-priyansh"); login({email: "FB_EMAIL", password: "FB_PASSWORD"}, (err, api) => { if(err) return console.error(err); var userID = "000000000000000"; var messageWithImage = { body: "Check out this image!", attachment: fs.createReadStream(__dirname + '/image.jpg') } api.sendMessage(messageWithImage, userID); }); ``` **Use Cases:** photo sharing bots, document distribution, media automation, profile picture updates ---### šŸ” Session Management - Persistent Login #### **Save Your Session (AppState) - Avoid Re-login Every Time** To avoid logging in with credentials every time your bot runs, save the AppState (session cookies) to a file: ```js const fs = require("fs"); const login = require("fca-priyansh"); var credentials = {email: "FB_EMAIL", password: "FB_PASSWORD"}; login(credentials, (err, api) => { if(err) return console.error(err); // Save session to file fs.writeFileSync('appstate.json', JSON.stringify(api.getAppState())); console.log("āœ… Session saved to appstate.json"); }); ``` #### **Restore Session (Login with Saved AppState)** Next time, use the saved session instead of credentials: ```js const fs = require("fs"); const login = require("fca-priyansh"); // Load saved session login({appState: JSON.parse(fs.readFileSync('appstate.json', 'utf8'))}, (err, api) => { if(err) return console.error(err); console.log("āœ… Logged in using saved session!"); // Your bot code here }); ``` **Benefits:** - āœ… No credentials needed in code - āœ… Faster bot startup - āœ… Secure session storage - āœ… Multiple account support **Alternative:** Use [c3c-fbstate](https://github.com/c3cbot/c3c-fbstate) to get fbstate.json (alternate appstate format) --- ### šŸ‘‚ Listening to Messages & Events #### **api.listen(callback) & api.listenMqtt(callback)** Listen to incoming messages and events in real-time using MQTT protocol. Perfect for: - **Real-time chatbots** with instant responses - **Event monitoring** (users joining/leaving groups, title changes) - **Message filtering** and intelligent routing **Configuration Options:** - `listenEvents: true` - Receive group events (join, leave, title change) - `selfListen: true` - Receive your own sent messages - `logLevel: "silent"` - Disable verbose logging #### **Complete Example: Smart Event-Handling Bot** ```js const fs = require("fs"); const login = require("fca-priyansh"); // Advanced bot with event handling login({appState: JSON.parse(fs.readFileSync('appstate.json', 'utf8'))}, (err, api) => { if(err) return console.error(err); // Enable event listening api.setOptions({listenEvents: true}); // Start listening for messages and events var stopListening = api.lisenMqtt((err, event) => { if(err) return console.error(err); // Mark message as read api.markAsRead(event.threadID, (err) => { if(err) console.error(err); }); // Handle different event types switch(event.type) { case "message": // Message received if(event.body === '/stop') { api.sendMessage("Bot stopping...", event.threadID); return stopListening(); } // Auto-reply with command prefix api.sendMessage("BOT REPLY: " + event.body, event.threadID); break; case "event": // Group events (user join/leave, title change) console.log("šŸ“¢ Group Event:", event); api.sendMessage("Group event detected!", event.threadID); break; } }); }); ``` **Event Types You Can Listen To:** - `message` - New message in conversation - `event` - Group changes, user joins/leaves, emoji changes - `presence` - User online/offline status - `read` - Message read receipts **Use Cases:** - Customer support chatbots - Group chat moderators - Auto-responders and notifications - Meeting room alerts - Social media monitoring --- ## ā“ Frequently Asked Questions (FAQ) - FCA Troubleshooting Guide ### Q1: How do I run tests for FCA-Priyansh? > **A:** Create a `test-config.json` file in the test directory (template: `example-config.json`). From the root directory, run: > ```bash > npm test > ``` > This will run all unit tests and integration tests. ### Q2: Why doesn't sendMessage work when I'm logged in as a Facebook Page? > **A:** Facebook Pages have restrictions to prevent spam. Pages cannot initiate conversations with users directly. **Workaround:** Use your personal account instead, or create a custom app to handle page messaging through the official API. ### Q3: How do I fix login errors? (Login not working) > **A:** > 1. First, verify you can manually login to Facebook on the website > 2. If you have login approvals (2FA) enabled, see our login documentation > 3. Try creating a new app password if using strong security > 4. Check if your account is temporarily locked > 5. Read our docs on login handlers for advanced authentication ### Q4: How can I avoid logging in every time? Can I login from a previous session? > **A:** Yes! Use **AppState** caching. Save it with: > ```js > fs.writeFileSync('appstate.json', JSON.stringify(api.getAppState())); > ``` > Then reuse it: > ```js > login({appState: mySavedAppState}, (err, api) => { ... }) > ``` > **Note:** Sessions expire after ~60-90 days. If it fails, create a new login session. ### Q5: How can I send messages as a Facebook Page? > **A:** Yes, but with limitations. Set the pageID during login (NOT with setOptions): > ```js > login(credentials, {pageID: "000000000000000"}, (err, api) => { > // Now send as page > }); > ``` > **Limitation:** Pages still cannot initiate conversations. ### Q6: I'm getting strange syntax errors like "SyntaxError: Unexpected token [" > **A:** **Update your Node.js version!** This library uses modern JavaScript features. Required: Node.js 12.0 or higher. Install the latest LTS version from [nodejs.org](https://nodejs.org) ### Q7: How do I disable the logging/verbose output? > **A:** Use `api.setOptions` to customize logging: > ```js > api.setOptions({ > logLevel: "silent" // Options: "info", "warning", "error", "silent" > }); > ``` > Most detailed option: `logLevel: "trace"` for debugging ### Q8: How do I handle 2FA (Two-Factor Authentication)? > **A:** For 2FA-protected accounts, pass the verification code: > ```js > login({ > email: "FB_EMAIL", > password: "FB_PASSWORD", > twoFactorNumber: "123456" // Your 2FA code > }, callback); > ``` ### Q9: How do I get user/thread IDs? > **A:** User IDs are in Facebook cookies as `c_user`. For threads, use: > ```js > api.getThreadList(10, null, (err, threads) => { > threads.forEach(t => console.log(t.threadID)); > }); > ``` ### Q10: Can I use FCA-Priyansh commercially? > **A:** This is a personal project. Check Facebook's Terms of Service and always get explicit permission before automating user accounts. Not recommended for large-scale commercial applications without legal review. --- ## 🌟 Projects Using FCA-Priyansh Real-world applications built with FCA and FCA-Priyansh: - **[c3c](https://github.com/lequanglam/c3c)** - Advanced customizable Facebook & Discord bot with plugin system - **[Priyansh Facebook Bot](https://gitlab.com/priyanshufsdev/priyanshu-fb-bot)** - Feature-rich automated Messenger bot by Priyanshu Rajput (Creator of FCA-Priyansh) > šŸ’” Built something cool with FCA-Priyansh? Submit a PR to add your project to this list! --- ## šŸ¤ Contributing & Community We welcome contributions! Whether it's: - šŸ› Bug fixes and issue reports - ✨ New features and improvements - šŸ“– Documentation enhancements - šŸ’¬ Community support and examples **How to contribute:** 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Submit a pull request --- ## šŸ‘Øā€šŸ’» About the Developer **Priyanshu Rajput** - Founder & Maintainer of FCA-Priyansh ### Connect With Me: - 🌐 **Website:** [https://priyanshuapi.xyz](https://priyanshuapi.xyz) - šŸ™ **GitHub:** [@priyanshfsdev](https://github.com/priyanshfsdev) - 🦊 **GitLab:** [@priyanshufsdev](https://gitlab.com/priyanshufsdev) - šŸ“ø **Instagram:** [@pri_yanshu12](https://instagram.com/pri_yanshu12) - šŸ’¬ **Telegram:** [@Priyanshrajput](https://t.me/Priyanshrajput) ### Support the Project: - ⭐ Star this repository - šŸ”— Share with friends interested in Facebook automation - šŸ’¬ Report bugs and suggest features - šŸ¤ Contribute code and documentation --- ## šŸ“œ License This project is licensed under the [MIT License](LICENSE) - feel free to use in personal and commercial projects. --- ## āš–ļø Legal Notice **Important:** This library is for **educational use and authorized automation only**. - Ensure you have permission before automating any account - Respect Facebook's Terms of Service - Don't use for spam, harassment, or unauthorized access - The developers are not liable for any account bans or legal issues Always use responsibly and ethically. šŸ™ --- ## šŸš€ Quick Links - **NPM Package:** [fca-priyansh on NPM](https://www.npmjs.com/package/fca-priyansh) - **GitLab Repository:** [priyanshufsdev/fca-priyansh](https://gitlab.com/priyanshufsdev/fca-priyansh) - **GitHub Mirror:** [priyanshfsdev/fca-priyansh](https://github.com/priyanshfsdev/fca-priyansh) - **Full Documentation:** [DOCS.md](DOCS.md) - **Report Issues:** [GitLab Issues](https://gitlab.com/priyanshufsdev/fca-priyansh/-/issues) --- **Happy bot building! šŸ¤–**