241 lines
10 KiB
Python
241 lines
10 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 출력
|
|
python3 tools/cloud.py image art/kitchen.png "이름" # 그림 업로드, 에셋 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"),
|
|
("game-passes", "Rainbow Shop Name (무지개 가게 이름)",
|
|
"Your shop name shines in rainbow colors for everyone! 가게 이름이 무지개색으로 반짝여요!", 99,
|
|
"rainbow_name.png", "RAINBOW_NAME_PASS"),
|
|
("game-passes", "Candy Castle Design (사탕 궁전 디자인)",
|
|
"A pastel candy shop with hearts and lollipops. 하트와 막대사탕이 있는 사탕 궁전 가게 디자인", 149,
|
|
"candy_design.png", "CANDY_DESIGN_PASS"),
|
|
("game-passes", "Hanok Design (한옥 분식집 디자인)",
|
|
"A traditional Korean hanok shop with a tiled roof and lanterns. 기와지붕과 등롱이 있는 한옥 가게 디자인", 149,
|
|
"hanok_design.png", "HANOK_DESIGN_PASS"),
|
|
("developer-products", "Customer Rush (손님 러시)",
|
|
"Customers come twice as fast for 10 minutes. 10분 동안 손님이 2배 빨리 와요.", 15, "rush.png",
|
|
"RUSH_PRODUCT"),
|
|
("developer-products", "Bring Customers (옆 가게 손님 데려오기)",
|
|
"Customers waiting at a neighbor shop come to your shop. 옆 가게에서 기다리던 손님이 우리 가게로 와요.", 15,
|
|
"kick.png", "KICK_PRODUCT"),
|
|
("developer-products", "Promotion Ad Reward (홍보 광고 보상)",
|
|
"Reward for watching an ad: neighbor customers visit your shop. 광고를 보면 옆 가게 손님이 와요.", 5,
|
|
"promote_ad.png", "PROMOTE_AD_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, asset_type="Audio", mime="audio/ogg",
|
|
description="Bunsik Tycoon sound effect (synthesized, original)."):
|
|
meta = {
|
|
"assetType": asset_type,
|
|
"displayName": name,
|
|
"description": description,
|
|
"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: {mime}\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] == ["image"]:
|
|
# 그림 업로드(화면 UI 그림 모음). 에셋 ID 출력
|
|
print(upload_audio(argv[1], argv[2], "Image", "image/png", "Bunsik Tycoon UI art (drawn in code, original)."))
|
|
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:]))
|