IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import aiohttp
|
||||
|
||||
KEYS_FILE = os.environ.get("AFKEYS", "/opt/grok-bot/apiframe_keys.jsonl")
|
||||
API = "https://api.apiframe.ai"
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
|
||||
|
||||
_dead = {}
|
||||
_sem = asyncio.Semaphore(2)
|
||||
|
||||
|
||||
def _load_keys():
|
||||
keys = []
|
||||
try:
|
||||
with open(KEYS_FILE, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
d = json.loads(line)
|
||||
k = d.get("key") or d.get("api_key")
|
||||
if isinstance(d, str):
|
||||
k = d
|
||||
if k and k.startswith("afk_"):
|
||||
keys.append(k)
|
||||
except Exception:
|
||||
if line.startswith("afk_"):
|
||||
keys.append(line)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
# dedupe, keep order
|
||||
seen, out = set(), []
|
||||
for k in keys:
|
||||
if k not in seen:
|
||||
seen.add(k)
|
||||
out.append(k)
|
||||
return out
|
||||
|
||||
|
||||
def _alive_keys():
|
||||
now = time.time()
|
||||
return [k for k in _load_keys() if now - _dead.get(k, 0) > 1800]
|
||||
|
||||
|
||||
def _headers(key):
|
||||
return {"X-API-Key": key, "User-Agent": UA,
|
||||
"Origin": "https://apiframe.ai", "Referer": "https://apiframe.ai/"}
|
||||
|
||||
|
||||
async def get_credits(session, key):
|
||||
try:
|
||||
async with session.get(API + "/v2/credits", headers=_headers(key),
|
||||
timeout=aiohttp.ClientTimeout(total=20)) as r:
|
||||
if r.status != 200:
|
||||
return None
|
||||
d = await r.json()
|
||||
return d.get("credits", d.get("balance"))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def pool_status():
|
||||
"""[{key_tail, credits}] for admin."""
|
||||
out = []
|
||||
async with aiohttp.ClientSession() as s:
|
||||
for k in _load_keys():
|
||||
c = await get_credits(s, k)
|
||||
out.append({"key": k[:8] + "..." + k[-4:], "credits": c,
|
||||
"dead": (time.time() - _dead.get(k, 0)) < 1800})
|
||||
return out
|
||||
|
||||
|
||||
async def generate_music(prompt, title=None, style=None, instrumental=False,
|
||||
model_version="V5", timeout=420):
|
||||
"""Generate a Suno track. Returns dict:
|
||||
{ok, tracks:[{audioUrl,title,imageUrl}], error, key_tail}"""
|
||||
keys = _alive_keys()
|
||||
if not keys:
|
||||
return {"ok": False, "error": "POOL_EMPTY"}
|
||||
payload = {"model": "suno", "prompt": prompt}
|
||||
sp = {"model_version": model_version, "instrumental": bool(instrumental)}
|
||||
if title or style:
|
||||
sp["custom_mode"] = True
|
||||
if title:
|
||||
sp["title"] = title
|
||||
if style:
|
||||
sp["style"] = style
|
||||
sp["negative_tags"] = "instrumental, pop, slow" if not instrumental else "vocal"
|
||||
payload["sunoParams"] = sp
|
||||
|
||||
async with _sem:
|
||||
last_err = None
|
||||
for key in keys:
|
||||
try:
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.post(API + "/v2/music/generate", headers=_headers(key),
|
||||
json=payload, timeout=aiohttp.ClientTimeout(total=40)) as r:
|
||||
body = await r.text()
|
||||
if r.status == 402:
|
||||
_dead[key] = time.time()
|
||||
last_err = "NO_CREDITS"
|
||||
continue
|
||||
if r.status == 401 or r.status == 403:
|
||||
_dead[key] = time.time()
|
||||
last_err = "KEY_DEAD_%d" % r.status
|
||||
continue
|
||||
if r.status not in (200, 202):
|
||||
last_err = "HTTP_%d:%s" % (r.status, body[:120])
|
||||
continue
|
||||
try:
|
||||
d = json.loads(body)
|
||||
except Exception:
|
||||
last_err = "BAD_JSON"
|
||||
continue
|
||||
job = d.get("jobId") or d.get("job_id") or d.get("id")
|
||||
if not job:
|
||||
last_err = "NO_JOBID:%s" % body[:120]
|
||||
continue
|
||||
# poll
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
await asyncio.sleep(8)
|
||||
async with aiohttp.ClientSession() as s2:
|
||||
async with s2.get(API + "/v2/jobs/" + job, headers=_headers(key),
|
||||
timeout=aiohttp.ClientTimeout(total=25)) as jr:
|
||||
try:
|
||||
jd = await jr.json()
|
||||
except Exception:
|
||||
continue
|
||||
st = str(jd.get("status", "")).lower()
|
||||
if st in ("done", "succeeded", "success", "completed"):
|
||||
res = jd.get("result") or {}
|
||||
tracks = res.get("tracks") or jd.get("tracks") or []
|
||||
out = [{"audioUrl": t.get("audioUrl") or t.get("audio_url"),
|
||||
"title": t.get("title") or title or "track",
|
||||
"imageUrl": t.get("imageUrl") or t.get("image_url")}
|
||||
for t in tracks if (t.get("audioUrl") or t.get("audio_url"))]
|
||||
return {"ok": bool(out), "tracks": out, "job": job,
|
||||
"key_tail": key[-6:], "error": None if out else "NO_TRACKS"}
|
||||
if st in ("failed", "error", "cancelled"):
|
||||
last_err = "JOB_FAILED:%s" % str(jd.get("error"))[:120]
|
||||
break
|
||||
else:
|
||||
last_err = "TIMEOUT"
|
||||
continue
|
||||
except asyncio.TimeoutError:
|
||||
last_err = "NET_TIMEOUT"
|
||||
except Exception as e:
|
||||
last_err = repr(e)[:150]
|
||||
return {"ok": False, "tracks": [], "error": last_err or "UNKNOWN"}
|
||||
Reference in New Issue
Block a user