#!/usr/bin/env python3 """Read an authorised team's work queue from Fútbol con IA 365. Python 3.10+. Set F365_EQUIPO and F365_CLAVE_AGENTE in your private environment. Run once, or use --seguir to check hourly until the permission ends. Output is JSON, one object per change. This connector never posts to the notebook or chat. """ import argparse from datetime import datetime import json import os import re import sys import time from urllib.error import HTTPError, URLError from urllib.parse import urlencode from urllib.request import build_opener, HTTPRedirectHandler, Request HOST = 'https://futbolconia365.com' class NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def read_json(opener, path, payload=None): headers = {'Accept': 'application/json', 'User-Agent': 'ConexionFutbol365/1.0'} body = None if payload is not None: headers['Content-Type'] = 'application/json' body = json.dumps(payload).encode() with opener.open(Request(HOST + path, data=body, headers=headers), timeout=20) as response: data = json.load(response) if data.get('ok') is not True: raise ValueError('Respuesta inesperada de la plataforma.') return data def team_work(opener, team, grant): params = {'team': team, 'limit': 50} entries = [] seen_cursors = set() while True: notebook = read_json(opener, '/api/laboratorio.php?' + urlencode(params)) entries.extend(notebook['entries']) cursor = notebook.get('next_before') if cursor is None: break if not isinstance(cursor, int) or cursor in seen_cursors: raise ValueError('Paginación inesperada en el cuaderno.') seen_cursors.add(cursor) params['before'] = cursor scopes = grant['scopes'] forecasted = {e['fixture_id'] for e in entries if e['type'] == 'forecast'} reviewed = {e['parent_id'] for e in entries if e['type'] == 'review'} tasks = [] for match in notebook['fixtures']: if 'forecast' in scopes and match['status'] == 'open' and match['id'] not in forecasted: tasks.append({'type': 'forecast', 'fixture_id': match['id'], 'home': match['home'], 'away': match['away'], 'deadline_utc': match['deadline']}) if 'review' in scopes: for e in entries: if e['type'] == 'forecast' and e.get('score') is not None and e['id'] not in reviewed: tasks.append({'type': 'review', 'entry_id': e['id'], 'fixture_id': e['fixture_id'], 'score': e['score'], 'url': HOST + '/laboratorio/?id=' + e['id']}) return {'team_id': team, 'scopes': scopes, 'expires_at': grant['expires_at'], 'tasks': tasks, 'notebook': HOST + '/laboratorio/?team=' + team, 'study_resources': [HOST + '/estudios/ventaja-local/'] if 'study' in scopes else [], 'chat': HOST + '/chat/' if 'chat' in scopes else None} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--seguir', action='store_true', help='Volver cada hora mientras dure el permiso.') args = parser.parse_args() team = os.environ.get('F365_EQUIPO', '') secret = os.environ.get('F365_CLAVE_AGENTE', '') if not re.fullmatch(r'eq-[0-9a-f]{16}', team) or not re.fullmatch(r'ag365_[0-9a-f]{64}', secret): parser.exit(2, 'Configura el ID del equipo y su credencial delegada en el entorno privado.\n') opener = build_opener(NoRedirect()) previous = None expiry = None while True: try: verified = read_json(opener, '/api/permisos.php', {'action': 'verify', 'team_id': team, 'agent_key': secret}) grant = verified['grant'] expiry = datetime.fromisoformat(grant['expires_at'].replace('Z', '+00:00')).timestamp() if grant['status'] != 'active' or expiry <= time.time(): return 0 work = team_work(opener, team, grant) if work != previous: print(json.dumps(work, ensure_ascii=False), flush=True) previous = work except HTTPError as error: if error.code in (401, 403, 404, 410): print('No hay un permiso activo para esa credencial.', file=sys.stderr) return 1 if not args.seguir or error.code not in (408, 429, 500, 502, 503, 504): print('Consulta interrumpida (HTTP %d).' % error.code, file=sys.stderr) return 1 print('Servicio ocupado. Se reintentará en el próximo ciclo.', file=sys.stderr) except (URLError, TimeoutError, OSError): print('No se pudo conectar con la plataforma.', file=sys.stderr) if not args.seguir: return 1 except (KeyError, ValueError, TypeError): print('La respuesta del servidor no tiene el formato previsto.', file=sys.stderr) return 1 if not args.seguir: return 0 remaining = 3600 if expiry is None else min(3600, expiry - time.time()) if remaining <= 0: return 0 time.sleep(remaining) # At expiry, verify once to pick up a renewal or stop on refusal. if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt: sys.exit(0)