Exemple #1
0
    def connect(self):
        is_ready = False

        options = {'exit_event': self._exit_event, 'poll': 0.1, 'ping_rate': 0}

        for event in persist(self._websocket, **options):
            if is_ready:
                try:
                    message = self._messages.get(False)
                    #print 'SEND %s' % message
                    self._websocket.send_text(
                        unicode(json.dumps(message), 'utf-8'))
                except Queue.Empty:
                    pass

            if event.name == 'ready':
                is_ready = True
            if event.name == 'text':
                body = json.loads(event.text)
                if 'id' in body:
                    #print 'RECV %s' % (body,)
                    self._results[body['id']] = body
                    self._locks.pop(body['id']).release()
                elif body.get('method') == 'Target.receivedMessageFromTarget':
                    result = json.loads(body['params']['message'])
                    if 'id' in result:
                        #print 'RECV %s' % (body,)
                        self._results[result['id']] = result
                        self._locks.pop(result['id']).release()
Exemple #2
0
 def monitor(self):
     for event in persist(self.ws):
         try:
             if not self.running:
                 self.thread_stopped = True
                 return
             if event.name == 'connecting':
                 print('connecting...')
             elif event.name == 'connected':
                 print('connected')
                 self.connected = True
             elif event.name == 'pong':
                 print('received pong')
             elif event.name == 'poll':
                 print('received poll')
             elif event.name == 'text':
                 json_str = event.text
                 data = json.loads(json_str)
                 if data['op'] == 'publish':
                     topic_id = data['topic']
                     if topic_id in self.pub_callbacks:
                         self.pub_callbacks[topic_id](data['msg'])
                 elif data['op'] == 'service_response':
                     service_id = data['service']
                     if service_id in self.srv_callbacks:
                         self.srv_callbacks[service_id](data['result'])
                 else:
                     print('unknown data: ', data)
             else:
                 print('unhandled event: ', event.name)
                 print(event)
         except:
             logging.exception('error handling %r', event)
Exemple #3
0
 def run(self):
     """
     Thread loop
     Listens for WS messages, and adds them the q_rx Queue.
     Monitors the q_tx, and sends any messages it finds.
     Handles PING, PONG, and POLL messages.
     :return:
     """
     for event in persist(self.ws):
         logging.info('RX-EVENT: ' + event.name)
         logging.debug(event)
         if self.stop:
             logging.info('STOP REQUESTED')
             break
         # WS reporting session is established
         if event.name == 'ready':
             self.ready = True
         # Service has sent us a text message
         elif event.name == 'text':
             logging.debug(event.text)
             self.q_rx.put(event.text)
         elif event.name not in self.ignore_events:
             logging.error('UNKNOWN RX-EVENT: ' + event.name)
         while self.ready:
             if not self.q_tx.empty():
                 send_msg = self.q_tx.get()
                 logging.info('TX-EVENT: ' + send_msg)
                 self.ws.send_text(send_msg)
                 self.q_tx.task_done()
             else:
                 break
     logging.info('CLOSING')
     self.ws.close()
Exemple #4
0
 def requests(self, persistent=True, **persist_args):
     """Return an interator"""
     events = persist(self, **persist_args) if persistent else self
     for event in events:
         request = self.get_request(event)
         if request is not None:
             yield request
 def run(self):
     """Main websocket handling loop."""
     try:
         with self.websocket:
             for event in persist(self.websocket):
                 log.debug('WS %r', event)
                 try:
                     self.on_event(event)
                 except Exception as error:
                     log.exception('error handling websocket event')
     except (SystemExit, KeyboardInterrupt):
         log.info('exit requested')
     except Exception:
         log.exception('unhandled error from websocket')
     self.on_close()
Exemple #6
0
    def websocket_task(self) -> None:
        """
        Runs the websocket task.
        """
        ws = WebSocket(self.url, agent=USER_AGENT)
        self._ws = ws
        # generate poll events every 0.5 seconds to see if we can cancel
        websocket = persist(ws,
                            ping_rate=0,
                            poll=1,
                            exit_event=self._cancelled)
        for event in websocket:
            self._portal.run(self._queue.put, event)

        # signal the end of the queue
        self._portal.run(self._queue.put, self._done)
