Exemplo n.º 1
0
        def go():
            sub_params = {'type': 'subscribe', 'product_ids': self.products}
            ws = WebSocket(gdax_ws_endpoint)

            for event in ws.connect():
                if event.name == 'poll':
                    ws.send_text(json.dumps(sub_params))
                elif event.name == 'text':

                    # print(event.text)

                    try:
                        msg = json.loads(event.text)
                        print(msg['price'])
                        print(msg['type'])
                    except:
                        print('couldnt parse msg')
Exemplo n.º 2
0
msgs['allclans'] = json.dumps({"start":0,"type":"page","page":"clans"})

clan = None
treas = None
members = None
donations = None
profiles = dict()
otherclans = [None, None, None]

battles = 0
for event in ws:
    #print(event)
    try:
        if isinstance(event, events.Ready):
            print("Requesting clan profile")
            ws.send_text(msgs['clan_profile'])

        if isinstance(event, events.Text):
            j = json.loads(event.text)[0]
            if 'type' in j:
                if (j['type'] == 'page') and (j['page'] == 'clan_view'):
                    print("Processing clan profile")
                    clan = j['result']
                    sleep(1)
                    print("Requesting clan treasury")
                    ws.send_text(msgs['clan_treasury'].replace('%%', str(clan['id'])))

        if isinstance(event, events.Text):
            j = json.loads(event.text)[0]
            if 'type' in j:
                if (j['type'] == 'page') and (j['page'] == 'clan_treasury'):
Exemplo n.º 3
0
class client():
    def __init__(self, connect=True, proxies=None):

        self.id = ""
        self.owner = ""
        self.ws = None
        self.eventID = 1

        self.reconnect_url = ""

        try:
            fp = open("id.cfg", "r")
            self.id = fp.readline()
            self.owner = fp.readline()
            print("id:" + self.id)
            print("owner:" + self.owner)
            fp.close()
        except IOError:
            print("unable to read id.cfg")
            quit()

        try:
            fp = open("token.dat", "rb")
            self.token = fp.readline()
            fp.close()
        except IOError:
            print("unable to read token.dat")
            quit()

        try:
            fp = open("acknowledged.dat", "rb")
            self.acknowledged = pickle.load(fp)
            fp.close()
        except IOError:
            self.acknowledged = []

    def webApiSend(self, contentType, apiMethod, dat=None):

        if dat != None:
            if contentType == "application/json":
                dat = json.dumps(dat).encode('utf8')
            else:
                dat = urllib.parse.urlencode(dat).encode("utf-8")

        header = {"Content-type": contentType, "Authorization": self.token}

        req = urllib.request.Request(url='https://slack.com/api/' + apiMethod,
                                     headers=header,
                                     method='POST',
                                     data=dat)
        res = urllib.request.urlopen(req, timeout=5)

        return res.read().decode('utf-8')

    def getRTM(self):
        return self.webApiSend("application/x-www-form-urlencoded",
                               "rtm.connect")

    def acknowledge(self, channel, user):
        self.sendMeMessage(channel, "acknowledges your presence.")

        if user in self.acknowledged:
            return

        self.acknowledged.append(user)
        fp = open("acknowledged.dat", "wb")
        pickle.dump(
            self.acknowledged,
            fp)  #to save to file and load on startup to make it persistant
        fp.close()

    def connect(self):
        rtm = json.loads(self.getRTM())

        self.id = rtm["self"]["id"]
        self.ws = WebSocket(rtm["url"])

    def sendMeMessage(self, channel, msg):
        dat = {"channel": channel, "text": msg}
        self.webApiSend("application/x-www-form-urlencoded", "chat.meMessage",
                        dat)

    def sendMessage(self, channel, msg):
        send = '{"id": ' + str(
            self.eventID
        ) + ', "type": "message", "channel": "' + channel + '", "text": "' + msg + '"}'
        self.ws.send_text(send)
        self.eventID = self.eventID + 1

    def messageHandler(self, channel, msg, elevated):

        if not elevated:
            if (msg == "banana"):
                self.sendMessage(
                    channel,
                    "mew mew mew mew mew mew mew. Thats you. Thats what you sound like. deplorable."
                )

            #elevated permissions needed for anything below this point
            return

        if (msg == "banana"):
            self.sendMessage(channel, "orange ya glad I didnt say banana?")

        if (msg == "laputan machine"):
            self.sendMessage(channel, "judas.")
            quit()

    def mainLoop(self):

        for event in self.ws:
            if event.name == "text":
                msg = json.loads(event.text)

                print(msg)

                if "type" in msg:
                    if "channel" in msg:
                        channel = msg["channel"]
                        print("")
                        print(channel)
                        print("")

                    #going to actually need to use this at some point
                    if msg["type"] == "reconnect_url":
                        self.reconnect_url = msg["url"]

                    if msg["type"] == "team_join":
                        self.sendMessage(channel,
                                         "You There. Kneel Before Zod.")

                    if msg["type"] == "message":
                        if "subtype" in msg:
                            if msg["subtype"] == "me_message":
                                if msg["text"] == "kneels":
                                    self.acknowledge(channel, msg["user"])

                    #only acknowledged users past this point
                        if msg["user"] not in self.acknowledged:
                            continue

                        #@ message to zod
                        if msg["text"][:12] == "<@" + self.id + ">":
                            self.messageHandler(channel, msg["text"][13:],
                                                msg["user"] == self.owner)
