igdb: auto-refresh twitch token; category -> game_type filter
Static app tokens expire after ~60 days -> every lookup failed with 401. With igdb-client-secret set, the bot fetches the token via client-credentials OAuth itself, refreshes a day before expiry and retries once on 401; a static igdb-access-token still works. IGDB renamed games.category to game_type: the category = 0 filter in search_games silently matched nothing even with a valid token. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
+38
-5
@@ -1,27 +1,60 @@
|
||||
import logging
|
||||
import time
|
||||
from functools import cache
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import requests
|
||||
|
||||
TWITCH_OAUTH_URL = "https://id.twitch.tv/oauth2/token"
|
||||
# Refresh this long before Twitch expires the token (app tokens live ~60 days)
|
||||
TOKEN_REFRESH_MARGIN = 86400
|
||||
|
||||
|
||||
class IGDBQuery(object):
|
||||
def __init__(self, client_id, igdb_api_key):
|
||||
def __init__(self, client_id, igdb_api_key=None, client_secret=None):
|
||||
self.client_id = client_id
|
||||
self.igdb_api_key = igdb_api_key
|
||||
self.client_secret = client_secret
|
||||
# Unknown for statically configured tokens; set after each refresh
|
||||
self._token_expires_at = None
|
||||
|
||||
def _refresh_token(self):
|
||||
response = requests.post(
|
||||
TWITCH_OAUTH_URL,
|
||||
params={"client_id": self.client_id, "client_secret": self.client_secret, "grant_type": "client_credentials"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
self.igdb_api_key = data["access_token"]
|
||||
self._token_expires_at = time.time() + data.get("expires_in", 0) - TOKEN_REFRESH_MARGIN
|
||||
logging.info("IGDB: refreshed Twitch app access token")
|
||||
|
||||
def _ensure_token(self):
|
||||
if not self.client_secret:
|
||||
return
|
||||
if not self.igdb_api_key or (self._token_expires_at is not None and time.time() >= self._token_expires_at):
|
||||
self._refresh_token()
|
||||
|
||||
def send_igdb_request(self, endpoint, query_body):
|
||||
igdb_url = f"https://api.igdb.com/v4/{endpoint}"
|
||||
headers = {"Client-ID": self.client_id, "Authorization": f"Bearer {self.igdb_api_key}"}
|
||||
|
||||
try:
|
||||
response = requests.post(igdb_url, headers=headers, data=query_body)
|
||||
self._ensure_token()
|
||||
response = self._post_igdb(igdb_url, query_body)
|
||||
if self.client_secret and response.status_code == 401:
|
||||
# Token expired server-side (e.g. statically configured) — refresh and retry once
|
||||
self._refresh_token()
|
||||
response = self._post_igdb(igdb_url, query_body)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
print(f"Error during IGDB API request: {e}")
|
||||
return None
|
||||
|
||||
def _post_igdb(self, igdb_url, query_body):
|
||||
headers = {"Client-ID": self.client_id, "Authorization": f"Bearer {self.igdb_api_key}"}
|
||||
return requests.post(igdb_url, headers=headers, data=query_body)
|
||||
|
||||
@staticmethod
|
||||
def build_query(fields, filters=None, limit=10, offset=None):
|
||||
query = f"fields {','.join(fields) if fields is not None and len(fields) > 0 else '*'}; limit {limit};"
|
||||
@@ -79,7 +112,7 @@ class IGDBQuery(object):
|
||||
"id",
|
||||
"name",
|
||||
"alternative_names",
|
||||
"category",
|
||||
"game_type",
|
||||
"release_dates",
|
||||
"franchise",
|
||||
"language_supports",
|
||||
@@ -120,7 +153,7 @@ class IGDBQuery(object):
|
||||
"themes.name",
|
||||
"cover.url",
|
||||
],
|
||||
additional_filters={"category": "= 0"}, # Main games only
|
||||
additional_filters={"game_type": "= 0"}, # Main games only (IGDB renamed category -> game_type)
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@@ -137,16 +137,20 @@ class OpenAIResponder(AIResponder, LeonardoAIDrawMixIn):
|
||||
|
||||
# Initialize IGDB if enabled
|
||||
self.igdb = None
|
||||
igdb_client_id = self.config.get("igdb-client-id")
|
||||
igdb_client_secret = self.config.get("igdb-client-secret")
|
||||
igdb_access_token = self.config.get("igdb-access-token")
|
||||
logging.info("IGDB Configuration Check:")
|
||||
logging.info(f" enable-game-info: {self.config.get('enable-game-info', 'NOT SET')}")
|
||||
logging.info(f" igdb-client-id: {'SET' if self.config.get('igdb-client-id') else 'NOT SET'}")
|
||||
logging.info(f" igdb-access-token: {'SET' if self.config.get('igdb-access-token') else 'NOT SET'}")
|
||||
logging.info(f" igdb-client-id: {'SET' if igdb_client_id else 'NOT SET'}")
|
||||
logging.info(f" igdb-client-secret: {'SET' if igdb_client_secret else 'NOT SET'}")
|
||||
logging.info(f" igdb-access-token: {'SET' if igdb_access_token else 'NOT SET'}")
|
||||
|
||||
if self.config.get("enable-game-info", False) and self.config.get("igdb-client-id") and self.config.get("igdb-access-token"):
|
||||
if self.config.get("enable-game-info", False) and igdb_client_id and (igdb_client_secret or igdb_access_token):
|
||||
try:
|
||||
self.igdb = IGDBQuery(self.config["igdb-client-id"], self.config["igdb-access-token"])
|
||||
self.igdb = IGDBQuery(igdb_client_id, igdb_access_token, client_secret=igdb_client_secret)
|
||||
logging.info("✅ IGDB integration SUCCESSFULLY enabled for game information")
|
||||
logging.info(f" Client ID: {self.config['igdb-client-id'][:8]}...")
|
||||
logging.info(f" Client ID: {igdb_client_id[:8]}...")
|
||||
logging.info(f" Available functions: {len(self.igdb.get_openai_functions())}")
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Failed to initialize IGDB: {e}")
|
||||
|
||||
Reference in New Issue
Block a user