Exemple #7
0
    def websocket_handler(self) -> None:
        """
        The actual websocket handler.

        This wraps the Lomond reconnecting websocket, putting data on the queue.
        """
        ws = WebSocket(self.url, agent=USER_AGENT)
        self._ws = ws
        # generate poll events every 0.5 seconds to see if we can cancel
        websocket = persist(ws,
                            ping_rate=0,
                            poll=1,
                            exit_event=self._cancelled)
        for event in websocket:
            self._queue.put(event)

        # signal the end of the queue
        self._queue.put(self._done)
Exemple #8
0
def persist_testing_helper(mocker, validate_function, websocket_connect=None):
    # ok. First, we start off by calling .spy on our fake function, so that
    # we could verify that it was called
    mocker.spy(FakeEvent, 'wait')
    # now, we patch the import path to threading.Event and replace it with
    # our own FakeEvent. Therefore, whenever persist.py will try to import
    # threading.Event, it will actually import FakeEvent
    mocker.patch('lomond.persist.threading.Event', FakeEvent)
    # great, now a simple websocket imposter
    websocket = FakeWebSocket()
    if websocket_connect:
        websocket.connect = websocket_connect

    yielded_events = list(persist(websocket))

    # the sole fact that we ended up in this line means that the event
    # method was called, but we can nevertheless check it
    assert FakeEvent.wait.call_count == 1

    # and now we can validate the events.
    validate_function(yielded_events)
    def connect(self):
        is_ready = False

        options = {'exit_event': self._exit_event, 'poll': 0.1, 'ping_rate': 0}

        for event in persist(self._websocket, **options):
            print event.name
            if is_ready:
                try:
                    message = self._messages.get(False)
                    self._websocket.send_text(
                        unicode(json.dumps(message), 'utf-8'))
                except Queue.Empty:
                    pass

            if event.name == 'ready':
                is_ready = True
            if event.name == 'text':
                body = json.loads(event.text)
                if 'id' in body:
                    self._results[body['id']] = body
                    self._locks.pop(body['id']).release()
Exemple #10
0
    def start_websocket(self):
        self.websocket = WebSocket(f'ws://{self.address}/')

        for event in persist(self.websocket):

            if event.name == 'ready':
                self.websocket.send_json(command='join_group',
                                         data=dict(key=self.key))

            if event.name == 'text':
                if event.json['command'] == 'new_id':
                    self.websocket_id = event.json['id']

                if event.json['command'] == 'new_view':
                    print('New view')
                    print(event.json['source'])
                    print(self.websocket_id)
                    if event.json['source'] != self.websocket_id:
                        flare.invoke_later(target=self.set_camera,
                                           args=(event.json['view'], ))

            if self.thread_exit:
                self.thread_exit = False
                break
