monk / exchange_user_to_page_token.py
hf-actions
chore: add exchange_user_to_page_token helper
90c5f55
"""Exchange a Facebook short-lived user token for a long-lived user token and obtain a page access token.
Saves `FB_PAGE_ACCESS_TOKEN` into `.env` (replacing existing value) and appends a masked entry to `log.txt`.
Do NOT print full tokens to stdout.
"""
from dotenv import load_dotenv
import os
import requests
from pathlib import Path
ROOT = Path.cwd()
load_dotenv()
def mask(tok: str) -> str:
if not tok:
return ''
return tok[:4] + '...' + tok[-4:]
app_id = os.getenv('FB_APP_ID')
app_secret = os.getenv('FB_APP_SECRET')
user_token = os.getenv('FB_USER_TOKEN')
page_id = os.getenv('FB_PAGE_ID')
if not app_id or not app_secret or not user_token or not page_id:
print('Missing one of FB_APP_ID, FB_APP_SECRET, FB_USER_TOKEN, or FB_PAGE_ID in environment. Aborting.')
raise SystemExit(2)
try:
# Exchange short-lived user token for long-lived token
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}"
r = requests.get(exch_url, timeout=15)
r.raise_for_status()
data = r.json()
long_user_token = data.get('access_token')
except Exception as e:
print('Failed to exchange user token:', e)
raise
try:
# Obtain page access token using the long-lived user token
page_url = f"https://graph.facebook.com/{page_id}?fields=access_token&access_token={long_user_token}"
r2 = requests.get(page_url, timeout=15)
r2.raise_for_status()
page_data = r2.json()
page_token = page_data.get('access_token')
if not page_token:
# fallback: try listing accounts from user
accounts_url = f"https://graph.facebook.com/me/accounts?access_token={long_user_token}"
r3 = requests.get(accounts_url, timeout=15)
r3.raise_for_status()
accounts = r3.json().get('data', [])
for acct in accounts:
if str(acct.get('id')) == str(page_id):
page_token = acct.get('access_token')
break
except Exception as e:
print('Failed to obtain page token:', e)
raise
if not page_token:
print('Could not retrieve page access token from Graph API. Aborting.')
raise SystemExit(3)
# Save to .env (replace or append)
env_path = ROOT / '.env'
lines = []
if env_path.exists():
lines = env_path.read_text(encoding='utf-8').splitlines()
found = False
for i,l in enumerate(lines):
if l.startswith('FB_PAGE_ACCESS_TOKEN='):
lines[i] = f'FB_PAGE_ACCESS_TOKEN={page_token}'
found = True
break
if not found:
lines.append(f'FB_PAGE_ACCESS_TOKEN={page_token}')
env_path.write_text('\n'.join(lines) + '\n', encoding='utf-8')
# Append masked log
try:
with open('log.txt', 'a', encoding='utf-8') as lf:
lf.write(f"[{__import__('time').strftime('%Y-%m-%d %H:%M:%S')}] FB_PAGE_TOKEN_CREATED page={page_id} token={mask(page_token)}\n")
except Exception:
pass
print('Successfully obtained page access token and saved to .env (token masked).')