Exemplo n.º 4
0
msgs['clan_members'] = json.dumps({'clan': '%%', 'type': 'page', 'page': 'clan_members'})
msgs['profile'] = json.dumps({'type': 'page', 'page': 'profile', 'username': '******'})

clans = list()
profiles = dict()
listsRequested = 0
entriesExpected = 0

battles = 0
for event in ws:
    #print(event)
    try:
        if isinstance(event, events.Ready):
            for rival in settings['rivals']:
                print("Requesting clan profile for clan " + rival['name'])
                ws.send_text(msgs['clan_profile'].replace('%%', str(rival['id'])))
                sleep(1)

        if isinstance(event, events.Text):
            j = json.loads(event.text)[0]
            if 'type' in j:
                if (j['type'] == 'page') and (j['page'] == 'clan_view'):
                    print("Processing clan profile")
                    node = dict()
                    node['id'] = j['result']['id']
                    node['xp'] = j['result']['experience']
                    node['level'] = j['result']['level']
                    clans.append(node)
                    print("Requesting membership list for clan " + j['result']['name'])
                    ws.send_text(msgs['clan_members'].replace('%%', str(node['id'])))
                    listsRequested += 1
Exemplo n.º 5
0
class RosbridgeSuitComponent(BaseComponent):
    def __init__(self):
        super(RosbridgeSuitComponent, self).__init__()
        self.is_setup = False
        self.connected = False
        self.running = True
        self.pub_callbacks = {}
        self.srv_callbacks = {}
        self.thread_stopped = False
        self.q = queue.Queue()

    def setup(self):
        if self.is_setup:
            print('setup is done earlier, return')
            return
        command = 'roslaunch rosbridge_server rosbridge_websocket.launch'
        self.bridge_proc_id = external_command_pool.start_command(command)
        self.ws = WebSocket('ws://localhost:9090')
        self.monitor_t = Thread(target=self.monitor)
        self.monitor_t.start()
        self.is_setup = True

    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)

    def shutdown(self):
        self.running = False
        while not self.thread_stopped:
            time.sleep(1)
        external_command_pool.end_command(self.bridge_proc_id)

    def send_req(self, req):
        while not self.connected:
            time.sleep(1)
        self.ws.send_text(json.dumps(req))

    def subscribe(self, topic, type, callback):
        req = {'op': 'subscribe', 'topic': topic, 'type': type}
        self.pub_callbacks[topic] = callback
        self.send_req(req)

    def unsubscribe(self, topic):
        req = {'op': 'unsubscribe', 'topic': topic}
        del self.pub_callbacks[topic]
        self.send_req(req)

    def publish(self, topic, msg):
        req = {'op': 'publish', 'topic': topic, 'msg': msg}
        self.send_req(req)

    def call_service(self, service, callback, args=[]):
        req = {'op': 'call_service', 'service': service, 'args': args}
        self.srv_callbacks[service] = callback
        self.send_req(req)

    def respond_service(self, service, result):
        req = {'op': 'service_response', 'service': service, 'result': result}
        self.send_req(req)

    def advertise(self, topic, type):
        req = {'op': 'advertise', 'topic': topic, 'type': type}
        self.send_req(req)

    def advertise_service(self, type, service):
        req = {'op': 'advertise_service', 'type': type, 'service': service}
        self.send_req(req)

    def unadvertise(self, topic):
        req = {'op': 'unadvertise', 'topic': topic}
        self.send_req(req)

    def unadvertise_service(self, service):
        req = {'op': 'unadvertise_service', 'service': service}
        self.send_req(req)
Exemplo n.º 6
0
    "page_num": "%%",
    "q": 0,
    "ll": 0,
    "hl": 0,
    "st": "all"
})

resources = dict()

battles = 0
for event in ws:
    #print(event)
    try:
        if isinstance(event, events.Ready):
            print("Requesting crystals (page 0)")
            ws.send_text(msgs['crystals'].replace('"%%"', '0'))

        if isinstance(event, events.Text):
            j = json.loads(event.text)[0]
            if 'type' in j:
                if (j['type'] == 'page') and (j['page'] == 'market'):
                    rec = j['result']
                    pageno = rec['page']
                    resource = rec['cn'].lower()
                    print("Processing {} (page {})".format(resource, pageno))
                    if resource not in resources:
                        resources[resource] = dict()
                    #assert len(rec['l']) > 0
                    for l in rec['l']:
                        resources[resource][l['tid']] = l
                    sleep(1)
Exemplo n.º 7
0
from lomond.websocket import WebSocket
import json
import requests

gdax_http_endpoint = 'https://api.gdax.com'
gdax_ws_endpoint = 'wss://ws-feed.gdax.com'

subscribe_msg = {"type": "subscribe", "product_ids": ["LTC-USD"]}

# ob_request='/products/BTC-USD/book?level=3'


def getProductOrderBook(self, json=None, level=3, product=''):
    r = requests.get(self.url + '/products/%s/book?level=%s' %
                     (product, str(level)))
    return r.json()


ws = WebSocket(gdax_ws_endpoint)
for event in ws.connect():
    # print(event)
    if event.name == 'poll':
        ws.send_text(json.dumps(subscribe_msg))
    elif event.name == 'text':
        print(event.text)