def ws():
    nicknames = {}
    file_names = {}
    headers = {}
    trades = {}
    opened_files = {}
    old_ob = {}
    send_ob = {}
    global deri_ob
    deri_ob = {}
    high = {}
    low = {}

    time_now = datetime.datetime.utcnow()
    fut_sym, back_sym = contract_sym(time_now)
    instruments = ["BTC-PERPETUAL", fut_sym, back_sym]
    short = ["_btc_perpetual_", "_btc_front_quarter_", "_btc_back_quarter_"]
    channels = ["quote", "trade"]
    directory = arb_algo_path + "\data\deri_data\\"
    m1_directory = arb_algo_path + "\data\deri_1min\\"

    for chan in channels:
        nicknames[chan] = {}
        headers[chan] = {}
        file_names[chan] = {}
        opened_files[chan] = {}
        for idx in range(len(instruments)):
            nicknames[chan][instruments[idx]] = short[idx] + chan

    for chan in channels:
        for inst in instruments:
            file_names[chan][inst] = directory + str(
                time_now.date()) + nicknames[chan][inst] + ".csv"
            if os.path.isfile(file_names[chan][inst]) == False:
                headers[chan][inst] = True
            else:
                headers[chan][inst] = False
            ### open all files, creating any new files names for those that dont exist
            opened_files[chan][inst] = open(file_names[chan][inst],
                                            'a+',
                                            newline='')

    for inst in instruments:
        ### create data stores ###
        #deri_ob[inst] = [] dont create as it creates itself
        old_ob[inst] = {}
        high[inst] = -np.inf
        low[inst] = np.inf
    spread_high = -np.inf
    spread_low = np.inf

    ### files just for 1min quote ###
    file_name_min = m1_directory + "week_" + str(
        time_now.isocalendar()[1]) + "_1min" + ".csv"
    headers_min = False

    save_min = False
    ws_fund = False
    heartbeat1h = False
    old_date = datetime.datetime(2008, 1, 1)
    ### Start websocket ###
    while True:
        ws_delay = False
        websocket = WebSocket('wss://www.deribit.com/ws/api/v1')
        now_time = datetime.datetime.utcnow()
        for event in persist(websocket):

            time_now = datetime.datetime.utcnow()
            ### check if file exisits (either because you run the ws for the first time, or its a new date) ####
            if time_now.date() != old_date:
                for chan in channels:
                    for inst, nickname in nicknames[chan].items():
                        file_names[chan][inst] = directory + str(
                            time_now.date()) + nickname + ".csv"
                        if os.path.isfile(file_names[chan][inst]) == False:
                            ## only creates a new file if one doenst exist
                            opened_files[chan][inst] = open(
                                file_names[chan][inst], 'a+', newline='')
                            headers[chan][inst] = True
                file_name_min = m1_directory + "week_" + str(
                    time_now.isocalendar()[1]) + "_1min" + ".csv"
                if os.path.isfile(file_name_min) == False:
                    headers_min = True

            old_date = time_now.date()

            ####################################################################################################

            if event.name == "ready":
                ############ need to code up way to auto subscribe when instruments change ##############
                #fut_sym, back_sym = contract_sym(time_now)
                ################################
                ws_args = {
                    "instrument": instruments,
                    "event": ["order_book", "trade"]
                }
                signature = generate_signature(key, secret,
                                               "/api/v1/private/subscribe",
                                               ws_args)
                print("connecting", datetime.datetime.now(), signature)
                websocket.send_json(id=5533,
                                    action="/api/v1/private/subscribe",
                                    arguments=ws_args,
                                    sig=signature)
                ws_args = {"instrument": "BTC-PERPETUAL"}
                signature = generate_signature(key, secret,
                                               "/api/v1/public/getsummary",
                                               ws_args)
                ws_funding = websocket.send_json(
                    id=62,
                    action="/api/v1/public/getsummary",
                    arguments=ws_args,
                    sig=signature)
            elif event.name == "text":
                now_time = datetime.datetime.utcnow()
                result = event.json
                #print("actual new websocket object coming through")
                ###############################################################
                ######### funding if requested ####
                if "id" in result:
                    if result["id"] == 62:
                        current_funding = result["result"]["currentFunding"]
                        funding_8h = result["result"]["funding8h"]
                ######################################
                if "notifications" in result:
                    if result["notifications"][0][
                            "message"] == "order_book_event":
                        inst = result["notifications"][0]["result"][
                            "instrument"]
                        chan = "quote"

                        deri_ob[inst] = []
                        for lev in range(
                                len(result["notifications"][0]["result"]
                                    ["bids"])):
                            ob = {}
                            ob["instrument"] = inst
                            ob["level"] = lev + 1
                            ob["bid_price"] = result["notifications"][0][
                                "result"]["bids"][lev]["price"]
                            ob["bid_size"] = result["notifications"][0][
                                "result"]["bids"][lev]["quantity"]
                            ob["ask_price"] = result["notifications"][0][
                                "result"]["asks"][lev]["price"]
                            ob["ask_size"] = result["notifications"][0][
                                "result"]["asks"][lev]["quantity"]
                            deri_ob[inst].append(ob)
                            if lev == 0:
                                if ob["ask_price"] > high[inst]:
                                    high[inst] = ob["ask_price"]
                                if ob["bid_price"] < low[inst]:
                                    low[inst] = ob["bid_price"]

                        #for m1,m2 in [("BTC-PERPETUAL",fut_sym),("BTC-PERPETUAL",back_sym),(fut_sym,back_sym)]
                        #perp = deri_ob.get("BTC-PERPETUAL",[{"bid_price":np.nan}])[0]["bid_price"]
                        #fut = deri_ob.get(fut_sym,[{"bid_price":np.nan}])[0]["bid_price"]
                        #spread = perp-fut
                        #if spread > spread_high:
                        #    spread_high = spread
                        #if spread < spread_low:
                        #    spread_low = spread

                        if inst in instruments:
                            if deri_ob[inst] != old_ob[inst]:
                                old_ob[inst] = deri_ob[inst].copy()
                                send_ob[inst] = deri_ob[inst].copy()
                                for level in send_ob[inst]:
                                    level["timestamp"] = str(
                                        pd.to_datetime(result["notifications"]
                                                       [0]["result"]["tstamp"],
                                                       unit="ms"))
                                    level["my_utc_time"] = str(now_time)
                                    if pd.to_datetime(
                                            level["my_utc_time"]
                                    ) > pd.to_datetime(
                                            level["timestamp"]
                                    ) + datetime.timedelta(seconds=60):
                                        print(
                                            "websocket is delayed, restarting",
                                            "deribit time",
                                            pd.to_datetime(level["timestamp"]),
                                            "my_time", level["my_utc_time"])
                                        ws_delay = True
                                        break
                                # breaks from websocket loop to restart
                                if ws_delay == True:
                                    break

                                write(send_ob[inst],
                                      "fast",
                                      file_names[chan][inst],
                                      opened_files[chan][inst],
                                      headers[chan][inst],
                                      rows="multi")
                                headers[chan][inst] = False

                        if now_time.second >= 30:
                            save_min = True
                        if now_time.second < 30:
                            ws_fund = True

                        if now_time.second > 45 and ws_fund == True:
                            ### quickly send a ws request and loop to collect it, should be very quick and you are back here##
                            if ws_fund == True:
                                ws_args = {"instrument": "BTC-PERPETUAL"}
                                signature = generate_signature(
                                    key, secret, "/api/v1/public/getsummary",
                                    ws_args)
                                ws_funding = websocket.send_json(
                                    id=62,
                                    action="/api/v1/public/getsummary",
                                    arguments=ws_args,
                                    sig=signature)
                                ws_fund = False

                        if now_time.second < 30 and save_min == True:
                            min_data = []
                            for inst in instruments:
                                send_ob_min = deri_ob[inst][0].copy()
                                send_ob_min["high"] = high[inst]
                                send_ob_min["low"] = low[inst]
                                high[inst] = -np.inf
                                low[inst] = np.inf
                                send_ob_min["timestamp"] = str(
                                    pd.to_datetime(result["notifications"][0]
                                                   ["result"]["tstamp"],
                                                   unit="ms"))
                                min_data.append(send_ob_min)

                            ## add in 8h funding ##
                            dummy = min_data[0]
                            dummy = {
                                key: np.nan
                                for key, value in dummy.items()
                            }
                            dummy["instrument"] = "8h_funding"
                            dummy["bid_price"] = funding_8h
                            dummy["ask_price"] = current_funding
                            dummy["timestamp"] = str(
                                pd.to_datetime(result["notifications"][0]
                                               ["result"]["tstamp"],
                                               unit="ms"))
                            min_data.append(dummy)

                            ## write
                            write(min_data,
                                  "slow",
                                  file_name_min,
                                  rows="multi")
                            headers_min = False
                            save_min = False

                        if now_time.minute == 0 and now_time.second == 0:
                            heartbeat1h = True
                        elif now_time.minute == 0 and now_time.second > 0 and heartbeat1h == True:
                            print("ws full alive", now_time)
                            heartbeat1h = False

                    if result["notifications"][0]["message"] == "trade_event":
                        inst = result["notifications"][0]["result"][0][
                            "instrument"]
                        chan = "trade"
                        trades[inst] = []
                        for trade in result["notifications"][0]["result"]:
                            trades_dict = {}
                            trades_dict["instrument"] = trade["instrument"]
                            trades_dict["qty"] = trade["quantity"]
                            trades_dict["timestamp"] = str(
                                pd.to_datetime(trade["timeStamp"], unit="ms"))
                            trades_dict["my_utc_time"] = str(now_time)
                            trades_dict["price"] = trade["price"]
                            trades_dict["direction"] = trade["direction"]

                            trades[inst].append(trades_dict)

                        write(trades[inst],
                              "fast",
                              file_names[chan][inst],
                              opened_files[chan][inst],
                              headers[chan][inst],
                              rows="multi")
                        headers[chan][inst] = False

    ###############################################################

            elif event.name == "pong":
                continue
            elif event.name == "poll":  # happens every 5 seconds
                new_fut, new_back = contract_sym(now_time)
                if (fut_sym, back_sym) != (new_fut, new_back):
                    ## break websocket so it can change contracts
                    print("breaking websocket to change contracts")
                    break
                if now_time + datetime.timedelta(
                        seconds=5) < datetime.datetime.utcnow():
                    print("websocket has been stale for 5 seconds", "ws_time",
                          now_time, "now", datetime.datetime.utcnow())
                    break
