Skip to content

Commit 2406e0e

Browse files
committed
Implement challenge page detection and handling in Meta AI API
- Added `detect_challenge_page` function to identify challenge pages in HTML responses. - Introduced `handle_meta_ai_challenge` function to manage challenge verification requests. - Updated `extract_value` function to handle missing patterns gracefully. - Modified `get_fb_session` and `get_cookies` functions to improve error handling and ensure compatibility with new challenge handling. - Created comprehensive tests for challenge detection, token extraction, and manual token provision. - Added real-world integration test script to validate the entire flow with user-provided cookies. - Enhanced logging for better debugging and user feedback during challenge handling. - Updated example scripts to demonstrate new functionality and manual token provision process.
1 parent 5135c9a commit 2406e0e

File tree

10 files changed

+1364
-38
lines changed

10 files changed

+1364
-38
lines changed

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ test_video_fixed.py
7373
test_orientation_quick.py
7474
test_image_quick.py
7575
debug_async_video_test.py
76+
test_current_flow.py
77+
test_simple_approach.py
78+
test_render_fix.py
79+
test_success.py
7680

7781
# =========================
7882
# Node modules
@@ -95,6 +99,8 @@ FINAL_RESULTS.md
9599
VIDEO_BREAKTHROUGH.md
96100
IMPLEMENTATION_SUMMARY.md
97101
DEPLOYMENT_FIX.md
102+
GITHUB_ISSUE_RESPONSE.md
103+
QUICK_FIX_GUIDE.md
98104

99105
# Don't include cloudflare-worker files
100106
cloudflare-worker

README.md

Lines changed: 106 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -51,18 +51,18 @@ All in one SDK
5151

5252
### 🌟 Core Capabilities
5353

54-
| Feature | Description | Status |
55-
| ---------------------------- | ------------------------------------------------ | -------- |
56-
| 💬 **Intelligent Chat** | Powered by Llama 3 with internet access | ✅ Ready |
57-
| 📤 **Image Upload** | Upload & analyze images, generate similar images | ✅ Ready |
58-
| 🎨 **Image Generation** | Create stunning AI-generated images | ✅ Ready |
59-
| 🎬 **Video Generation** | Generate videos from text or uploaded images | ✅ Ready |
60-
| 🔍 **Image Analysis** | Describe, analyze, and extract info from images | ✅ Ready |
61-
| 🌐 **Real-time Data** | Get current information via Bing integration | ✅ Ready |
62-
| 📚 **Source Citations** | Responses include verifiable sources | ✅ Ready |
63-
| 🔄 **Streaming Support** | Real-time response streaming | ✅ Ready |
64-
| 🔐 **Auto Token Management** | Automatic authentication handling | ✅ Ready |
65-
| 🌍 **Proxy Support** | Route requests through proxies | ✅ Ready |
54+
| Feature | Description | Status |
55+
| ------------------------------ | ------------------------------------------------ | -------- |
56+
| 💬 **Intelligent Chat** | Powered by Llama 3 with internet access | ✅ Ready |
57+
| 📤 **Image Upload** | Upload & analyze images, generate similar images | ✅ Ready |
58+
| 🎨 **Image Generation** | Create stunning AI-generated images | ✅ Ready |
59+
| 🎬 **Video Generation** | Generate videos from text or uploaded images | ✅ Ready |
60+
| 🔍 **Image Analysis** | Describe, analyze, and extract info from images | ✅ Ready |
61+
| 🌐 **Real-time Data** | Get current information via Bing integration | ✅ Ready |
62+
| 📚 **Source Citations** | Responses include verifiable sources | ✅ Ready |
63+
| 🔄 **Streaming Support** | Real-time response streaming | ✅ Ready |
64+
| 🔐 **Flexible Authentication** | Auto-fetch or manual token provision | ✅ Ready |
65+
| 🌍 **Proxy Support** | Route requests through proxies | ✅ Ready |
6666

6767
---
6868

