### Install Project Dependencies Source: https://github.com/minhhuydev/fbchat-v2/blob/main/README.md Install all required Python packages listed in the requirements.txt file using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Upload and Send an Image Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README_EN.md This example shows how to upload an image file and then send it as a message. It first uses `_uploadAttachment` to get an `attachmentID`, then sends the message with the `typeAttachment` set to 'image' and provides the `attachmentID`. ```python from _messaging._attachments import _uploadAttachment from _messaging._send import api uploaded = _uploadAttachment("path/to/image.jpg", dataFB) sender = api() print(sender.send( dataFB, "Here is your image", "1234567890", typeAttachment="image", attachmentID=uploaded["attachmentID"], )) ``` -------------------------------- ### Unsend a Message (Example) Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README_EN.md Provides a direct example of calling the `func` to unsend a message using a placeholder message ID and the `dataFB` object. ```python from _messaging._unsend import func print(func("mid.$abc...", dataFB)) ``` -------------------------------- ### Fetch Pending Requests (Example) Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README_EN.md Demonstrates how to call the `func` to fetch pending message requests, passing the `dataFB` object for authentication. ```python from _messaging._message_requests import func print(func(dataFB)) ``` -------------------------------- ### Listen for Real-time Events via MQTT Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README_EN.md Sets up a listener to receive messages and events in real-time using MQTT. It initializes `listeningEvent`, retrieves the last sequence ID, and starts a background thread to connect to the MQTT broker. Ensure this runs in a dedicated thread to avoid blocking. ```python import threading from _messaging._listening import listeningEvent listener = listeningEvent(dataFB) listener.get_last_seq_id() threading.Thread(target=listener.connect_mqtt, daemon=True).start() ``` -------------------------------- ### Get Marketplace Product Information Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Use this function to retrieve detailed information about a Marketplace product using its ID. ```python getInformationProductItemMarketPlace(dataFB, idProductItem) ``` -------------------------------- ### Get Message Requests Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README.md Retrieves a list of pending message requests. ```APIDOC ## Get Message Requests ### Description Retrieves a list of pending message requests (messages in the "Message Requests" folder). ### Method `_message_requests.getMessageRequests(dataFB)` ### Parameters - **dataFB** (object) - Required - Data object containing session and token information. ### Response - The response containing the list of message requests. Specific success/error structure not detailed in the source. ``` -------------------------------- ### Get Notifications Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Retrieves the latest notifications for the user's account. ```APIDOC ## `_features._facebook._notification` — Lấy thông báo ### `func(dataFB) -> dict` Lấy danh sách thông báo mới nhất của tài khoản. ```python from _core._session import dataGetHome from _features._facebook import _notification dataFB = dataGetHome("c_user=...; xs=...") result = _notification.func(dataFB) if result.get("success") == 1: for notif in result["NotificationResults"]: print(notif) else: print(f"❌ {result.get('messages')}") ``` **Parameters:** - `dataFB` (dict): Session data, typically obtained from `dataGetHome`. ``` -------------------------------- ### Get User Info Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Retrieves information about a Facebook user. ```APIDOC ## `_features._facebook._get_user_info` — Lấy thông tin người dùng This function is documented to retrieve user information but lacks specific details on its parameters and return values in the provided source. Please refer to the library's source code or additional documentation for usage details. ``` -------------------------------- ### Get User Information Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Use this function to fetch detailed user information via the user info chat endpoint. It returns a dictionary of details on success or an error object. ```python func(dataFB, userID) ``` -------------------------------- ### Get Notifications Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Use this function to retrieve a list of user notifications. It returns a success object with notification results or an error object. ```python func(dataFB) ``` -------------------------------- ### Get Pending Messages Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Retrieves a list of messages awaiting approval in the PENDING inbox using a GraphQL batch request. Requires session cookies for authentication. ```python from _core._session import dataGetHome from _messaging._message_requests import func as get_pending dataFB = dataGetHome("c_user=...; xs=...") result = get_pending(dataFB) if result.get("success") == 1: import json data = json.loads(result["messageRequests"]) print(f"Số tin nhắn chờ: {data['total_count']}") for i in range(data['total_count']): msg = data[i] print(f" [{i+1}] Từ {msg['senderID']}: {msg['snippet']} ({msg['timestamp_precise']})") ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/minhhuydev/fbchat-v2/blob/main/README.md It is recommended to create a virtual environment for managing project dependencies. Activate it using the appropriate command for your operating system. ```bash python -m venv .venv ``` ```bash # Windows (PowerShell) .venv\Scripts\activate ``` ```bash # macOS / Linux source .venv/bin/activate ``` -------------------------------- ### Run the Demo Bot Source: https://github.com/minhhuydev/fbchat-v2/blob/main/README.md Execute the main.py script to run a minimal demo bot. Ensure you have configured your Facebook cookies in src/config.json before running. ```bash python src/main.py ``` -------------------------------- ### Initialize Session from Cookies Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md Use dataGetHome to initialize a session by parsing user cookies and extracting necessary tokens like fb_dtsg and jazoest. This is crucial for subsequent requests. ```python # src/_core/_session.py dataGetHome(setCookies: str) -> dict ``` -------------------------------- ### Get Inbox and Thread Data Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Fetches inbox data and extracts metadata for individual threads. ```APIDOC ## Get Inbox and Thread Data ### Description Fetches a list of inbox threads (up to 50) and extracts metadata for each thread. It also provides `last_seq_id` for MQTT listeners. ### Functions - `_all_thread_data.func(dataFB) -> dict`: Retrieves inbox data and thread metadata. - `_all_thread_data.features(dataGet, threadID, commandUse) -> dict`: Extracts specific details for a given thread. ### Parameters - **dataFB**: Session data obtained from `dataGetHome`. - **dataGet**: Data obtained from the `func` call, used for `features`. - **threadID** (string) - Required - The ID of the thread to get details for. - **commandUse** (string) - Required - The specific command to use (e.g., "getAdmin", "threadInfomation", "exportMemberListToJson"). ### Request Example ```python from _core._session import dataGetHome from _features._thread import _all_thread_data dataFB = dataGetHome("c_user=...; xs=...") inbox = _all_thread_data.func(dataFB) threads = inbox["dataAllThread"] THREAD_ID = threads["threadIDList"][0] dataGet = inbox["dataGet"] # Get list of admins admins = _all_thread_data.features(dataGet, THREAD_ID, "getAdmin") # Get full thread information info = _all_thread_data.features(dataGet, THREAD_ID, "threadInfomation") # Export member list to JSON members = _all_thread_data.features(dataGet, THREAD_ID, "exportMemberListToJson") ``` ### Response (func) - **ProcessingTime** (float) - Time taken to process the request. - **last_seq_id** (string) - Sequence ID for MQTT listener. - **dataAllThread** (dict) - Contains thread data including `countThread`, `threadNameList`, `threadIDList`. - **dataGet** (any) - Data used by the `features` function. ### Response (features - example for `threadInfomation`) - **nameThread** (string) - The name of the thread. - **IDThread** (string) - The ID of the thread. - **emojiThread** (string) - The thread's emoji. - **messageCount** (integer) - The number of messages in the thread. - **adminThreadCount** (integer) - The number of admins in the thread. - **memberCount** (integer) - The number of members in the thread. - **approvalMode** (string) - Approval mode status. - **joinableMode** (string) - Joinable mode status. - **urlJoinableThread** (string) - URL to join the thread. ``` -------------------------------- ### Prepare Request Arguments Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md Generates keyword arguments ready to be used with requests.post, including necessary headers and data. ```python # src/_core/_utils.py mainRequests(urlRequests, dataForm, setCookies) ``` -------------------------------- ### Get Latest Notifications Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Retrieves the most recent notifications for the account. Requires session cookies for authentication. ```python from _core._session import dataGetHome from _features._facebook import _notification dataFB = dataGetHome("c_user=...; xs=...") result = _notification.func(dataFB) if result.get("success") == 1: for notif in result["NotificationResults"]: print(notif) else: print(f"❌ {result.get('messages')}") ``` -------------------------------- ### Clone fbchat-v2 Repository Source: https://github.com/minhhuydev/fbchat-v2/blob/main/README.md Use this command to clone the project repository from GitHub. Alternatively, you can download the project as a ZIP file. ```bash git clone https://github.com/MinhHuyDev/fbchat-v2 cd fbchat-v2 ``` -------------------------------- ### Get User Info Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Retrieves detailed information about a Facebook user using their User ID (UID). ```APIDOC ## Get User Info ### Description Retrieves detailed information about a Facebook user using their User ID (UID). ### Method Signature `func(dataFB, userID) -> dict` ### Parameters - **dataFB**: Session data obtained from `dataGetHome`. - **userID** (string) - Required - The Facebook User ID. ### Request Example ```python from _core._session import dataGetHome from _features._facebook import _get_user_info dataFB = dataGetHome("c_user=...; xs=...") info = _get_user_info.func(dataFB, userID="100034261636200") ``` ### Response - **err** (int) - Error code (0 indicates success). - **name** (string) - User's name. - **id** (string) - User's ID. - **url** (string) - URL to the user's profile. ### Response Example ```json { "err": 0, "name": "John Doe", "id": "100034261636200", "url": "https://www.facebook.com/app_scoped_user_id/" } ``` ``` -------------------------------- ### Get Notifications Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Fetches notifications from Facebook. Requires a valid dataFB object obtained from session data. ```python from _core._session import dataGetHome from _features._facebook import _notification, _blocking from _features._thread import _changeEmoji, _all_thread_data dataFB = dataGetHome("c_user=...; xs=...") # Lấy thông báo print(_notification.func(dataFB)) ``` -------------------------------- ### Directory Structure of _messaging Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README.md Overview of the file structure within the _messaging module. ```text src/_messaging/ ├── __init__.py ├── _attachments.py # Upload tệp → attachmentID ├── _listening.py # MQTT realtime listener ├── _message_requests.py # Tin nhắn chờ ├── _reactions.py # Thả / gỡ reaction ├── _send.py # Gửi tin nhắn (HTTP) ├── _unsend.py # Thu hồi tin nhắn ├── README.md # ← bạn đang ở đây └── README_EN.md ``` -------------------------------- ### MQTT Realtime Listener Class Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README.md The `listeningEvent` class connects to Messenger's MQTT over WebSocket for real-time event listening. The `connect_mqtt()` method is blocking and should be run in a separate thread or process. `bodyResults` contains event details like message content, sender, and attachments. ```python class listeningEvent(dataFB): # ... methods like get_last_seq_id(), connect_mqtt() pass ``` ```text body · timestamp · userID · messageID · replyToID · type attachments.id · attachments.url ``` -------------------------------- ### Get Pending Messages Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Retrieves a list of messages that are pending approval in the PENDING mailbox using a GraphQL batch request. ```APIDOC ## `_messaging._message_requests` — Tin nhắn chờ (Pending) ### `func(dataFB) -> dict` Lấy danh sách tin nhắn đang chờ phê duyệt (hộp thư `PENDING`) qua GraphQL batch. ```python from _core._session import dataGetHome from _messaging._message_requests import func as get_pending dataFB = dataGetHome("c_user=...; xs=...") result = get_pending(dataFB) if result.get("success") == 1: import json data = json.loads(result["messageRequests"]) print(f"Số tin nhắn chờ: {data['total_count']}") for i in range(data['total_count']): msg = data[i] print(f" [{i+1}] Từ {msg['senderID']}: {msg['snippet']} ({msg['timestamp_precise']})") ``` **Parameters:** - `dataFB` (dict): Session data, typically obtained from `dataGetHome`. ``` -------------------------------- ### Initialize dataFB from Cookies Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md Use this to initialize the dataFB object with session cookies. This is required for subsequent operations that rely on an authenticated session. ```python from _core._session import dataGetHome setCookies = "c_user=...; xs=...; fr=...; datr=..."; dataFB = dataGetHome(setCookies) print(dataFB["FacebookID"]) print(dataFB["fb_dtsg"]) ``` -------------------------------- ### Listen for Realtime Events Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README.md Listens for realtime events via MQTT over WebSocket. This method is blocking and should be run in a separate thread or process. ```APIDOC ## Listen for Realtime Events ### Description Listens for realtime events via MQTT over WebSocket (`wss://edge-chat.facebook.com/...`). This method is blocking and should be run in a separate thread or process. ### Class `listeningEvent(dataFB)` ### Methods - **`get_last_seq_id()`**: Retrieves and updates the latest `last_seq_id`. - **`connect_mqtt()`**: Initializes the MQTT client, subscribes to the sync queue, and receives message deltas. This method is blocking (`loop_forever()`). ### Event Data Structure When an event occurs, `self.bodyResults` will contain: - **body** (string) - The message content. - **timestamp** (integer) - The event timestamp. - **userID** (string) - The ID of the user who sent the message. - **messageID** (string) - The ID of the message. - **replyToID** (string) - The ID of the message this is a reply to. - **type** (string) - The type of the event. - **attachments.id** (string) - The ID of the attachment. - **attachments.url** (string) - The URL of the attachment. ### Notes - Includes a reconnect mechanism for unexpected disconnections. - Handles `errorCode == 100` (queue overflow) by resetting the queue token. - `connect_mqtt()` is blocking, so it should be executed in a separate thread or process. ``` -------------------------------- ### Get Facebook User Info by UID Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Retrieves detailed information about a Facebook user using their User ID. Requires session data. ```python from _core._session import dataGetHome from _features._facebook import _get_user_info dataFB = dataGetHome("c_user=...; xs=...") info = _get_user_info.func(dataFB, userID="100034261636200") if info.get("err") != 0: print(f"Tên: {info.get('name')}") print(f"UID: {info.get('id')}") print(f"URL: {info.get('url')}") else: print("❌ Không lấy được thông tin người dùng.") ``` -------------------------------- ### Upload and Send Image - Python Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README.md Uploads an image file and then sends it as a message with a caption. Ensure the file path is correct and accessible. ```python from _messaging._attachments import _uploadAttachment from _messaging._send import api uploaded = _uploadAttachment("path/to/image.jpg", dataFB) sender = api() print(sender.send( dataFB, "Ảnh của bạn đây", "1234567890", typeAttachment="image", attachmentID=uploaded["attachmentID"], )) ``` -------------------------------- ### Initialize Session with Cookies Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Use this function to access Facebook and extract necessary tokens by providing a cookie string. It returns a dataFB dictionary essential for most library functions. Ensure your cookies are valid to avoid errors. ```python from _core._session import dataGetHome setCookies = "c_user=61551671683861; xs=8:abc123...; fr=0KEtD...; datr=aMM8Z...;" dataFB = dataGetHome(setCookies) # Kiểm tra cookie còn sống không if not dataFB.get("FacebookID") or "Unable to retrieve" in str(dataFB.get("FacebookID")): raise SystemExit("❌ Cookie đã hết hạn hoặc không hợp lệ.") print(f"✅ Đã đăng nhập: FacebookID = {dataFB['FacebookID']}") print(f" fb_dtsg = {dataFB['fb_dtsg']}") print(f" sessionID = {dataFB['sessionID']}") # dataFB schema: # { # "fb_dtsg": "AQH...", # CSRF token runtime # "fb_dtsg_ag": "AQH...", # Biến thể fb_dtsg # "jazoest": "25678", # "hash": "abc123", # "sessionID": "xyz", # "FacebookID": "61551671683861", # "clientRevision": 1009977215, # "cookieFacebook": "c_user=...;" # Cookie gốc # } ``` -------------------------------- ### Get All Inbox Threads Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Retrieves all inbox threads along with the last sequence ID. Requires a valid dataFB object. The returned dictionary contains 'dataAllThread'. ```python from _core._session import dataGetHome from _features._facebook import _notification, _blocking from _features._thread import _changeEmoji, _all_thread_data dataFB = dataGetHome("c_user=...; xs=...") # Lấy toàn bộ inbox threads = _all_thread_data.func(dataFB) print(threads["dataAllThread"]) ``` -------------------------------- ### Session Initialization Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md Initializes a user session by parsing cookies and extracting necessary tokens like fb_dtsg, jazoest, and others. This is the primary method for establishing a connection to Facebook services. ```APIDOC ## dataGetHome(setCookies: str) -> dict ### Description Accesses `https://www.facebook.com/` using the provided cookies to extract essential tokens for session management. ### Method GET ### Endpoint `https://www.facebook.com/` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **dataFB** (dict) - A dictionary containing session tokens and user information. Keys include `fb_dtsg`, `fb_dtsg_ag`, `jazoest`, `hash`, `sessionID`, `FacebookID`, `clientRevision`, `cookieFacebook`. #### Response Example ```json { "fb_dtsg": "...", "fb_dtsg_ag": "...", "jazoest": "...", "hash": "...", "sessionID": "...", "FacebookID": "...", "clientRevision": "...", "cookieFacebook": { "c_user": "...", "xs": "...", "fr": "...", "datr": "..." } } ``` ``` -------------------------------- ### Send and Unsend Messages Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Demonstrates how to send a message and then immediately unsend it using its message ID. Also shows how to unsend a message if the message ID is already known. ```python result = sender.send(dataFB, "Tin này sẽ bị thu hồi", "4805171782880318") if result.get("success") == 1: mid = result["payload"]["messageID"] print(f"Đã gửi: {mid}") # Thu hồi tin nhắn unsend_result = unsend(mid, dataFB) print(unsend_result) # ✅ {'success': 1, 'messages': 'Thu hồi tin nhắn thành công.'} # ❌ Exception({'error': '...'}) # Thu hồi tin nhắn bất kỳ (cần biết messageID) mid_known = "mid.$cAABa-wot0daSn4Obo2Mbj5L5njhO" print(unsend(mid_known, dataFB)) ``` -------------------------------- ### Create Feature Branch Source: https://github.com/minhhuydev/fbchat-v2/blob/main/README.md Use this command to create a new branch for a feature according to the contribution guidelines. ```bash git checkout -b feat/ ``` -------------------------------- ### Create Secondary Profile Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Use this function to create a secondary profile on the same account. Note that this functionality is only available for eligible accounts. ```python func(dataFB, newName, newUsername) ``` -------------------------------- ### Listen for Real-time Messages Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Connects to Facebook MQTT via WebSocket to receive messages and events in real-time. This function is blocking and should be run in a separate thread. It requires an initial `dataFB` object obtained from `dataGetHome`. ```python import threading import time from _core._session import dataGetHome from _messaging._listening import listeningEvent dataFB = dataGetHome("c_user=...; xs=...") # Khởi tạo listener listener = listeningEvent(dataFB) listener.get_last_seq_id() # Lấy last_seq_id mới nhất # Chạy MQTT trong thread daemon (blocking call) t = threading.Thread(target=listener.connect_mqtt, daemon=True) t.start() print("Đang lắng nghe tin nhắn... Nhấn Ctrl+C để thoát.") last_mid = None try: while True: snap = listener.bodyResults mid = snap.get("messageID") if mid and mid != last_mid: last_mid = mid print(f"\n📨 Tin nhắn mới:") print(f" Từ userID : {snap['userID']}") print(f" Tại threadID: {snap['replyToID']}") print(f" Loại : {snap['type']}") # "user" hoặc "thread" print(f" Nội dung : {snap['body']}") print(f" Timestamp : {snap['timestamp']}") if snap["attachments"]["url"]: print(f" Đính kèm : {snap['attachments']['url']}") time.sleep(0.3) except KeyboardInterrupt: print("Đã dừng.") # bodyResults schema: # { # "body": "nội dung tin nhắn", # "timestamp": "1702314310077", # "userID": "1619995045", # "messageID": "mid.$gABESRz00DD6Sixx...", # "replyToID": "4805171782880318", # "type": "thread", # hoặc "user" # "attachments": {"id": "...", "url": "https://..."} # } ``` -------------------------------- ### Send and Unsend Messages Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Demonstrates how to send a message and then immediately unsend it using the sender and unsend functions. It also shows how to unsend a message if the message ID is known. ```APIDOC ## Send and Unsend Messages This section covers sending a message and then optionally un-sending it, or un-sending a message given its ID. ### Send Message ```python result = sender.send(dataFB, "Tin này sẽ bị thu hồi", "4805171782880318") if result.get("success") == 1: mid = result["payload"]["messageID"] print(f"Đã gửi: {mid}") ``` ### Unsend Message (Immediately after sending) ```python # Assuming 'mid' is obtained from the send operation above unsend_result = unsend(mid, dataFB) print(unsend_result) ``` ### Unsend Message (Known Message ID) ```python mid_known = "mid.$cAABa-wot0daSn4Obo2Mbj5L5njhO" print(unsend(mid_known, dataFB)) ``` **Note:** The `unsend` function requires the message ID (`mid`) and session data (`dataFB`). ``` -------------------------------- ### HTTP Utilities Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md Provides utility functions for handling HTTP requests, including header generation, cookie parsing, and request argument preparation. ```APIDOC ## HTTP Utilities ### Headers(dataForm=None, Host=None) -> dict Generates standard HTTP headers for requests. Automatically adds `Content-Length` if `dataForm` is provided. ### parse_cookie_string(cookie_string: str) -> dict Parses a raw cookie string into a dictionary format suitable for the `requests` library. ### mainRequests(urlRequests, dataForm, setCookies) -> dict Prepares keyword arguments for `requests.post` calls, including URL, data, and cookies. ``` -------------------------------- ### Send a Text Message Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README_EN.md Demonstrates how to send a simple text message. Requires an initialized sender object and `dataFB` for authentication. The `threadID` is used to specify the recipient or group. ```python from _messaging._send import api sender = api() print(sender.send(dataFB, "Hello", "1234567890")) ``` -------------------------------- ### loginFacebook(username, password, AuthenticationGoogleCode=None).main() -> dict Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Logs into a Facebook account using email/phone number and password. Automatically handles two-factor authentication (2FA) if a TOTP key is provided. Returns the session cookie upon success. ```APIDOC ## loginFacebook(username, password, AuthenticationGoogleCode=None).main() -> dict ### Description Logs into a Facebook account using email/phone number and password. Automatically handles two-factor authentication (2FA) if a TOTP key is provided. Returns the session cookie upon success. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method POST ### Endpoint (Internal API endpoint, not directly exposed as HTTP) ### Request Example ```python from _core._facebookLogin import loginFacebook # Standard login (no 2FA) client = loginFacebook( username="minhhuydev@icloud.com", password="mypassword123", AuthenticationGoogleCode=None, # Skip if no 2FA ) result = client.main() if result.get("success"): setCookies = result["success"]["setCookies"] accessToken = result["success"]["accessTokenFB"] print(f"✅ Login successful!") print(f" Cookie: {setCookies[:60]}...") print(f" AccessToken: {accessToken[:40]}...") else: err = result["error"] print(f"❌ Login failed: {err['description']} (code {err['error_code']})") # Example error: {'error': {'title': 'Wrong Credentials', # 'description': 'Invalid username or password', # 'error_subcode': 1348131, 'error_code': 401}} # Login with 2FA (provide 16-character secret key from Facebook) client_2fa = loginFacebook( username="minhhuydev@icloud.com", password="mypassword123", AuthenticationGoogleCode="JBSWY3DPEHPK3PXP", # 2FA secret key ) result_2fa = client_2fa.main() ``` ### Response #### Success Response (200) - **success** (dict) - **setCookies** (str) - Session cookies. - **accessTokenFB** (str) - Facebook access token. #### Error Response - **error** (dict) - **title** (str) - Error title. - **description** (str) - Detailed error description. - **error_subcode** (int) - **error_code** (int) #### Response Example (Success) ```json { "success": { "setCookies": "c_user=...; xs=...;", "accessTokenFB": "EAA..." } } ``` #### Response Example (Error) ```json { "error": { "title": "Wrong Credentials", "description": "Invalid username or password", "error_subcode": 1348131, "error_code": 401 } } ``` ``` -------------------------------- ### Create a New Post Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Creates a new post on the user's timeline. An optional attachment ID can be provided. Requires session cookies. ```python from _core._session import dataGetHome from _features._facebook import _createPost dataFB = dataGetHome("c_user=...; xs=...") result = _createPost.func( dataFB, newContents="Xin chào từ fbchat-v2! 🚀 #Python #Facebook", ) if result.get("success"): print(f"✅ Đăng bài thành công: {result.get('urlPost')}") # https://www.facebook.com/permalink.php?story_fbid=... else: print(f"❌ Lỗi: {result.get('error')}") ``` -------------------------------- ### Configure PYTHONPATH for src/ Import Source: https://github.com/minhhuydev/fbchat-v2/blob/main/README.md To allow direct imports from the 'src/' directory (e.g., `from src._core import ...`), set the PYTHONPATH environment variable. This is crucial when running scripts from the project's root directory. ```bash # Windows (PowerShell) $env:PYTHONPATH = "src" ``` ```bash # macOS / Linux export PYTHONPATH=src ``` -------------------------------- ### Fetch All Threads Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README_EN.md Fetches the entire inbox, including thread data and the last sequence ID. Requires a valid `dataFB` session object. ```python from _core._session import dataGetHome from _features._facebook import _notification, _blocking from _features._thread import _changeEmoji, _all_thread_data dataFB = dataGetHome("c_user=...; xs=...") # Fetch the entire inbox threads = _all_thread_data.func(dataFB) print(threads["dataAllThread"]) ``` -------------------------------- ### Search Users Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Use this function to search for users. It returns a formatted string for bot/CLI use and a list of dictionaries containing user details. ```python func(dataFB, keywordSearch) ``` -------------------------------- ### Public API of _messaging Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README.md Lists the modules exposed by the _messaging package for import. ```python # src/_messaging/__init__.py __all__ = [ "_attachments", "_listening", "_reactions", "_send", "_unsend", "_message_requests", ] ``` -------------------------------- ### General Form Builder Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md This function serves as the backbone for most request flows, supporting both GraphQL and legacy/minimal request modes by including appropriate parameters. ```python # src/_core/_utils.py formAll(dataFB, FBApiReqFriendlyName=None, docID=None, requireGraphql=None) ``` -------------------------------- ### Create Post Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Creates a new post on the user's Facebook timeline. ```APIDOC ## `_features._facebook._createPost` — Đăng bài viết ### `func(dataFB, newContents, attachmentID=None) -> dict` Tạo bài viết mới trên timeline tài khoản. ```python from _core._session import dataGetHome from _features._facebook import _createPost dataFB = dataGetHome("c_user=...; xs=...") result = _createPost.func( dataFB, newContents="Xin chào từ fbchat-v2! 🚀 #Python #Facebook", ) if result.get("success"): print(f"✅ Đăng bài thành công: {result.get('urlPost')}") else: print(f"❌ Lỗi: {result.get('error')}") ``` **Parameters:** - `dataFB` (dict): Session data, typically obtained from `dataGetHome`. - `newContents` (str): The content of the post. - `attachmentID` (str, optional): The ID of an attachment to include in the post. Defaults to `None`. ``` -------------------------------- ### Create Marketplace Item Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Use this function to post a new item on Facebook Marketplace. `photoIDList` should be obtained from `_messaging._attachments`. ```python createItem(dataFB, nameItem, brandItem, priceItem, currencyItem, decriptionItem, hashtagList, typeItem, photoIDList, locationSeller) ``` -------------------------------- ### dataGetHome(setCookies: str) -> dict Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Accesses Facebook homepage with provided cookies to extract necessary tokens (fb_dtsg, jazoest, FacebookID, etc.) and returns the dataFB dictionary. ```APIDOC ## dataGetHome(setCookies: str) -> dict ### Description Accesses `https://www.facebook.com/` with provided cookies, extracts necessary tokens (`fb_dtsg`, `jazoest`, `FacebookID`, etc.) and returns the `dataFB` dictionary, which is a required parameter for most other APIs in the library. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method GET ### Endpoint `https://www.facebook.com/` ### Request Example ```python from _core._session import dataGetHome setCookies = "c_user=61551671683861; xs=8:abc123...; fr=0KEtD...; datr=aMM8Z...;" dataFB = dataGetHome(setCookies) # Check if cookie is still valid if not dataFB.get("FacebookID") or "Unable to retrieve" in str(dataFB.get("FacebookID")): raise SystemExit("❌ Cookie has expired or is invalid.") print(f"✅ Logged in: FacebookID = {dataFB['FacebookID']}") print(f" fb_dtsg = {dataFB['fb_dtsg']}") print(f" sessionID = {dataFB['sessionID']}") ``` ### Response #### Success Response (200) - **dataFB** (dict) - Dictionary containing session tokens and user information. - **fb_dtsg** (str) - CSRF token runtime - **fb_dtsg_ag** (str) - Variant of fb_dtsg - **jazoest** (str) - **hash** (str) - **sessionID** (str) - **FacebookID** (str) - **clientRevision** (int) - **cookieFacebook** (str) - Original cookie #### Response Example ```json { "fb_dtsg": "AQH...", "fb_dtsg_ag": "AQH...", "jazoest": "25678", "hash": "abc123", "sessionID": "xyz", "FacebookID": "61551671683861", "clientRevision": 1009977215, "cookieFacebook": "c_user=...;" } ``` ``` -------------------------------- ### Git Branching for Features Source: https://github.com/minhhuydev/fbchat-v2/blob/main/README_EN.md Use this command to create a new branch for developing a feature. Follow the Conventional Commits specification for commit messages. ```bash git checkout -b feat/ ``` -------------------------------- ### Send GraphQL Request Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md This snippet demonstrates how to send a GraphQL request to the Facebook API using the library's utilities. Ensure dataFB is initialized and the necessary variables are set. ```python import json, requests from _core._utils import formAll, mainRequests dataForm = formAll( dataFB, FBApiReqFriendlyName="CometNotificationsDropdownQuery", docID=6770067089747450, ) dataForm["variables"] = json.dumps({ "count": 10, "environment": "MAIN_SURFACE", "scale": 1, }) resp = requests.post(**mainRequests( "https://www.facebook.com/api/graphql/", dataForm, dataFB["cookieFacebook"], )) print(resp.status_code) ``` -------------------------------- ### Listening for Real-time Messages Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Connects to Facebook MQTT via WebSocket to receive real-time messages and events. This function is blocking and should be run in a separate thread. ```APIDOC ## _messaging._listening.listeningEvent ### Description Connects to Facebook MQTT via WebSocket (`wss://edge-chat.facebook.com`) to receive real-time messages and events. This function is blocking (`loop_forever()`) and should be run in a separate thread. ### Method Signature `listeningEvent(dataFB)` ### Parameters - **dataFB** (dict) - Session data required for authentication. ### Usage Example ```python import threading import time from _core._session import dataGetHome from _messaging._listening import listeningEvent dataFB = dataGetHome("c_user=...; xs=...") listener = listeningEvent(dataFB) listener.get_last_seq_id() # Get the latest last_seq_id # Run MQTT in a daemon thread (blocking call) t = threading.Thread(target=listener.connect_mqtt, daemon=True) t.start() print("Listening for messages... Press Ctrl+C to exit.") last_mid = None try: while True: snap = listener.bodyResults mid = snap.get("messageID") if mid and mid != last_mid: last_mid = mid print(f"\n📨 New message:") print(f" From userID : {snap['userID']}") print(f" In threadID: {snap['replyToID']}") print(f" Type : {snap['type']}") # "user" or "thread" print(f" Content : {snap['body']}") print(f" Timestamp : {snap['timestamp']}") if snap["attachments"]["url"]: print(f" Attachment : {snap['attachments']['url']}") time.sleep(0.3) except KeyboardInterrupt: print("Stopped.") # bodyResults schema: # { # "body": "message content", # "timestamp": "1702314310077", # "userID": "1619995045", # "messageID": "mid.$gABESRz00DD6Sixx...", # "replyToID": "4805171782880318", # "type": "thread", # or "user" # "attachments": {"id": "...", "url": "https://..."} # } ``` ``` -------------------------------- ### Toggle Professional Mode Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Use this function to enable or disable Professional Mode for an account. The `statusBusiness` parameter accepts various string and boolean values. ```python func(dataFB, statusBusiness=None) ``` -------------------------------- ### Create New Post Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_features/README.md Use this function to create a new post on the user's timeline. The `attachmentID` parameter is a fallback and not currently active in the flow. ```python func(dataFB, newContents, attachmentID=None) ``` -------------------------------- ### Minimal Payload (non-GraphQL) Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md Construct a minimal payload for non-GraphQL requests. This is useful for simpler API interactions where a full GraphQL structure is not needed. ```python from _core._utils import formAll payload = formAll(dataFB, requireGraphql=False) payload["message_id"] = "mid...." ``` -------------------------------- ### Facebook Login with 2FA Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md Handles the process of logging into Facebook using a username and password, with support for two-factor authentication. ```python # src/_core/_facebookLogin.py # (Functionality not shown in detail, only module purpose described) ``` -------------------------------- ### Login with Username and Password Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt This function logs into Facebook using credentials and optionally handles two-factor authentication (2FA) with a provided secret key. It returns session cookies and an access token upon successful login. ```python from _core._facebookLogin import loginFacebook # Đăng nhập thường (không 2FA) client = loginFacebook( username="minhhuydev@icloud.com", password="mypassword123", AuthenticationGoogleCode=None, # bỏ qua nếu không có 2FA ) result = client.main() if result.get("success"): setCookies = result["success"]["setCookies"] accessToken = result["success"]["accessTokenFB"] print(f"✅ Đăng nhập thành công!") print(f" Cookie: {setCookies[:60]}...") print(f" AccessToken: {accessToken[:40]}...") else: err = result["error"] print(f"❌ Đăng nhập thất bại: {err['description']} (code {err['error_code']})") # Ví dụ lỗi: {'error': {'title': 'Wrong Credentials', # 'description': 'Invalid username or password', # 'error_subcode': 1348131, 'error_code': 401}} # Đăng nhập có 2FA (cung cấp secret key 16 ký tự từ Facebook) client_2fa = loginFacebook( username="minhhuydev@icloud.com", password="mypassword123", AuthenticationGoogleCode="JBSWY3DPEHPK3PXP", # secret key 2FA ) result_2fa = client_2fa.main() ``` -------------------------------- ### Core Module Exports Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md This snippet shows the public API of the _core module, indicating which submodules are available for import. ```python # src/_core/__init__.py __all__ = ["_session", "_utils", "_facebookLogin"] ``` -------------------------------- ### Upload Attachment API Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_messaging/README.md Use `_uploadAttachment` to upload a single file and obtain an `attachmentID` required for sending attachments. Note that errors are printed to the console instead of raising detailed exceptions. ```python _uploadAttachment(filenames, dataFB) ``` ```json { "attachmentID": ..., "attachmentUrl": ..., "attachmentType": ..., "attachmentDataSend": None, } ``` -------------------------------- ### Facebook Login Source: https://github.com/minhhuydev/fbchat-v2/blob/main/src/_core/README.md Handles the process of logging into a Facebook account using username and password, with support for two-factor authentication. ```APIDOC ## Facebook Login ### Description Provides functionality to log in to a Facebook account using username and password credentials. Supports optional two-factor authentication. ### Method POST (typically) ### Endpoint (Specific endpoint details not provided in source, but implied to be a Facebook login endpoint) ### Parameters - **username** (str) - The user's Facebook username or email. - **password** (str) - The user's Facebook password. - **twoFactorCode** (str, optional) - The code for two-factor authentication, if enabled. ``` -------------------------------- ### Fetch Facebook Inbox and Thread Metadata Source: https://context7.com/minhhuydev/fbchat-v2/llms.txt Retrieves a list of inbox threads (up to 50) and extracts metadata for each thread. Includes `last_seq_id` for MQTT listeners. Requires session data. ```python from _core._session import dataGetHome from _features._thread import _all_thread_data dataFB = dataGetHome("c_user=...; xs=...") # Lấy dữ liệu inbox inbox = _all_thread_data.func(dataFB) print(f"Thời gian xử lý : {inbox['ProcessingTime']:.2f}s") print(f"last_seq_id : {inbox['last_seq_id']}") # Dùng cho MQTT threads = inbox["dataAllThread"] print(f"Số nhóm trong inbox: {threads['countThread']}") for name, tid in zip(threads["threadNameList"], threads["threadIDList"]): print(f" 📦 {name} — {tid}") # Trích xuất thông tin chi tiết một thread THREAD_ID = threads["threadIDList"][0] dataGet = inbox["dataGet"] # Lấy danh sách admin admins = _all_thread_data.features(dataGet, THREAD_ID, "getAdmin") print(admins) # {'adminThreadList': ['100012345678', '100087654321']} # Lấy thông tin đầy đủ thread info = _all_thread_data.features(dataGet, THREAD_ID, "threadInfomation") print(info) # {'nameThread': 'Nhóm Dev', 'IDThread': '480517...', # 'emojiThread': '🔥', 'messageCount': 1234, # 'adminThreadCount': 2, 'memberCount': 15, # 'approvalMode': 'Tắt', 'joinableMode': 'Bật', # 'urlJoinableThread': 'https://www.facebook.com/j/...'} # Xuất danh sách thành viên ra JSON members = _all_thread_data.features(dataGet, THREAD_ID, "exportMemberListToJson") for m in members: import json member = json.loads(m) for uid, data in member.items(): print(f" 👤 {data['nameFB']} ({uid}) — {data['gender']}") ```