Skip to content

Instantly share code, notes, and snippets.

@evanaze
Last active August 23, 2020 21:11
Show Gist options
  • Save evanaze/b4fbb72ab176bdc6a1cc1e4ef2708b9b to your computer and use it in GitHub Desktop.
Save evanaze/b4fbb72ab176bdc6a1cc1e4ef2708b9b to your computer and use it in GitHub Desktop.
A method for listening to streaming data on an Amberdata websocket
async def listen(api_key):
"Opens the websocket connection and listens for pending transactions"
# the amberdata websocket uri
uri = 'wss://ws.web3api.io'
# our headers for the connection
headers = {
"x-api-key": api_key["AMBERDATA_API_KEY"],
"x-amberdata-blockchain-id": "408fa195a34b533de9ad9889f076045e"
}
# outer loop
while True:
# create the websocket item
async with websockets.connect(uri, extra_headers=headers) as websocket:
logger.info(f"Connected to Websocket at {uri}")
# the message to pass for pending transactions
message = json.dumps({
'jsonrpc': '2.0',
'id': 2,
'method': 'subscribe',
'params': ['pending_transaction']
})
# send our message to the websocket
await websocket.send(message)
# continuously listen for data and process
while True:
try:
# the response from the websocket
response = await asyncio.wait_for(websocket.recv(), timeout=25)
except Exception as e:
logger.error(str(e))
try:
pong = await websocket.ping()
await asyncio.wait_for(pong, timeout=100)
logger.debug('Ping OK, keeping connection alive...')
continue
except:
# sleep for 30 seconds
await asyncio.sleep(30)
break # inner loop
# interpret the response
await on_response(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment