Genesys Cloud Python SDK auto-refresh token not working for long-running script

Hey folks,

I’m trying to write a simple Python script to pull WEM adherence stats every 5 minutes for our Central time zone team. I’ve got 7 years of scheduling experience, but I’m pretty new to the Genesys Cloud Platform SDK.

I thought the SDK would handle the OAuth token refresh automatically if I just passed in the client ID and secret. It works fine for the first hour or so, but then I start getting 401 Unauthorized errors. I assumed the SDK’s Client object would refresh the token in the background since I’m using the client_credentials flow.

Here is what I’ve got so far:

from genesyscloud.rest import Configuration
from genesyscloud.client import Client
from genesyscloud.analytics_api import AnalyticsApi
import time

config = Configuration(
 host="https://api.mypurecloud.com",
 client_id="my-client-id",
 client_secret="my-client-secret"
)

client = Client(configuration=config)
analytics = AnalyticsApi(client)

while True:
 try:
 # Pull some adherence data
 data = analytics.get_analytics_interactions_details(
 query="query=type:adhherence+filter:startTime+gte+2023-01-01T00:00:00Z"
 )
 print("Got data")
 except Exception as e:
 print(f"Error: {e}")
 
 time.sleep(300) # 5 minutes

The error I’m seeing after about an hour is:

genesyscloud.exceptions.ApiException: (401)
Reason: Unauthorized
HTTP response headers: HTTPHeaderDict({'Content-Type': 'application/json', 'X-Request-Id': 'abc-123'})
HTTP response body: {"code":"unauthorized","message":"Access token is expired"}

I read somewhere that the SDK handles token refresh for you, but maybe I’m missing a step? Do I need to manually call a refresh method or is there a specific way to initialize the client for long-running jobs? I don’t want to have to manage the token lifecycle manually if I don’t have to.

Any ideas on how to make the SDK handle this automatically?