Skip to content

Instantly share code, notes, and snippets.

@lFitzl
Created August 22, 2024 04:00
Show Gist options
  • Save lFitzl/92da5692eb054309dab47e81076775dd to your computer and use it in GitHub Desktop.
Save lFitzl/92da5692eb054309dab47e81076775dd to your computer and use it in GitHub Desktop.
patreon_auth_client_local
import time
import json
import re
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from dotenv import dotenv_values
import patreon
config = dotenv_values(".env")
USER_AGENT = "PixivIOSApp/7.13.3 (iOS 14.6; iPhone13,2)"
REDIRECT_URI = config["PATREON_REDIRECT_URI"]
LOGIN_URL = "https://www.patreon.com/oauth2/authorize"
CLIENT_ID = config["PATREON_CLIENT_ID"]
CLIENT_SECRET = config["PATREON_CLIENT_SECRET"]
PATREON_ACCESS_TOKEN = config.get("PATREON_ACCESS_TOKEN", None)
REQUESTS_KWARGS = {}
def get_auth_url():
url = f"{LOGIN_URL}?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}"
print(f"[INFO] Open this URL in your browser: {url}")
return url
def login():
options = ChromeOptions()
log_prefs = {"performance": "ALL"}
options.set_capability("goog:loggingPrefs", log_prefs)
driver = webdriver.Chrome(options=options)
driver.get(get_auth_url())
while True:
if driver.current_url.startswith(REDIRECT_URI):
break
time.sleep(1)
code = None
for row in driver.get_log("performance"):
data = json.loads(row.get("message", {}))
message = data.get("message", {})
if message.get("method") == "Network.requestWillBeSent":
url = message.get("params", {}).get("documentURL")
if url and url.startswith(REDIRECT_URI):
code = re.search(r"code=([^&]*)", url).groups()[0]
break
driver.close()
print("[INFO] Get code:", code)
get_access_token(code)
def get_access_token(code):
url = "https://www.patreon.com/api/oauth2/token"
data = {
"grant_type": "authorization_code",
"code": code,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_uri": REDIRECT_URI,
}
response = requests.post(url, data=data)
# Add debug messages
print("URL:", url)
print("Data sent:", data)
print("API response:", response.json())
response_data = response.json()
if "access_token" in response_data:
print("Access token:", response_data["access_token"])
else:
raise Exception(
"Error obtaining access token: "
+ response_data.get("error_description", "Unknown error")
)
def fetch_campaign():
users = patreon.API(access_token=PATREON_ACCESS_TOKEN).fetch_page_of_pledges().json_data
# save json file
with open("patreon.json", "w") as f:
json.dump(users, f, indent=4)
if __name__ == "__main__":
login()
fetch_campaign()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment