Skip to content

Websocket Server Requests

VRFlad edited this page Jun 26, 2021 · 2 revisions

Requests can be made to the server, in JSON format, the basic format for a request is as follows:

{
  "request": "<request>",
  "id": "<id>"
}

Get Actions (0.41)

This request will get you a list of all the actions you currently have.

Response:

{
  "id": "<message id>",
  "count": 00,
  "actions": [
    {
      "id": "<action guid>",
      "name": "<action name>"
    },
  ],
  "status": "ok"
}

DoAction (0.41)

This request will trigger an action that you provide

{
  "request": "<request>",
  "action": {
    "id": "<guid>",
    "name": "<name>"
  },
  "args": {
    "key": "value",
  },
  "id": "<id>"
}

If the action is not found, an error will be returned, if the action was dispatched it will return success.

{
  "id": "<id>",
  "status": "ok"
}

Example JavaScript code that can be used with Websocket Server:

Code to connect - this function is ideally called directly / indirectly from onload

function connectws() {
if ("WebSocket" in window) {
  var ws = new WebSocket("ws://localhost:8080/");

Code to attempt to reconnect (after 10 seconds) when disconnected:

  ws.onclose = function() 
    { 
    setTimeout("connectws()",10000);
    };

Code to subscribe to events - In this example: Follows, Cheers, Subs, Resubs, Gift Subs and Gift Bombs.

ws.onopen = function(){
  ws.send('{"request": "Subscribe", "events": {"Twitch": ["Follow","Cheer","Sub","Resub","GiftSub","GiftBomb"] },"id": "123"}')
}    

Code to Handle the above messages when received from the server:

  ws.onmessage = function (event) 
    { 
    var received_msg = event.data;
    //parse JSON
    var wsdata=JSON.parse(received_msg);
    //check for events to trigger
   if (wsdata.event.source=="Twitch")
   {
    if (wsdata.event.type=="Sub" || wsdata.event.type=="ReSub")
    {
        alert("trigger sub event for "+wsdata.data.displayName);
    }
    else if ( wsdata.event.type=="GiftSub")
    {
        alert("trigger Gift sub event for "+wsdata.data.recipientDisplayName);
    }
    else if (wsdata.event.type=="GiftBomb")
    {
        if  (wsdata.data.isAnonymous==false)
        {
        alert("trigger gift bomb event for "+wsdata.data.displayName+" "+wsdata.data.gifts+" subs");
        }
        else
        {
        alert("trigger gift bomb event for Anonymous "+wsdata.data.gifts+" subs");
        }
    }
    else if (wsdata.event.type=="Follow")
    {
        alert("trigger follow event for "+wsdata.data.displayName);
    }
    else if (wsdata.event.type=="Cheer")
    {
        alert("trigger cheer event for "+wsdata.data.message.displayName+wsdata.data.message.bits);
    }
   }
    };

Clone this wiki locally