from xdk.auth import OAuth2PKCE
from urllib.parse import urlparse
import webbrowser
# Step 1: Create PKCE instance
auth = OAuth2PKCE(
    client_id="your_client_id",
    redirect_uri="http://localhost:8080/callback",
    scopes=["tweet.read", "users.read", "offline.access"]  # Adjust scopes as needed
)
# Step 2: Get authorization URL
auth_url = auth.get_authorization_url()
print(f"Visit this URL to authorize: {auth_url}")
webbrowser.open(auth_url)
# Step 3: Handle callback (in a real app, use a web framework like Flask)
# Assume callback_url = "http://localhost:8080/callback?code=AUTH_CODE_HERE"
callback_url = input("Paste the full callback URL here: ")
parsed = urlparse(callback_url)
code = parsed.query.split("=")[1]
# Step 4: Exchange code for tokens
tokens = auth.fetch_token(authorization_code=code)
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]  # Store for renewal
# Step 5: Create client
client = Client(oauth2_access_token=access_token)