hf-actions commited on
Commit
90c5f55
·
1 Parent(s): 475fc0c

chore: add exchange_user_to_page_token helper

Browse files
Files changed (1) hide show
  1. exchange_user_to_page_token.py +86 -0
exchange_user_to_page_token.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exchange a Facebook short-lived user token for a long-lived user token and obtain a page access token.
2
+ Saves `FB_PAGE_ACCESS_TOKEN` into `.env` (replacing existing value) and appends a masked entry to `log.txt`.
3
+
4
+ Do NOT print full tokens to stdout.
5
+ """
6
+ from dotenv import load_dotenv
7
+ import os
8
+ import requests
9
+ from pathlib import Path
10
+
11
+ ROOT = Path.cwd()
12
+ load_dotenv()
13
+
14
+ def mask(tok: str) -> str:
15
+ if not tok:
16
+ return ''
17
+ return tok[:4] + '...' + tok[-4:]
18
+
19
+ app_id = os.getenv('FB_APP_ID')
20
+ app_secret = os.getenv('FB_APP_SECRET')
21
+ user_token = os.getenv('FB_USER_TOKEN')
22
+ page_id = os.getenv('FB_PAGE_ID')
23
+
24
+ if not app_id or not app_secret or not user_token or not page_id:
25
+ print('Missing one of FB_APP_ID, FB_APP_SECRET, FB_USER_TOKEN, or FB_PAGE_ID in environment. Aborting.')
26
+ raise SystemExit(2)
27
+
28
+ try:
29
+ # Exchange short-lived user token for long-lived token
30
+ exch_url = f"https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={app_id}&client_secret={app_secret}&fb_exchange_token={user_token}"
31
+ r = requests.get(exch_url, timeout=15)
32
+ r.raise_for_status()
33
+ data = r.json()
34
+ long_user_token = data.get('access_token')
35
+ except Exception as e:
36
+ print('Failed to exchange user token:', e)
37
+ raise
38
+
39
+ try:
40
+ # Obtain page access token using the long-lived user token
41
+ page_url = f"https://graph.facebook.com/{page_id}?fields=access_token&access_token={long_user_token}"
42
+ r2 = requests.get(page_url, timeout=15)
43
+ r2.raise_for_status()
44
+ page_data = r2.json()
45
+ page_token = page_data.get('access_token')
46
+ if not page_token:
47
+ # fallback: try listing accounts from user
48
+ accounts_url = f"https://graph.facebook.com/me/accounts?access_token={long_user_token}"
49
+ r3 = requests.get(accounts_url, timeout=15)
50
+ r3.raise_for_status()
51
+ accounts = r3.json().get('data', [])
52
+ for acct in accounts:
53
+ if str(acct.get('id')) == str(page_id):
54
+ page_token = acct.get('access_token')
55
+ break
56
+ except Exception as e:
57
+ print('Failed to obtain page token:', e)
58
+ raise
59
+
60
+ if not page_token:
61
+ print('Could not retrieve page access token from Graph API. Aborting.')
62
+ raise SystemExit(3)
63
+
64
+ # Save to .env (replace or append)
65
+ env_path = ROOT / '.env'
66
+ lines = []
67
+ if env_path.exists():
68
+ lines = env_path.read_text(encoding='utf-8').splitlines()
69
+ found = False
70
+ for i,l in enumerate(lines):
71
+ if l.startswith('FB_PAGE_ACCESS_TOKEN='):
72
+ lines[i] = f'FB_PAGE_ACCESS_TOKEN={page_token}'
73
+ found = True
74
+ break
75
+ if not found:
76
+ lines.append(f'FB_PAGE_ACCESS_TOKEN={page_token}')
77
+ env_path.write_text('\n'.join(lines) + '\n', encoding='utf-8')
78
+
79
+ # Append masked log
80
+ try:
81
+ with open('log.txt', 'a', encoding='utf-8') as lf:
82
+ lf.write(f"[{__import__('time').strftime('%Y-%m-%d %H:%M:%S')}] FB_PAGE_TOKEN_CREATED page={page_id} token={mask(page_token)}\n")
83
+ except Exception:
84
+ pass
85
+
86
+ print('Successfully obtained page access token and saved to .env (token masked).')