Exemple #12
0
    def poll(logintoken):

        websocket = WebSocket("wss://{apic_address}/socket{token}".format(
            apic_address=apic_address, token=logintoken))

        subscribed = False
        count = 0

        for event in persist(websocket):
            if event.name not in ['poll', 'pong']:
                log("event received " + event.name)

            count += 1

            if event.name in ['ready', 'poll', 'pong'] and (not subscribed
                                                            or count > 20):
                #2019-01-10T00:14:24
                from_time = datetime.fromtimestamp(
                    int(not_connected[apic_address])).strftime(
                        '%Y-%m-%dT%H:%M:%S')
                #from_time = datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%dT%H:%M:%S')

                log("subscribing from %s" % (from_time))
                r = requests.get(
                    'https://' + apic_address +
                    "/api/node/class/aaaModLR.json?subscription=yes&page=0&page-size=10000&query-target-filter=and(gt(aaaModLR.created,\"%s\"))"
                    % (from_time),
                    headers={
                        'Content-type': 'application/json',
                        'Cookie': "APIC-cookie=%s" % (logintoken)
                    },
                    verify=False,
                    proxies=proxies)
                log("subscribe request returned (%s)" % (r.status_code))
                result = json.loads(r.text)
                #dump previus events
                for aci_event in result.setdefault("imdata", []):
                    if "aaaModLR" in aci_event:
                        message = aci_event["aaaModLR"]["attributes"]
                        dump_message(message)

                count = 0
                if r.ok:
                    subscribed = True
                    log("subscribed")
                    #we won't ever need events before this
                    not_connected[apic_address] = time.time()
                else:
                    log(r.text)
                    result = json.loads(r.text)
                    subscribed = False
                    log("not subscribed (request was not ok)")
                    if (re.match(
                            r'Token was invalid', result["imdata"][0]["error"]
                        ["attributes"]["text"])):
                        log("Token was invalid; reconnecting")
                        break

            if event.name == 'text':
                #websocket.send_text(event.text)
                aci_event = json.loads(event.text)
                message = aci_event["imdata"][0]["aaaModLR"]["attributes"]
                dump_message(message)
                #we won't ever need events before this
                not_connected[apic_address] = time.time()

        websocket.close()
        init()
