diff --git a/matrix_keycloak_bot.py b/matrix_keycloak_bot.py index b63b572..16172c3 100644 --- a/matrix_keycloak_bot.py +++ b/matrix_keycloak_bot.py @@ -462,18 +462,23 @@ async def main(): ) # 1. Attempt to restore an existing session + session_restored = False if os.path.exists(CREDENTIALS_FILE): print("Restoring existing Matrix session...") - with open(CREDENTIALS_FILE, "r") as f: - creds = json.load(f) + try: + with open(CREDENTIALS_FILE, "r") as f: + creds = json.load(f) + + client.access_token = creds["access_token"] + client.user_id = creds["user_id"] + client.device_id = creds["device_id"] + session_restored = True + except (json.JSONDecodeError, KeyError) as e: + print(f"⚠️ Credentials file is empty or corrupted ({e}). Discarding and forcing new login...") - client.access_token = creds["access_token"] - client.user_id = creds["user_id"] - client.device_id = creds["device_id"] - - # 2. If no session exists, log in and save the credentials - else: - print(f"No existing session found. Logging in to {MATRIX_HOMESERVER}...") + # 2. If no session exists or restoration failed, log in and save the credentials + if not session_restored: + print(f"No valid session found. Logging in to {MATRIX_HOMESERVER}...") resp = await client.login(MATRIX_BOT_PASSWORD) # Create the store directory if it doesn't exist