@@ -177,7 +177,57 @@ This calculation uses the compound interest formula: A = P(1 + r/n)^(nt)
177177

178178
---
179179

180-
## 💬 Chat Features
180+
## � Authentication Options
181+
182+
The SDK supports **flexible authentication** with two modes:
183+
184+
### Mode 1: Automatic Token Fetching (Recommended)
185+
186+
Provide basic cookies - `lsd` and `fb_dtsg` tokens are automatically fetched from Meta AI:
187+
188+
```python
189+
from metaai_api import MetaAI
190+
191+
# Provide basic cookies only
192+
cookies = {
193+
"datr": "your_datr_value",
194+
"abra_sess": "your_abra_sess_value",
195+
"dpr": "1.25",
196+
"wd": "1920x1080"
197+
}
198+
199+
ai = MetaAI(cookies=cookies)
200+
# SDK automatically fetches lsd and fb_dtsg tokens!
201+
```
202+
203+
### Mode 2: Manual Token Provision (Fallback)
204+
205+
Provide all tokens manually if automatic fetching fails:
206+
207+
```python
208+
from metaai_api import MetaAI
209+
210+
# Provide cookies + manual tokens
211+
cookies = {
212+
"datr": "your_datr_value",
213+
"abra_sess": "your_abra_sess_value",
214+
"dpr": "1.25",
215+
"wd": "1920x1080"
216+
}
217+
218+
ai = MetaAI(
219+
cookies=cookies,
220+
lsd="AVq1234567890", # Manual token
221+
fb_dtsg="ABCD:EFGH:123456789" # Manual token
222+
)
223+
# No auto-fetch needed!
224+
```
225+
226+
> **💡 Tip:** Start with **Mode 1** (automatic). Only use **Mode 2** if you encounter token fetching issues.
227+
228+
---
229+
230+
## �💬 Chat Features
181231

182232
### Streaming Responses
183233

@@ -349,6 +399,11 @@ Create AI-generated videos from text descriptions!
349399
4. Click any request → **Headers** → Copy **Cookie** value
350400
5. Extract these values: `datr`, `abra_sess`, `dpr`, `wd`
351401

402+
> **💡 Note:** The SDK supports **two authentication modes**:
403+
>
404+
> - **Automatic** (Recommended): Provide basic cookies, `lsd` and `fb_dtsg` tokens are auto-fetched
405+
> - **Manual**: Optionally provide `lsd` and `fb_dtsg` tokens directly if automatic fetching fails
406+
352407
### Example 1: Generate Your First Video
353408

354409
```python
@@ -402,6 +457,44 @@ else:
402457
🆔 Conversation ID: abc123-def456-ghi789
403458
```
404459

460+
### Example 1b: Manual Token Provision (Optional)
461+
462+
If automatic token fetching fails or you prefer to provide tokens directly:
463+
464+
```python
465+
from metaai_api import MetaAI
466+
467+
# Your browser cookies + manually extracted tokens
468+
cookies = {
469+
"datr": "your_datr_value_here",
470+
"abra_sess": "your_abra_sess_value_here",
471+
"dpr": "1.25",
472+
"wd": "1920x1080"
473+
}
474+
475+
# Initialize with manual tokens (no auto-fetch needed)
476+
ai = MetaAI(
477+
cookies=cookies,
478+
lsd="AVq1234567890", # Manually extracted lsd token
479+
fb_dtsg="ABCD:EFGH:123456789" # Manually extracted fb_dtsg token
480+
)
481+
482+
# Generate a video - tokens are already provided!
483+
result = ai.generate_video("A peaceful zen garden with koi fish")
484+
485+
if result["success"]:
486+
print("✅ Video generated successfully with manual tokens!")
487+
print(f"🎬 Video URL: {result['video_urls'][0]}")
488+
```
489+
490+
**How to extract `lsd` and `fb_dtsg` tokens:**
491+
492+
1. Open https://meta.ai in your browser (logged in)
493+
2. Press **F12****Console** tab
494+
3. Run: `document.cookie`
495+
4. Look for `lsd=...` and `fb_dtsg=...` values
496+
5. Alternatively, right-click → **View Page Source** → Search for `"LSD",[],{"token":"` and `DTSGInitData",[],{"token":"`
497+
405498
### Example 2: Generate Multiple Videos
406499