Exemple #13
0
import json
import re
from lomond.persist import persist
from HQApi import HQApi, HQWebSocket

bearer = "Bearer"
api = HQApi(bearer)
ws = HQWebSocket(api, demo=True, log_new_methods=True)
websocket = ws.get()

for msg in persist(websocket):
    if msg.name == "text":
        data = json.loads(re.sub(r"[\x00-\x1f\x7f-\x9f]", "", msg.text))
        print(data)
Exemple #14
0
 def run(self):
     for msg in persist(self.new.ws):
         if msg.name == "text":
             data = json.loads(re.sub(r"[\x00-\x1f\x7f-\x9f]", "",
                                      msg.text))
             self.new.call({"type": data["type"], "data": data})
        "change": get_change_flag(data_array[5]),
        "sequence": int(data_array[6]),
        "price": float(data_array[7]),
        "quantity": float(data_array[8])
    }
    return data_obj

cryptocompare_ws = WebSocket('wss://streaming.cryptocompare.com')
subs = {
    "action": "SubAdd",
    "subs": ["8~bitfinex~BTC~USD"],
    "api_key": "YOUR-API-KEY",
    "format": "streamer"
}

for event in persist(cryptocompare_ws):
    if event.name == "ready":
        print('ready')
        cryptocompare_ws.send_json(subs)
    if event.name == "text":
        print(event.text)
        messages = event.text.split("|")
        messages = messages[:-1] #Last element is empty string
        for message in messages:
            if message == "999~HEARTBEAT|":
                print(message)
            elif message.split("~")[0] == "9":
                print(parse_snapshot(message))
                continue
            else:
                print(parse_level_2(message))
