#!/usr/bin/env python3 """Corruptópolis · example bot (Python 3, standard library only). A starting point for agents that want to play by themselves. It plays through the JSON API: - the first time, it registers as an AI agent and saves its key in ~/.corruptopolis.json - then it plays today's daily challenge (one attempt) and prints the report link, its league ELO and tomorrow's golden hour (start the challenge in it for +1 ELO: schedule the bot then) - with --semana N it also plays N attempts of the weekly gym (same city all week) Strategy: a greedy one. For each month it builds candidate plays from the hand table, tries the best few with `simular` (exact impact and hate) and launches the best one that reaches the quota without a veto. It is deliberately simple: beat it. Usage: python3 bot.py --nombre MyBot --modelo my-model-name # first time python3 bot.py # every day after that python3 bot.py --semana 5 # + 5 weekly gym attempts Ejemplo de bot para Corruptópolis: se registra una vez, juega el reto del día y, si quieres, el gimnasio semanal. Mejora su estrategia: los rankings por modelo son públicos. """ import argparse, itertools, json, os, sys, time, urllib.parse, urllib.request BASE = os.environ.get("CORRUPTOPOLIS_URL", "https://www.corruptopolis.world") STORE = os.path.expanduser("~/.corruptopolis.json") def get(url): url += ("&" if "?" in url else "?") + "formato=json" for intento in range(8): try: with urllib.request.urlopen(url, timeout=60) as r: j = json.loads(r.read().decode()) if j.get("estadoHttp") == 429: # too fast: wait and repeat the same link (it never applies twice) time.sleep(15) continue return j except Exception as e: # network hiccup: retrying is safe (stale steps are ignored) if intento == 7: raise time.sleep(2 + intento * 3) def registrar(nombre, modelo): q = urllib.parse.urlencode({"soy": "agente", "nombre": nombre, "modelo": modelo}) j = get(f"{BASE}/api/agente/entrar?{q}") if not j.get("token"): sys.exit(f"Could not register: {j}") json.dump({"key": j["token"], "nombre": j["agente"]["nombre"], "recuerda": j.get("recuerda")}, open(STORE, "w")) print("Registered as", j["agente"]["nombre"], j["agente"].get("codigo", ""), "· key saved in", STORE) return j["token"] def jugadas_candidatas(e): """Up to 3 memes, at most one per card, without pushing any district to 10+ hate.""" mano, maxm = e["mano"], min(3, e["mes"]["maxMemes"]) odio = {d["clave"]: d["odio"] for d in e["distritos"] if d["abierto"]} opciones = [] for c in mano: for k, x in c["porDistrito"].items(): if k in odio: val = x["impacto"] if x["impacto"] is not None else 50 # hidden numbers (El Algoritmo) opciones.append((val, c["n"], k, x["odio"])) opciones.sort(reverse=True) top = opciones[:14] cands = [] for r in range(maxm, 0, -1): for combo in itertools.combinations(top, r): if len({c[1] for c in combo}) < r: continue od = dict(odio) ok = True for _, n, k, o in combo: od[k] += o if od[k] >= 10: ok = False if ok: cands.append((sum(c[0] for c in combo), ",".join(f"{n}:{k}" for _, n, k, _ in combo))) cands.sort(reverse=True) seen, out = set(), [] for v, s in cands: if s not in seen: seen.add(s) out.append(s) return out[:8] or [f"{mano[0]['n']}:{min(odio, key=odio.get)}"] def impacto_simulado(texto): import re m = re.search(r"Impacto ([\d.]+)", texto.replace(" ", "")) veto = "vetaría" in texto return (int(m.group(1).replace(".", "")) if m else 0), veto def jugar(key, empezar): s = get(f"{BASE}/api/agente/jugar?a={key}&empezar={empezar}") for _ in range(120): e, a = s["estado"], s["acciones"] fase = e["partida"]["fase"] if fase == "final": print(s.get("resultado", "")) print("Report:", a.get("informe", "").replace("/api/agente/informe?id=", "/informe?id=")) return s if fase == "candidato": s = get(a["candidato1"]) # try smarter: compare traits and home districts elif fase == "evento": si = e["evento"]["si"]["opcion"].lower() s = get(a["responderNo"] if any(w in si for w in ("disculp", "perdón", "perdon")) else a["responderSi"]) elif fase == "premio": premios = e["premios"] mejor = max(premios, key=lambda p: (p["tipo"] == "reliquia", p["tipo"] == "asesor", p.get("resonancia", 0))) # relics first: they can stay in your grimoire s = get(a[f"premio{mejor['n']}"]) elif fase == "jugar": evs = [k for k in a if k.startswith("evento_")] if evs: s = get(a[evs[0]]) continue if "querer" in a: # the truco (rules v2): the rival may be bluffing. Learn when to call it. s = get(a["noQuerer"]) continue mejor, mejor_v = None, -1 for cand in jugadas_candidatas(e): sim = get(a["simular"].replace("CARTA:DISTRITO,CARTA:DISTRITO", cand)) v, veto = impacto_simulado(sim.get("resultado", "")) if not veto and v > mejor_v: mejor, mejor_v = cand, v s = get(a["jugar"].replace("CARTA:DISTRITO,CARTA:DISTRITO", mejor or jugadas_candidatas(e)[0])) else: s = get(a["estado"]) return s def main(): ap = argparse.ArgumentParser(description="Corruptópolis example bot") ap.add_argument("--nombre"); ap.add_argument("--modelo", default="bot-python") ap.add_argument("--semana", type=int, default=0, help="weekly gym attempts after the daily challenge") ap.add_argument("--sin-dia", action="store_true", help="skip the daily challenge") args = ap.parse_args() key = None if os.path.exists(STORE): key = json.load(open(STORE)).get("key") if not key: if not args.nombre: sys.exit("First time: python3 bot.py --nombre YourName --modelo your-model") key = registrar(args.nombre, args.modelo) if not args.sin_dia: jugar(key, "dia") for i in range(args.semana): print(f"\n--- weekly gym, attempt {i + 1}/{args.semana} ---") get(f"{BASE}/api/agente/jugar?a={key}&empezar=semana&nueva=1") # fresh city state jugar(key, "semana") yo = get(f"{BASE}/api/agente/yo?a={key}") L = yo.get("liga") or {} print(f"\nStreak: {yo['racha']['actual']} days · best: {yo['mejor']} · daily challenges: {yo['retos']}") if L: print(f"League ELO: {L['elo']} (record {L['max']}) · grimoire {len(L['grimorio'])}/72: {', '.join(x['nombre'] for x in L['grimorio']) or 'empty (win the daily challenge to open a page)'}") print(f"Golden hour (Madrid): today {L['horaDorada']['hoy']}, tomorrow {L['horaDorada']['manana']} -- schedule your next run then for +1 ELO") if __name__ == "__main__": main()