8058
Ir
irvc / files
irvc / deploy / dev / tools / post.py
3.2 KB
1#!/usr/bin/env python3 2"""Post messages to a running irvc dev server as a seed user. 3 4Single: post.py -u sean -m "hello" [--at "2026-10-12 09:30"] 5Batch: post.py --jsonl convo.jsonl (lines: {"user","text","at"?}) 6 7Messages go through the real API (auth, validation, websocket broadcast). 8The API stamps messages with the current time, so when --at is given the 9row's created_at is rewritten in the sqlite db afterwards (--db, default 10./irvc.db). Post in chronological order: history is ordered by message id. 11""" 12import argparse, json, sqlite3, sys, time 13from datetime import datetime 14from urllib.request import Request, urlopen 15from urllib.error import HTTPError 16 17def parse_at(s): 18 if s.isdigit(): 19 return int(s) 20 return int(datetime.fromisoformat(s).timestamp()) # naive = local time 21 22class Client: 23 def __init__(self, base): 24 self.base, self.cookies = base.rstrip("/"), {} 25 26 def call(self, method, path, body=None, user=None): 27 data = json.dumps(body).encode() if body is not None else None 28 req = Request(self.base + path, data=data, method=method, 29 headers={"Content-Type": "application/json"}) 30 # Session cookies are Secure, which urllib's jar refuses over http. 31 if user in self.cookies: 32 req.add_header("Cookie", self.cookies[user]) 33 try: 34 resp = urlopen(req) 35 except HTTPError as e: 36 sys.exit(f"{method} {path}: {e.code} {e.read().decode()}") 37 if path == "/api/login": 38 self.cookies[user] = resp.headers["Set-Cookie"].split(";")[0] 39 return json.load(resp) 40 41 def login(self, user, password): 42 if user not in self.cookies: 43 self.call("POST", "/api/login", {"username": user, "password": password}, user) 44 45def main(): 46 ap = argparse.ArgumentParser() 47 ap.add_argument("-u", "--user") 48 ap.add_argument("-m", "--message") 49 ap.add_argument("--at", help="ISO local time or unix seconds") 50 ap.add_argument("--jsonl") 51 ap.add_argument("--channel", default="general", help="text channel name") 52 ap.add_argument("--password", default="11111111") 53 ap.add_argument("--url", default="http://localhost:8080") 54 ap.add_argument("--db", default="irvc.db") 55 a = ap.parse_args() 56 57 if a.jsonl: 58 items = [json.loads(l) for l in open(a.jsonl) if l.strip()] 59 elif a.user and a.message: 60 items = [{"user": a.user, "text": a.message, "at": a.at}] 61 else: 62 ap.error("need --user and --message, or --jsonl") 63 64 c = Client(a.url) 65 first = items[0]["user"] 66 c.login(first, a.password) 67 chans = c.call("GET", "/api/channels", user=first) 68 chan = next(x["id"] for x in chans if x["type"] == "text" and x["name"] == a.channel) 69 70 db = sqlite3.connect(a.db, timeout=5) if any(i.get("at") for i in items) else None 71 for i in items: 72 c.login(i["user"], a.password) 73 m = c.call("POST", f"/api/channels/{chan}/messages", {"body": i["text"]}, i["user"]) 74 if i.get("at"): 75 db.execute("UPDATE messages SET created_at = ? WHERE id = ?", (parse_at(str(i["at"])), m["id"])) 76 db.commit() 77 time.sleep(0.02) 78 print(f"posted {len(items)} message(s) to #{a.channel}") 79 80main()