Exemple #16
0
pen = servomotor.ServoPen()
eyes = eyematrix.RobotEyes(i2c, 0x70, 0x74)

# Create the robot
robot = Turtle(axle, pen, eyes)

# Set up the WebSocket connection
ws = JSONRPCWebSocket("wss://arch7210-fall2019.coditect.com/pablo")
ws.set_basic_auth("pablo", "*************")

# Counter for eyes
blink_count = 0
tired_count = 0
angry_count = 0
try:
    for event in persist(ws):
        request = ws.get_request(event)
        print(event)

        if request is not None:
            blink_count = 0
            tired_count += 1
            angry_count = 0

            if request == False or request.exec(robot, ws) == False:
                angry_count += 1
                print(angry_count)

                if angry_count > 5:
                    eyes.angry()
Exemple #17
0
    def run(self):
        cnt_deadman = 0  # recommended is 15 seconds, but 30 should do for dev
        cnt2 = 0  # ghetto reducing spamm

        subs_args = build_requests(self.subs, self.symbol_list)
        ws = self._prep_connection()

        for event in persist(ws):

            if isinstance(event, events.Rejected):
                self.logger.warning(str(event.response))
                self.warn(event.response)

            if isinstance(event, events.BackOff):
                self.warn("backing off for {} s".format(str(event.delay)))
                sleep(event.delay)
                ws.close()
                self.run()  # regen nonce and stuff

            if event.name == "ready":
                # send deadman switch
                ws.send_json({"op": "cancelAllAfter", "args": 60000})
                self._subscribe(ws=ws)

            if isinstance(event, events.Text):
                msg = (json.loads(event.text))
                # print(msg)
                # now we get the limit value from welcome message (or rate limit, later)#TODO MED test it rough!!!
                if 'info' in msg.keys() and 'limit' in msg.keys():
                    self.rem_limit = msg['limit']
                # we check and ack subscriptions
                if 'success' in msg.keys() and 'subscribe' in msg.keys():
                    try:
                        subs_args.remove(msg['subscribe'])
                    except:
                        self.warn(
                            "that's weird : {} was not to be sub'd".format(
                                msg['subscribe']))
                    if len(subs_args) == 0:
                        self.debug("all subs good to go")

                # # now we deal with L2
                if 'table' in msg.keys() and msg['table'] == 'orderBookL2_25':

                    self.book.getmsg(msg)
                    if self.book.partial:  # waiting for the order book
                        # self.toy_mm()
                        self.agent.on_l2()

                # # orders
                if 'table' in msg.keys() and msg['table'] == 'order':
                    # print(msg)
                    self.ord_keep.ws_update(
                        msg)  # TODO this needs to be threadsafe

                if 'table' in msg.keys() and msg['table'] in [
                        'trade', 'margin'
                ]:
                    self.message_data_updater(msg, event.received_time)
                    if msg['table'] == 'trade':
                        # we calculate state (trade ratio might change as a result)
                        self.agent.on_trade()

            if isinstance(event, events.Poll):
                cnt_deadman += 1
                print(self.ord_keep.exec_report())
                if cnt_deadman == self.deadman_renew:
                    # send deadman switch
                    self.debug("deadman re-activate")
                    ws.send_json({"op": "cancelAllAfter", "args": 60000})
                    cnt_deadman = 0

                try:
                    self.debug(self.book.bbo(lvl=5))
                except:
                    pass
                self.debug(self.ord_keep.ord_report())

                print("current inventory: {}".format(
                    sum([x['orderQty'] for x in self.ord_keep.transactions])))
                avg_price = avg_price_inv(self.symbol_list[0],
                                          self.ord_keep.transactions)
                if avg_price:
                    print("holding at avg price {}".format(str(avg_price)))