407500
```python

examples/manual_token_example.py

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
"""
2+
Example: Using Meta AI API with Manual Token Provision
3+
4+
This example demonstrates how to use the Meta AI API when encountering
5+
challenge page issues. You can manually extract and provide tokens to
6+
bypass the automatic token fetching.
7+
"""
8+
9+
from typing import Dict
10+
from metaai_api import MetaAI
11+
12+
# ============================================================================
13+
# Option 1: Let the library handle challenge pages automatically
14+
# ============================================================================
15+
print("Option 1: Automatic challenge handling\n" + "="*50)
16+
17+
# Provide your cookies (extracted from browser)
18+
cookies = {
19+
"datr": "your_datr_cookie",
20+
"abra_sess": "your_abra_sess_cookie",
21+
"dpr": "1.25",
22+
"wd": "1536x730",
23+
"abra_csrf": "your_abra_csrf_cookie"
24+
}
25+
26+
# The library will automatically handle challenge pages and fetch tokens
27+
ai = MetaAI(cookies=cookies)
28+
29+
# If successful, you can now use the API
30+
# Note: stream=False returns a Dict, stream=True returns a Generator
31+
response: Dict = ai.prompt("Hello, Meta AI!", stream=False) # type: ignore
32+
print(f"Response: {response['message']}\n")
33+
34+
35+
# ============================================================================
36+
# Option 2: Manually provide lsd and fb_dtsg tokens
37+
# ============================================================================
38+
print("\nOption 2: Manual token provision\n" + "="*50)
39+
40+
# If automatic fetching fails, you can manually extract tokens from browser
41+
# and provide them directly:
42+
43+
# 1. Open https://www.meta.ai in your browser
44+
# 2. Open Developer Tools (F12)
45+
# 3. Go to Console tab
46+
# 4. Type: document.cookie
47+
# 5. Extract lsd token from the page source:
48+
# - View page source (Ctrl+U)
49+
# - Search for: "LSD",[],{"token":"
50+
# - Copy the token value
51+
# 6. Extract fb_dtsg token:
52+
# - Search for: DTSGInitData",[],{"token":"
53+
# - Copy the token value
54+
55+
cookies_with_manual_tokens = {
56+
"datr": "your_datr_cookie",
57+
"abra_sess": "your_abra_sess_cookie",
58+
"dpr": "1.25",
59+
"wd": "1536x730",
60+
"abra_csrf": "your_abra_csrf_cookie"
61+
}
62+
63+
# Provide tokens explicitly
64+
ai_manual = MetaAI(
65+
cookies=cookies_with_manual_tokens,
66+
lsd="your_manually_extracted_lsd_token",
67+
fb_dtsg="your_manually_extracted_fb_dtsg_token"
68+
)
69+
70+
response: Dict = ai_manual.prompt("What can you help me with?", stream=False) # type: ignore
71+
print(f"Response: {response['message']}\n")
72+
73+
74+
# ============================================================================
75+
# Option 3: Using with Facebook login (auto-handles challenges)
76+
# ============================================================================
77+
print("\nOption 3: Facebook login with auto-challenge handling\n" + "="*50)
78+
79+
# If you have Facebook credentials, the library will authenticate
80+
# and automatically handle any challenge pages
81+
ai_fb = MetaAI(
82+
fb_email="your_email@example.com",
83+
fb_password="your_password"
84+
)
85+
86+
response: Dict = ai_fb.prompt("Tell me a fun fact", stream=False) # type: ignore
87+
print(f"Response: {response['message']}\n")
88+
89+
90+
# ============================================================================
91+
# Extracting tokens from browser (detailed guide)
92+
# ============================================================================
93+
print("\n" + "="*50)
94+
print("HOW TO EXTRACT TOKENS FROM BROWSER")
95+
print("="*50)
96+
print("""
97+
1. Open https://www.meta.ai in your browser and log in
98+
99+
2. Extract cookies:
100+
- Press F12 to open Developer Tools
101+
- Go to Application/Storage tab
102+
- Click on Cookies > https://www.meta.ai
103+
- Copy these cookie values:
104+
* datr
105+
* abra_sess
106+
* dpr
107+
* wd
108+
* abra_csrf
109+
110+
3. Extract lsd token:
111+
- Right-click on page and select "View Page Source" (Ctrl+U)
112+
- Press Ctrl+F and search for: "LSD",[],{"token":"
113+
- Copy the value between the quotes
114+
- Example: "LSD",[],{"token":"AVq1234567890"}
115+
Copy: AVq1234567890
116+
117+
4. Extract fb_dtsg token:
118+
- In the same page source, search for: DTSGInitData",[],{"token":"
119+
- Copy the value between the quotes
120+
- Example: DTSGInitData",[],{"token":"ABCD:EFGH:1234567890"}
121+
Copy: ABCD:EFGH:1234567890
122+
123+
5. Use the extracted values in your code:
124+
125+
cookies = {
126+
"datr": "<your_datr>",
127+
"abra_sess": "<your_abra_sess>",
128+
"dpr": "1.25",
129+
"wd": "1536x730",
130+
"abra_csrf": "<your_abra_csrf>"
131+
}
132+
133+
ai = MetaAI(
134+
cookies=cookies,
135+
lsd="<your_lsd_token>",
136+
fb_dtsg="<your_fb_dtsg_token>"
137+
)
138+
139+
Note: Tokens may expire after some time. If you get errors, extract fresh tokens.
140+
""")
141+
142+
143+
# ============================================================================
144+
# Troubleshooting
145+
# ============================================================================
146+
print("\n" + "="*50)
147+
print("TROUBLESHOOTING")
148+
print("="*50)
149+
print("""
150+
If you encounter errors:
151+
152+
1. Enable logging to see detailed information:
153+
154+
import logging
155+
logging.basicConfig(level=logging.INFO)
156+
157+
2. Check if challenge handling is working:
158+
- Look for log messages about "Meta AI challenge page"
159+
- The library will automatically retry with challenge handling
160+
161+
3. Try manual token provision if automatic fetching fails
162+
163+
4. Ensure your cookies are fresh (extracted within the last few hours)
164+
165+
5. If using a proxy, make sure it's working correctly
166+
167+
6. Try accessing https://www.meta.ai directly in your browser
168+
to ensure you're not blocked or rate-limited
169+
""")

examples/simple_example.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from metaai_api import MetaAI
22

3-
# Your cookies from browser (lsd and fb_dtsg are auto-fetched!)
3+
# Your cookies from browser - lsd and fb_dtsg are automatically fetched!
4+
# Note: If you encounter challenges, you can also provide tokens manually:
5+
# ai = MetaAI(cookies=cookies, lsd="your_lsd_token", fb_dtsg="your_fb_dtsg_token")
46
cookies = {
57
"datr": "datrcookie",
68
"abra_sess": "abrasessioncookie",
@@ -22,7 +24,7 @@
2224
# Use for chat
2325
print("\nAsking: What's the weather in San Francisco?")
2426
try:
25-
chat = ai.prompt("What's the weather in San Francisco?", stream=False)
27+
chat: dict = ai.prompt("What's the weather in San Francisco?", stream=False) # type: ignore
2628
print(f"\n✅ Chat Response:\n{chat['message'][:200]}...\n")
2729
except Exception as e:
2830
print(f"❌ Chat Error: {e}\n")

0 commit comments

Comments
 (0)