68 lines
2.5 KiB
Python
68 lines
2.5 KiB
Python
# get_refresh_token.py
|
|
# A temporary, one-time-use script to get your OAuth2 refresh token.
|
|
|
|
import praw
|
|
from dotenv import load_dotenv
|
|
import os
|
|
import random
|
|
import socket
|
|
|
|
# --- IMPORTANT: Ensure this matches the "redirect uri" in your Reddit App settings ---
|
|
REDIRECT_URI = "http://localhost:5000"
|
|
|
|
def main():
|
|
print("--- RSTAT Refresh Token Generator ---")
|
|
load_dotenv()
|
|
client_id = os.getenv("REDDIT_CLIENT_ID")
|
|
client_secret = os.getenv("REDDIT_CLIENT_SECRET")
|
|
|
|
if not all([client_id, client_secret]):
|
|
print("Error: REDDIT_CLIENT_ID and REDDIT_CLIENT_SECRET must be set in your .env file.")
|
|
return
|
|
|
|
# 1. Initialize PRAW
|
|
reddit = praw.Reddit(
|
|
client_id=client_id,
|
|
client_secret=client_secret,
|
|
redirect_uri=REDIRECT_URI,
|
|
user_agent="rstat_token_fetcher (by u/YourUsername)" # Can be anything
|
|
)
|
|
|
|
# 2. Generate the authorization URL
|
|
# Scopes define what our script is allowed to do. 'identity' and 'submit' are needed.
|
|
scopes = ["identity", "submit", "read"]
|
|
state = str(random.randint(0, 65536))
|
|
auth_url = reddit.auth.url(scopes, state, "permanent")
|
|
|
|
print("\nStep 1: Open this URL in your browser:\n")
|
|
print(auth_url)
|
|
|
|
print("\nStep 2: Log in to Reddit, click 'Allow', and you'll be redirected to a 'page not found'.")
|
|
print("Step 3: Copy the ENTIRE URL from your browser's address bar after the redirect.")
|
|
|
|
# 3. Get the redirected URL from the user
|
|
redirected_url = input("\nStep 4: Paste the full redirected URL here and press Enter:\n> ")
|
|
|
|
# 4. Exchange the authorization code for a refresh token
|
|
try:
|
|
# The state is used to prevent CSRF attacks, we're just checking it matches
|
|
assert state == redirected_url.split("state=")[1].split("&")[0]
|
|
code = redirected_url.split("code=")[1].split("#_")[0]
|
|
|
|
print("\nAuthorization code received. Fetching refresh token...")
|
|
|
|
# This is the line that gets the key!
|
|
refresh_token = reddit.auth.authorize(code)
|
|
|
|
print("\n--- SUCCESS! ---")
|
|
print("Your Refresh Token is:\n")
|
|
print(refresh_token)
|
|
print("\nStep 5: Copy this token and add it to your .env file as REDDIT_REFRESH_TOKEN.")
|
|
print("Step 6: You can now delete your REDDIT_USERNAME and REDDIT_PASSWORD from the .env file.")
|
|
|
|
except Exception as e:
|
|
print(f"\nAn error occurred: {e}")
|
|
print("Please make sure you copied the full URL.")
|
|
|
|
if __name__ == "__main__":
|
|
main() |