Exemple #18
0
    def _run_socketio_thread(self):
        self._running = True

        # Back off for Error restarting
        min_wait = 5
        max_wait = 30

        retries = 0

        random_wait = max_wait - min_wait

        while self._running is True:
            _LOGGER.info("Attempting to connect to SocketIO server...")

            try:
                retries += 1

                self._handle_event(STARTED, None)

                self._websocket = WebSocket(self._url)
                self._exit_event = threading.Event()

                if self._cookie:
                    self._websocket.add_header(COOKIE_HEADER, self._cookie)

                if self._origin:
                    self._websocket.add_header(ORIGIN_HEADER, self._origin)

                for event in persist(self._websocket,
                                     ping_rate=0,
                                     poll=5.0,
                                     exit_event=self._exit_event):
                    if isinstance(event, events.Connected):
                        retries = 0
                        self._on_websocket_connected(event)
                    elif isinstance(event, events.Disconnected):
                        self._on_websocket_disconnected(event)
                    elif isinstance(event, events.Text):
                        self._on_websocket_text(event)
                    elif isinstance(event, events.Poll):
                        self._on_websocket_poll(event)
                    elif isinstance(event, events.BackOff):
                        self._on_websocket_backoff(event)

                    if self._running is False:
                        self._websocket.close()

            except SocketIOException as exc:
                _LOGGER.warning("SocketIO Error: %s", exc.details)

            except WebSocketError as exc:
                _LOGGER.warning("Websocket Error: %s", exc)

            if self._running:
                wait_for = min_wait + random() * min(random_wait, 2**retries)

                _LOGGER.info("Waiting %f seconds before reconnecting...",
                             wait_for)

                if self._exit_event.wait(wait_for):
                    break

        self._handle_event(STOPPED, None)
Exemple #19
0
 def run(self):
     for msg in persist(self.new.ws):
         if msg.name == "text":
             data = json.loads(msg.text)
             self.new.call({"type": data["type"], "data": data})
Exemple #20
0
def constellation(token_info, f_refresh):
    ws = WebSocket('wss://constellation.mixer.com')
    ws.add_header(str.encode('authorization'),
                  str.encode('Bearer {}'.format(token_info["access_token"])))
    ws.add_header(str.encode('client-id'), str.encode(token_info["client_id"]))
    ws.add_header(str.encode('x-is-bot'), str.encode('true'))

    while 1:
        for event in persist(ws, ping_rate=30, poll=5, exit_event=f_refresh):

            if event.name == "ready":
                Method = {
                    'type': 'method',
                    'method': 'livesubscribe',
                    'params': {
                        'events': [
                            'channel:{}:followed'.format(
                                token_info["channel_id"]),
                            'channel:{}:hosted'.format(
                                token_info["channel_id"]),
                            'channel:{}:subscribed'.format(
                                token_info["channel_id"]),
                            'channel:{}:resubShared'.format(
                                token_info["channel_id"]),
                            #                    'channel:{}:update'.format(token_info["channel_id"]),
                            'channel:{}:subscriptionGifted'.format(
                                token_info["channel_id"]),
                            'channel:{}:skill'.format(
                                token_info["channel_id"]),
                        ]
                    },
                    'id': token_info["nonce"]
                }
                ws.send_json(Method)

            elif event.name == "text":
                print(event.json)
                if event.json['type'] == 'reply':
                    print('The Server replies to you')
                    if event.json['error'] != None:
                        print('Something to see here')
                        print(event.json['error'])
                        sys.exit()
                    elif event.json['id'] != token_info["nonce"]:
                        print('Nonce Mismatch')
                        sys.exit()

                if event.json['type'] == 'event':
                    if event.json['event'] == 'hello':
                        print(' The Server greets you back')

                    elif event.json['event'] == 'live':
                        print('Something happened')
                        if event.json['data'][
                                'channel'] == 'channel:{}:followed'.format(
                                    token_info["channel_id"]):
                            if event.json['data']['payload'][
                                    'following'] == True:
                                print('Someone is following you')
                                username = event.json['data']['payload'][
                                    'user']['username']
                                print("Username: {}".format(username))
                                avatar_url = event.json['data']['payload'][
                                    'user']['avatarUrl']
                                sparks = event.json['data']['payload']['user'][
                                    'sparks']
                                print("Sparks: {}".format(sparks))
                            if event.json['data']['payload'][
                                    'following'] == False:
                                print('Someone stopped following you')
                                username = event.json['data']['payload'][
                                    'user']['username']
                                print(username)

                        elif event.json['data'][
                                'channel'] == 'channel:{}:hosted'.format(
                                    token_info["channel_id"]):
                            print('Someone is hosting you')

                        elif event.json['data'][
                                'channel'] == 'channel:{}:subscribed'.format(
                                    token_info["channel_id"]):
                            print('Someone has subscribed to you')

                        elif event.json['data'][
                                'channel'] == 'channel:{}:resubShared'.format(
                                    token_info["channel_id"]):
                            print('Someone has resubscribed to you')

                        elif event.json['data'][
                                'channel'] == 'channel:{}:subscriptionGifted'.format(
                                    token_info["channel_id"]):
                            print('Someone has gifted a subscription to you')

                        elif event.json['data'][
                                'channel'] == 'channel:{}:skill'.format(
                                    token_info["channel_id"]):
                            print('Someone has used a skill on you')
            elif event.name == 'pong' or event.name == 'ping' or event.name == 'poll':
                continue
            else:
                continue
                print(event.name)
        if f_refresh.is_set():
            print("Closing Websocket")
            ws.close()
            f_refresh.clear()
            continue
