// TODO: stop when removed!! !7 lib 1002612 // websocket (tyrus) import javax.websocket.*; import org.glassfish.tyrus.client.*; static PersistentLog log; static volatile long started, triedStarting; p { log = new PersistentLog("log"); thread "Slack RTM Bot" { background(); } } synchronized answer { if "rtm started" ret yn(started != 0); if "rtm log size" ret lstr(log); if (master() && match("rtm last event", s)) ret structure(last(log)); if (master() && match("rtm clear", s)) { ret confirm("Clear RTM log?", new ClearLog); } try answer status_answer(s); } static class ClearLog { S answer(S s) { log.clear(); ret "OK, cleared RTM log."; } } static void background() ctex { triedStarting = now(); S token = devChannelToken(); S url = "https://slack.com/api/rtm.start"; Map postData = litmap("token", token, "no_unreads", "1"); S data = doPost(postData, url); Map map = cast jsonDecode(data); //printStructure(map); S websocketURL = getString(map, "url"); print("Websocket URL: " + websocketURL); assertTrue(nempty(websocketURL)); final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build(); ClientManager client = ClientManager.createClient(); client.connectToServer(new Endpoint() { public void onOpen(Session session, EndpointConfig config) ctex { session.addMessageHandler(new MessageHandler.Whole() { public void onMessage(String message) { incomingMessage(message); } }); } }, cec, new URI(websocketURL)); started = now(); } static synchronized void incomingMessage(S msg) { print("RTM incoming: " + msg); Map map = jsonDecodeMap(msg); if (!eq(getString(map, "type"), "reconnect_url")) // ignore those log.add(msg); }