Bot & Automation

jorgasisten

/root/hermes-projects/jorgasisten

scripts/generate_google_oauth_authorized_user.py text
import argparse
import base64
import json
from pathlib import Path

from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Generate authorized-user Google OAuth credential JSON for Jorgasisten."
    )
    parser.add_argument(
        "--client-secret",
        required=True,
        help="Path to OAuth client secret JSON, for example D:\\hermes agent\\envtreding.md",
    )
    parser.add_argument(
        "--output-json",
        default="data/google_authorized_user.json",
        help="Path to write the authorized-user JSON output.",
    )
    parser.add_argument(
        "--no-open-browser",
        action="store_true",
        help="Do not try to open the browser automatically.",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    client_secret_path = Path(args.client_secret)
    client_config = json.loads(client_secret_path.read_text(encoding="utf-8"))
    flow = InstalledAppFlow.from_client_config(client_config, SCOPES)
    credentials = flow.run_local_server(
        host="127.0.0.1",
        port=0,
        open_browser=not args.no_open_browser,
        authorization_prompt_message="Buka link ini di browser untuk login Google:\n{url}",
        success_message="Login Google berhasil. Kamu bisa kembali ke terminal.",
    )

    output_path = Path(args.output_json)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    authorized_user_json = credentials.to_json()
    output_path.write_text(authorized_user_json + "\n", encoding="utf-8")

    encoded = base64.b64encode(authorized_user_json.encode("utf-8")).decode("utf-8")
    print(f"saved_json={output_path}")
    print("env_line=GOOGLE_OAUTH_AUTHORIZED_USER_JSON_BASE64=" + encoded)


if __name__ == "__main__":
    main()