Files
roblox-project/bunsik-tycoon/tools/cloud.py
EJClaw c7af87c646 feat(bunsik): 직접 만든 효과음 4개, 게임 아이콘·썸네일
- tools/sfx.py: 동전·구매·확장·조리음 합성, 오디오 에셋으로 업로드(Sounds.luau)
- 구매·확장 소리는 클라이언트에서 2D로, 동전 소리는 손님 자리에서 재생
- tools/art.py: 게임 아이콘(512)과 썸네일(1920x1080) 그림 추가
- cloud.py: 오디오 업로드·에셋 상태 조회 명령, 통합 테스트에 효과음 소유 확인(526개 통과)
- DECISIONS: 에셋은 없으면 직접 만든다는 원칙과 현황

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 01:40:00 +09:00

217 lines
8.6 KiB
Python

#!/usr/bin/env python3
"""Open Cloud 도구: 게임 파일 업로드, 로블록스 서버에서 Luau 실행.
python3 tools/cloud.py publish build/BunsikTycoon.rbxl [--published]
python3 tools/cloud.py run script.luau [--version N] [--out file] # 기본: 가장 최근 저장 버전
python3 tools/cloud.py products # 게임패스·개발자 상품 만들기(이미 있으면 건너뜀)
python3 tools/cloud.py place # 서버 인원 6명, 설명 설정
python3 tools/cloud.py audio sfx/coin.ogg "이름" # 효과음 업로드, 에셋 ID 출력
API 키는 ~/.config/ejclaw/secrets.json 의 roblox.opencloud/bunsik-tycoon 에서 읽습니다.
"""
import json
import os
import sys
import time
import urllib.error
import urllib.request
UNIVERSE = 10770390863
CREATOR_USER = 4054147118 # tkrmagid
PLACE = 98118751156219
SECRETS = os.path.expanduser("~/.config/ejclaw/secrets.json")
def api_key():
with open(SECRETS) as f:
return json.load(f)["credentials"]["roblox.opencloud/bunsik-tycoon"]["token"]
def request(method, url, body=None, ctype="application/json", tries=5):
data = body
if body is not None and ctype == "application/json":
data = json.dumps(body).encode()
for attempt in range(tries):
req = urllib.request.Request(url, data=data, method=method)
req.add_header("x-api-key", api_key())
if data is not None:
req.add_header("Content-Type", ctype)
try:
with urllib.request.urlopen(req, timeout=120) as r:
raw = r.read()
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
msg = e.read().decode(errors="replace")
if e.code in (429, 500, 502, 503, 504) and attempt < tries - 1:
time.sleep(5 * (attempt + 1))
continue
raise SystemExit(f"HTTP {e.code} {method} {url}\n{msg}")
def publish(path, published=False):
vt = "Published" if published else "Saved"
with open(path, "rb") as f:
body = f.read()
url = f"https://apis.roblox.com/universes/v1/{UNIVERSE}/places/{PLACE}/versions?versionType={vt}"
res = request("POST", url, body, "application/octet-stream")
return res["versionNumber"]
def run(script, version=None, timeout_s=300, binary_out=None):
base = f"https://apis.roblox.com/cloud/v2/universes/{UNIVERSE}/places/{PLACE}"
if version:
base += f"/versions/{version}"
body = {"script": script, "timeout": f"{timeout_s}s"}
if binary_out:
body["enableBinaryOutput"] = True
task = request("POST", base + "/luau-execution-session-tasks", body)
path = task["path"]
while task.get("state") not in ("COMPLETE", "FAILED", "CANCELLED"):
time.sleep(3)
task = request("GET", f"https://apis.roblox.com/cloud/v2/{path}")
if binary_out and task.get("binaryOutputUri"):
with urllib.request.urlopen(task["binaryOutputUri"], timeout=120) as r, open(binary_out, "wb") as f:
f.write(r.read())
logs = request("GET", f"https://apis.roblox.com/cloud/v2/{path}/logs?maxPageSize=10000")
lines = []
for page in logs.get("luauExecutionSessionTaskLogs", []):
lines.extend(page.get("messages", []))
return task, lines
def multipart(fields, files):
boundary = "----bunsik" + str(int(time.time() * 1000))
out = b""
for k, v in fields.items():
out += f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n".encode()
for k, path in files.items():
with open(path, "rb") as f:
data = f.read()
name = os.path.basename(path)
out += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"; filename=\"{name}\"\r\n"
f"Content-Type: image/png\r\n\r\n").encode() + data + b"\r\n"
out += f"--{boundary}--\r\n".encode()
return out, f"multipart/form-data; boundary={boundary}"
ART = os.path.join(os.path.dirname(__file__), "..", "art")
PRODUCTS = [
# (종류, 이름, 설명, 가격, 그림, Products.luau 키)
("game-passes", "Double Money (2배 수익)",
"All sales are doubled forever! 모든 판매 금액이 영원히 2배!", 199, "double_money.png", "DOUBLE_MONEY_PASS"),
("developer-products", "Money Boost (돈 부스트)",
"Get 10 minutes of your current sales right now. 지금 매출 10분치를 바로 받아요.", 25, "money_boost.png",
"MONEY_BOOST_PRODUCT"),
]
def products():
found = {}
for kind, name, desc, price, image, key in PRODUCTS:
if kind == "game-passes":
base = f"https://apis.roblox.com/game-passes/v1/universes/{UNIVERSE}/game-passes"
listing = request("GET", base + "/creator?pageSize=100")
items = listing.get("gamePasses", [])
id_key = "gamePassId"
else:
base = f"https://apis.roblox.com/developer-products/v2/universes/{UNIVERSE}/developer-products"
listing = request("GET", base + "/creator?pageSize=100")
items = listing.get("developerProducts", [])
id_key = "productId"
existing = [i for i in items if i.get("name") == name]
if existing:
found[key] = existing[0][id_key]
print(f"{key}: 이미 있음 {found[key]}")
continue
body, ctype = multipart(
{"name": name, "description": desc, "price": str(price), "isForSale": "true",
"isRegionalPricingEnabled": "false"},
{"imageFile": os.path.join(ART, image)},
)
res = request("POST", base, body, ctype)
found[key] = res[id_key]
print(f"{key}: 만듦 {found[key]}")
return found
def place():
url = (f"https://apis.roblox.com/cloud/v2/universes/{UNIVERSE}/places/{PLACE}"
"?updateMask=serverSize,description")
body = {
"serverSize": 6,
"description": "떡볶이 포장마차에서 시작해 분식 제국을 키우는 타이쿤! "
"Grow your tiny tteokbokki street stall into a K-food empire!",
}
return request("PATCH", url, body)
def upload_audio(path, name):
meta = {
"assetType": "Audio",
"displayName": name,
"description": "Bunsik Tycoon sound effect (synthesized, original).",
"creationContext": {"creator": {"userId": str(CREATOR_USER)}},
}
boundary = "----bunsik" + str(int(time.time() * 1000))
with open(path, "rb") as f:
data = f.read()
body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"request\"\r\n"
f"Content-Type: application/json\r\n\r\n{json.dumps(meta)}\r\n").encode()
body += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"fileContent\"; "
f"filename=\"{os.path.basename(path)}\"\r\nContent-Type: audio/ogg\r\n\r\n").encode()
body += data + f"\r\n--{boundary}--\r\n".encode()
op = request("POST", "https://apis.roblox.com/assets/v1/assets", body, f"multipart/form-data; boundary={boundary}")
for _ in range(60):
if op.get("done"):
break
time.sleep(3)
op = request("GET", f"https://apis.roblox.com/assets/v1/{op['path']}")
if op.get("error"):
raise SystemExit(f"업로드 실패: {op['error']}")
return op.get("response", {}).get("assetId")
def asset_status(asset_id):
return request("GET", f"https://apis.roblox.com/assets/v1/assets/{asset_id}?readMask=moderationResult,state")
def main(argv):
if argv[:1] == ["audio"]:
print(upload_audio(argv[1], argv[2]))
return 0
if argv[:1] == ["asset"]:
print(json.dumps(asset_status(argv[1]), ensure_ascii=False))
return 0
if argv[:1] == ["products"]:
print(json.dumps(products()))
return 0
if argv[:1] == ["place"]:
print(json.dumps(place(), ensure_ascii=False))
return 0
if len(argv) >= 2 and argv[0] == "publish":
v = publish(argv[1], "--published" in argv)
print(f"version {v}")
return 0
if len(argv) >= 2 and argv[0] == "run":
version = None
if "--version" in argv:
version = int(argv[argv.index("--version") + 1])
with open(argv[1]) as f:
script = f.read()
out = argv[argv.index("--out") + 1] if "--out" in argv else None
task, lines = run(script, version, binary_out=out)
for line in lines:
print(line)
print(f"state: {task['state']}")
if task["state"] == "COMPLETE":
print("output:", json.dumps(task.get("output", {}), ensure_ascii=False))
return 0
print("error:", json.dumps(task.get("error", {}), ensure_ascii=False))
return 1
print(__doc__)
return 2
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))