Websockets Scripting Support

The Localcoin developer community use different ways to interact with the Core API mainly by the use of the Websocket.

Some of this methods are curl, pylocalcoin, wscat and many others.

The most used tool is wscat, this is a great tool but it is not scriptable. I found myself pasting the same commands like login and subscribe to database, crypto and other apis over and over again.

I was after scripting wscat since a while until @gdfbacchus asked in telegram for the same thing.

Python - websocket-client

Python is the choice as it is probably the most used language in the localcoin community.


Simply install by:

pip install websocket-client

Confirm the install by using the wsdump.py tool. This should do the same as wscat:

[email protected]:~# wsdump.py ws://localhost:8090
Press Ctrl+C to quit
> {"method": "call", "params": [1, "login", ["", ""]], "id": 2}

< {"id":2,"result":true}
> {"method": "call", "params": [1, "database", []], "id": 3}

< {"id":3,"result":2}

> {"method": "call", "params": [2, "get_objects", [["1.11.8799012"]]], "id": 4}
< {"id":4,"result":[{"id":"1.11.8799012","op":[14,{"fee":{"amount":281946,"asset_id":"1.3.0"},"issuer":"1.2.89940","asset_to_issue":{"amount":100,"asset_id":"1.3`

Create a python script that will execute the commands one after the other and get the output:

from websocket import create_connection
ws = create_connection("ws://localhost:8090")
ws.send('{"method": "call", "params": [1, "login", ["", ""]], "id": 2}')
result =  ws.recv()
print result

ws.send('{"method": "call", "params": [1, "database", []], "id": 3}')
result =  ws.recv()
print result

ws.send('{"method": "call", "params": [2, "get_objects", [["1.11.8799012"]]], "id": 4}')
result =  ws.recv()
print result


Execute as:

[email protected]:~# python testws.py
[email protected]:~#

You get the results of the 3 calls inside the python script.

Check the “Long-lived connection” sample of the websocket-client documentation in order to make a script that can receive updates.