Exemple #21
0
from lomond import WebSocket
from lomond.persist import persist
from cloud_service import CloudService
from datetime import datetime
from voice_codes_constants import *
import simplejson as json
from configuration_service import ConfigurationService
from subprocess import Popen, PIPE
import time
import requests

websocket = WebSocket('http://116.203.129.161:80/chat')
cloud_service = CloudService()
configuration_service = ConfigurationService.getInstance()

for event in persist(websocket):
    if event.name == "ready":
        print("ready")
    elif event.name == "text":
        text = event.text
        print(text)
        if (text.startswith("__SPEAK__")):
            text = text.replace("__SPEAK__", "")
            parts = text.split("_#_#_")
            cloud_service.speak(parts[1], parts[0])
            configuration_service.set_vision_language(parts[0], False)
            now = datetime.now()
            date_string = now.strftime("%d/%m/%Y %H:%M:%S")
            with open("remote_speech_log.txt", "a") as myfile:
                myfile.write(date_string + ": " + event.text + "\r\n")
                myfile.close()
Exemple #22
0
import json
import re

from lomond.persist import persist

from HQApi import HQApi, HQWebSocket

bearer = "Bearer"
api = HQApi(bearer)
ws = HQWebSocket(api)
websocket = ws.get()

for msg in persist(websocket.connect):
    if msg.name == "text":
        data = json.loads(re.sub(r"[\x00-\x1f\x7f-\x9f]", "", msg.text))
        if data["type"] != "interaction":
            print(str(data))
Exemple #23
0
        msgsec = 0.2
        rsec = 5
    instruments =  json_data['instruments']
    botname =  json_data['botname']
    version =  json_data['version']
    log =  json_data['log']
    trade =  json_data['trade']
    nonce =  json_data['nonce']
    json_file.close()


print("T: " + str(int(round(time.time() * 1000))) + " - Configuration successfully read, starting strategy: " + botname + " " + version + "...")

websocket = WebSocket(server)

for event in persist(websocket, poll=msgsec):
    
    #### On Connect handler ####
    if event.name == "ready":
      
      print("T: " + str(int(round(time.time() * 1000))) + " - Bot Connecting....")
      datapool = {}
      websocket.send_json({"jsonrpc":"2.0","id":0,"method":"public/auth","params":{"grant_type":"client_credentials","client_id":user,"client_secret":password,"nonce": nonce}})
      websocket.send_json({"jsonrpc":"2.0","id":1,"method":"public/disable_heartbeat","params":{}})
      websocket.send_json({"jsonrpc":"2.0","id":2,"method":"public/hello","params":{"client_name":botname,"client_version":version}})
      websocket.send_json({"jsonrpc":"2.0","method":"public/subscribe","id":3,"params":{"channels": ["platform_state"]}})
      authend = time.time()
      poller = 0
      botready = 0
      logready = 0
      logheader = 0