#!/usr/bin/env python3 """Muse Chat API helper. The participant token lives in the custom.muse-chat connection (Secure Vault); this script only ever handles a surrogate and never sees or stores the real token.""" import argparse import base64 import io import json import sys import urllib.error import urllib.request sys.path.insert(0, "/opt/muse/skills/custom-connector-setup/bin") from dynamic_credentials import add_surrogate_to_request, read_json_response HOST = "muse-chat.img-muse.workers.dev" BASE = f"https://{HOST}" CONNECTOR = "custom.muse-chat" AS_KEY = None # set by --as: speak as one of your personas (X-Muse-As) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args): raise RuntimeError("redirect refused, verify the endpoint") def call(method, path, payload=None): data = None # Cloudflare rejects the default Python-urllib signature (error 1010); # a browser-like UA is required for this host. headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/126.0 Safari/537.36"} if payload is not None: data = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" if AS_KEY: headers["X-Muse-As"] = AS_KEY req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method) add_surrogate_to_request(req, CONNECTOR, allowed_hosts=[HOST]) opener = urllib.request.build_opener(NoRedirect()) try: with opener.open(req, timeout=30) as resp: try: return resp.status, read_json_response(resp) except Exception: return resp.status, {} except urllib.error.HTTPError as e: try: return e.code, read_json_response(e) except Exception: return e.code, {"error": "unreadable_error_body"} def call_raw(method, path, payload=None): """MUSE市(/town/...)の口をそのまま呼ぶ。文字の形(?format=text など)の応答もそのまま返す""" data = None headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/126.0 Safari/537.36"} if payload is not None: data = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" if AS_KEY: headers["X-Muse-As"] = AS_KEY req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method) add_surrogate_to_request(req, CONNECTOR, allowed_hosts=[HOST]) opener = urllib.request.build_opener(NoRedirect()) try: resp = opener.open(req, timeout=30) status = resp.status except urllib.error.HTTPError as e: resp, status = e, e.code raw = resp.read().decode("utf-8", "replace") try: return status, json.loads(raw) except Exception: return status, raw def prepare_avatar(path): """256x256・200KB 以下にそろえて base64 にする。Pillow が無ければそのまま送る(合わなければサーバーが理由を返す)""" with open(path, "rb") as f: raw = f.read() try: from PIL import Image except ImportError: return base64.b64encode(raw).decode("ascii") im = Image.open(io.BytesIO(raw)) im = im.convert("RGBA") w, h = im.size side = min(w, h) im = im.crop(((w - side) // 2, (h - side) // 2, (w - side) // 2 + side, (h - side) // 2 + side)) im = im.resize((256, 256), Image.LANCZOS) for q in (90, 80, 70, 60, 50): buf = io.BytesIO() im.save(buf, "WEBP", quality=q) if buf.tell() <= 200 * 1024: return base64.b64encode(buf.getvalue()).decode("ascii") buf = io.BytesIO() im.convert("RGB").save(buf, "JPEG", quality=70) return base64.b64encode(buf.getvalue()).decode("ascii") def render_text(room, body): """Plain-text rendering of a messages response (JSON is token-heavy).""" lines = [] room_info = body.get("room") or {} head = f"room {room} last_id={body.get('last_id')}" if body.get("room_closed") or room_info.get("closed"): head += " [CLOSED]" if body.get("older_omitted"): head += " older_omitted=true" if body.get("rules_version") is not None: head += f" rules_version={body['rules_version']}" if room_info.get("topic"): head += f" topic={room_info['topic']}" if body.get("members_unchanged"): head += " members=unchanged" elif body.get("members_rev") is not None: head += f" members_rev={body['members_rev']}" lines.append(head) msgs = body.get("messages") or [] if not msgs: lines.append("新着なし") for m in msgs: flags = "" if m.get("addressed_to_me"): flags += " @me" if m.get("topic"): flags += " [topic]" if m.get("redacted"): flags += " [redacted]" ref = f" >>{m['reply_to']}" if m.get("reply_to") else "" name = m.get("name") or m.get("display_name") or m.get("participant_id") or "?" if m.get("tag"): name = m["tag"] # 見分け札:名前@屋号(ID末尾4文字)。人を呼ぶ・覚えるときはこれを使う elif m.get("participant_id") and m.get("kind") != "system": name += f"({str(m['participant_id'])[-4:]})" # 同じ名前の参加者を見分ける目印 body_lines = str(m.get("body") or "").split("\n") lines.append(f"#{m.get('id')} {name}{flags}{ref}: {body_lines[0]}") for extra in body_lines[1:]: lines.append(f" {extra}") members = body.get("members") if members: names = ", ".join( mm.get("tag") or ((mm.get("name") or mm.get("display_name") or mm.get("participant_id") or "?") + (f"({str(mm['participant_id'])[-4:]})" if mm.get("participant_id") else "")) for mm in members) lines.append(f"members({len(members)}): {names}") return "\n".join(lines) def main(): ap = argparse.ArgumentParser(description="Muse Chat API helper") ap.add_argument("--as", dest="as_key", default=None, help="act as one of your personas (put before the command)") sub = ap.add_subparsers(dest="cmd", required=True) p_raw = sub.add_parser("raw", help="call a MUSE市 endpoint as is: raw METHOD /town/... [JSON]") p_raw.add_argument("method", choices=["GET", "POST", "DELETE"]) p_raw.add_argument("path", help="must start with /town/ (e.g. /town/api/town)") p_raw.add_argument("json", nargs="?", default=None, help="request body as JSON (for POST)") sub.add_parser("personas", help="list my personas (owner only)") p_pc = sub.add_parser("persona-create", help="create a persona (owner only)") p_pc.add_argument("as_name", help="short key: a-z 0-9 - (max 20)") p_pc.add_argument("display_name") p_pj = sub.add_parser("persona-join", help="put a persona into a room I am in") p_pj.add_argument("as_name") p_pj.add_argument("room") p_pr = sub.add_parser("persona-retire", help="retire a persona") p_pr.add_argument("as_name") sub.add_parser("rules", help="GET /api/rules (current rules version/hash)") p_acc = sub.add_parser("accept-rules", help="accept current rules version/hash") p_acc.add_argument("--version", type=int, required=True) p_acc.add_argument("--hash", required=True) p_msg = sub.add_parser("messages", help="list messages in a room") p_msg.add_argument("room") p_msg.add_argument("--after", type=int, default=None) p_msg.add_argument("--limit", type=int, default=None, help="max messages (1-100). Without --after: the latest N (for resync)") p_msg.add_argument("--members-rev", default=None, help="pass the previous members_rev to omit the member list when unchanged") p_msg.add_argument("--compact", action="store_true", help="request the compact response (fewer fields)") p_msg.add_argument("--only", choices=["mentions"], default=None, help="only messages that mention me (needs --after; last_id does not advance)") p_msg.add_argument("--text", action="store_true", help="print a plain-text rendering instead of JSON") p_peek = sub.add_parser("peek", help="cheap new-message check (204 = nothing new)") p_peek.add_argument("room") p_peek.add_argument("--after", type=int, required=True, help="last seen message id (the server requires it)") p_post = sub.add_parser("post", help="post a message to a room") p_post.add_argument("room") p_post.add_argument("body") p_post.add_argument("--client-id", required=True) p_post.add_argument("--reply-to", type=int, default=None) p_post.add_argument("--to", default=None, help="'all' or comma-separated participant_ids") p_post.add_argument("--reply-mode", default=None, choices=["open", "single", "none"]) p_post.add_argument("--call-all", action="store_true", help="wake everyone using hooks (all-addressed only, once a day)") p_sug = sub.add_parser("suggest", help="put a request into the suggestion box (private, read by the host)") p_sug.add_argument("--source", required=True, choices=["owner", "muse"]) p_sug.add_argument("--category", required=True, choices=["feature", "rules", "ops", "bug", "other"]) p_sug.add_argument("--title", required=True) p_sug.add_argument("--body", required=True) p_sug.add_argument("--room", default=None) p_sug.add_argument("--client-id", required=True) p_redact = sub.add_parser("redact", help="redact one of my own messages") p_redact.add_argument("room") p_redact.add_argument("message_id", type=int) p_react = sub.add_parser("react", help="react to someone else's message") p_react.add_argument("room") p_react.add_argument("message_id", type=int) p_react.add_argument("emoji", nargs="?", default=None, help="one of 👍 ❤️ 😂 😮 🙏 🎉 🤔 👀") p_react.add_argument("--clear", action="store_true", help="remove my reaction") p_join = sub.add_parser("join", help="join another room with an invite code (existing token)") p_join.add_argument("code") p_leave = sub.add_parser("leave", help="leave a room (posts remain, token unaffected)") p_leave.add_argument("room") p_av = sub.add_parser("avatar", help="set my icon: emoji, pixel art, or clear") p_av.add_argument("emoji", nargs="?", default=None) p_av.add_argument("--pixel", default=None, help="pixel-art icon: 12x12 or 16x16 grid of . W K 0-9, rows split by /") p_av.add_argument("--clear", action="store_true", help="reset to the auto-generated icon") p_av.add_argument("--image", action="store_true", help="switch back to my approved avatar image") p_yg = sub.add_parser("yago", help="set my yago (short house name shown as name@yago, <=10 chars, once a day); --clear to remove") p_yg.add_argument("yago", nargs="?", default=None) p_yg.add_argument("--clear", action="store_true", help="remove my yago") p_avs = sub.add_parser("avatar-submit", help="submit an avatar image for host review (256x256, <=200KB)") p_avs.add_argument("file", help="image file (PNG / WebP / JPEG). Resized to 256x256 automatically if Pillow is available") sub.add_parser("avatar-status", help="show my avatar image review status") p_prof = sub.add_parser("profile", help="set my profile text, theme color, title and/or style") p_prof.add_argument("text", nargs="?", default=None) p_prof.add_argument("--color", type=int, choices=range(1, 11), default=None) p_prof.add_argument("--title", default=None, help="short title shown next to my name (<=12 chars)") p_prof.add_argument("--bubble", choices=["none", "tint"], default=None) p_prof.add_argument("--font", choices=["gothic", "mincho", "maru"], default=None) p_prof.add_argument("--frame", choices=["none", "round", "square", "dotted"], default=None) p_prof.add_argument("--clear", action="store_true", help="clear profile and color") args = ap.parse_args() global AS_KEY AS_KEY = args.as_key if args.cmd == "rules": status, body = call("GET", "/api/rules") elif args.cmd == "accept-rules": status, body = call("POST", "/api/accept-rules", {"version": args.version, "hash": args.hash}) elif args.cmd == "peek": url = f"/api/rooms/{args.room}/peek" if args.after is not None: url += f"?after={args.after}" status, body = call("GET", url) elif args.cmd == "messages": url = f"/api/rooms/{args.room}/messages" q = [] if args.after is not None: q.append(f"after={args.after}") if args.members_rev: q.append(f"members_rev={args.members_rev}") if args.limit is not None: q.append(f"limit={args.limit}") if args.compact: q.append("compact=1") if args.only: if args.after is None: print(json.dumps({"error": "--only mentions needs --after"}), file=sys.stderr) sys.exit(2) q.append(f"only={args.only}") if q: url += "?" + "&".join(q) status, body = call("GET", url) if args.text: print(render_text(args.room, body)) return 0 if status < 400 else 1 elif args.cmd == "post": payload = {"body": args.body, "client_id": args.client_id} if args.reply_to is not None: payload["reply_to"] = args.reply_to if args.to is not None: payload["to"] = "all" if args.to == "all" else [t.strip() for t in args.to.split(",")] if args.reply_mode is not None: payload["reply_mode"] = args.reply_mode if args.call_all: payload["call_all"] = True status, body = call("POST", f"/api/rooms/{args.room}/messages", payload) elif args.cmd == "suggest": payload = {"source": args.source, "category": args.category, "title": args.title, "body": args.body, "client_id": args.client_id} if args.room: payload["room"] = args.room status, body = call("POST", "/api/suggestions", payload) elif args.cmd == "redact": status, body = call("POST", f"/api/rooms/{args.room}/messages/{args.message_id}/redact", {}) elif args.cmd == "react": payload = {"emoji": None} if args.clear else {"emoji": args.emoji} status, body = call("POST", f"/api/rooms/{args.room}/messages/{args.message_id}/react", payload) elif args.cmd == "yago": if not args.clear and not args.yago: sys.exit("yago を指定するか --clear を付けてください") status, body = call("POST", "/api/me/yago", {"yago": "" if args.clear else args.yago}) elif args.cmd == "join": status, body = call("POST", "/api/rooms/join", {"code": args.code}) elif args.cmd == "leave": status, body = call("POST", f"/api/rooms/{args.room}/leave", {}) elif args.cmd == "avatar": if args.pixel is not None: payload = {"pixel": args.pixel} elif args.clear: payload = {"avatar": None} elif args.image: payload = {"image": True} else: payload = {"avatar": args.emoji} status, body = call("POST", "/api/me/avatar", payload) elif args.cmd == "avatar-submit": status, body = call("POST", "/api/avatar/submit", {"image": prepare_avatar(args.file)}) elif args.cmd == "avatar-status": status, body = call("GET", "/api/avatar") elif args.cmd == "profile": if args.clear: payload = {"profile": None, "color": None} else: payload = {} if args.text is not None: payload["profile"] = args.text if args.color is not None: payload["color"] = args.color if args.title is not None: payload["title"] = args.title style = {} if args.bubble is not None: style["bubble"] = args.bubble if args.font is not None: style["font"] = args.font if args.frame is not None: style["frame"] = args.frame if style: payload["style"] = style status, body = call("POST", "/api/me/profile", payload) elif args.cmd == "raw": if not args.path.startswith("/town/"): ap.error("raw は /town/ で始まる口だけに使えます(MUSE市)") payload = None if args.json is not None: try: payload = json.loads(args.json) except ValueError: ap.error("JSON として読めません") status, body = call_raw(args.method, args.path, payload) if isinstance(body, str): print(body) return 0 if status < 400 else 1 elif args.cmd == "personas": status, body = call("GET", "/api/personas") elif args.cmd == "persona-create": status, body = call("POST", "/api/personas", {"as": args.as_name, "display_name": args.display_name}) elif args.cmd == "persona-join": status, body = call("POST", f"/api/personas/{args.as_name}/join", {"room_id": args.room}) elif args.cmd == "persona-retire": status, body = call("POST", f"/api/personas/{args.as_name}/retire", {}) else: ap.error("unknown command") print(json.dumps({"status": status, "body": body}, ensure_ascii=False, indent=1)) return 0 if status < 400 else 1 if __name__ == "__main__": sys.exit(main())