Multiple Websocket

This is my code:

import websocket
import json
from datetime import datetime
import os
import time

# Intents are passed through here
def on_message(ws, message):
    data = json.loads(message)
    print("**Captured New Intent**")
    print(data)

    if ("Hello" == data["intent"]["name"]):
       print("Hello, Sir")
        
def on_error(ws, error):
    print(error)

def on_close(ws):
    print("\n**Disconnected**\n")

def on_open(ws):
    print("\n**Connected**\n")

# Start web socket client
if __name__ == "__main__":
    ws = websocket.WebSocketApp("ws://localhost:12101/api/events/intent",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

As you can notice, ws = websocket.WebSocketApp(“ws://localhost:12101/api/events/intent”, I only send me the “intent”. If I change it to “wake” it shows me when I say the wakeword. If Change to “text” shows me what you pronounce.

My question is: it is possible to show them the 3 with the same code? That is, I want to receive all the data.

Hey,

Yes, you can receive three of them. I had the same doubt initially.

You need to use threading (from threading import Thread) in python. Then you can create ws for an intent and similarly wake (ws://localhost:12101/api/events/wake) for hot word and so on as you did in your script.
Then,

t1 = Thread(target = ws.run_forever)
t2 = Thread(target = wake.run_forever)
# starting threads 
t1.start()
t2.start()

# wait until all threads finish 
t1.join()
t2.join()

This is how you can achieve it. you can look for more pythonic way but this is simpler one.
Hope this will solve your problem.

1 Like