Ejemplo n.º 1
0
	def on_notification(self, conn, event, respond_to):
		"""Handle notification messages from Twitch, sending the message up to the web"""
		log.info("Notification: %s" % event.arguments[0])
		notifyparams = {
			'apipass': config['apipass'],
			'message': event.arguments[0],
			'eventtime': time.time(),
		}
		if irc.client.is_channel(event.target):
			notifyparams['channel'] = event.target[1:]
		subscribe_match = self.re_subscription.match(event.arguments[0])
		if subscribe_match:
			notifyparams['subuser'] = subscribe_match.group(1)
			try:
				channel_info = twitch.get_info(subscribe_match.group(1))
			except:
				pass
			else:
				if channel_info.get('logo'):
					notifyparams['avatar'] = channel_info['logo']
			# have to get this in a roundabout way as datetime.date.today doesn't take a timezone argument
			today = datetime.datetime.now(config['timezone']).date().toordinal()
			if today != storage.data.get("storm",{}).get("date"):
				storage.data["storm"] = {
					"date": today,
					"count": 0,
				}
			storage.data["storm"]["count"] += 1
			storage.save()
			conn.privmsg(respond_to, "lrrSPOT Thanks for subscribing, %s! (Today's storm count: %d)" % (notifyparams['subuser'], storage.data["storm"]["count"]))

			self.subs.add(subscribe_match.group(1).lower())
			storage.data['subs'] = list(self.subs)
			storage.save()
		utils.api_request('notifications/newmessage', notifyparams, 'POST')
Ejemplo n.º 2
0
def get_user_info(username):
    method = "user.getInfo"
    params = {'user': username}
    result = api_request(method, params)
    if result is None or 'user' not in result:
        return None
    return result['user']
Ejemplo n.º 3
0
def fetch_user_friends(username, limit=30):
    friends_dict = {}
    page = 1

    # make a request to get friends info
    method = "user.getFriends"
    params = {'user': username, 'limit': limit}

    while 1:
        params['page'] = page
        print Color.emphasise('--- user=%s friends page=%d ---' % (username, page))
        result = api_request(method, params=params)
        if result is not None and 'friends' in result:
            obj = result['friends']
        else:
            return None
        if page == 1 and 'user' not in obj:  # no friends
            return friends_dict
        else:
            attr = obj['@attr']
            last_page = int(attr['totalPages'])
            if isinstance(obj['user'], dict):
                u = obj['user']
                friends_dict[u['name']] = u
            else:
                for u in obj['user']:
                    friends_dict[u['name']] = u

            page += 1
            if page > last_page:
                # just return the result
                return friends_dict
Ejemplo n.º 4
0
    def get_page(self, page):
        params = {"limit": FriendHistory.per_page, "page": page, 'extend': 1}
        params.update(self.params)
        r = api_request(FriendHistory.METHOD, params)
        if r is None or "recenttracks" not in r:
            return None

        if '@attr' in r["recenttracks"]:
            meta = r["recenttracks"]["@attr"]
        else:
            meta = r["recenttracks"]

        if int(meta['page']) != page:
            # so api error
            raise RuntimeError

        if "track" in r["recenttracks"]:
            result = r["recenttracks"]["track"]
            if isinstance(result, dict):  # only one item
                result = [result]
        else:
            result = None

        if result is None:
            self.log_this(page)
        return result
Ejemplo n.º 5
0
 def _api_request(self, path='', method='get', \
     data=None, params={}):
     api_url = 'http://{0}:{1}'.format(
         self.settings.get('api', {}).get('host'),
         self.settings.get('api', {}).get('port'))
     return utils.api_request(host=api_url,
                              path=path,
                              method=method,
                              data=data,
                              params=params)
Ejemplo n.º 6
0
def sell(branch, isdn, amount):
    result = None

    try:
        xml = (
            '<request><branch>%(branch)s</branch><customer system="ISDN">%(isdn)s</customer><point>%(point)s</point><smsPrefix>my.ubedn.mn</smsPrefix><smsSuffix>UBEDN</smsSuffix><product>tsaxilgaanii tulbur</product><productType></productType><description>tsaxilgaanii tulbur tulugdsun.</description></request>'
            % {"branch": branch, "isdn": isdn, "point": amount}
        )

        result = api_request("sell", xml)
    except Exception as ex:
        logging.error("[candy api] [sell] error: %s" % ex)

    return result
Ejemplo n.º 7
0
def friend_like(track, artist, friend):
    params = {'username': friend, 'track': track, 'artist': artist}
    service = 'track.getInfo'
    result = api_request(service, params)

    try:
        track = result['track']
        if 'userplaycount' not in track:
            return (0, 0)
        userplaycount = track['userplaycount']
        userloved = track['userloved']
        return (userplaycount, userloved)
    except (TypeError, KeyError):
        print "--- get wired result in friend_like (%s, %s, %s) ---" % (
                track, artist, friend)
        return None
Ejemplo n.º 8
0
def hello_world():
    response = {}
    if request.method == 'POST':
        type_request = request.form['type']
        response_raw = api_request(
            type_request,
            params_dict(lat=request.form['latitude'],
                        lon=request.form['longitude'],
                        hours=request.form['hours']))
        if response_raw.status_code != 200:
            response['success'] = False
            response['detail'] = "There was an error contacting the API"
        else:
            response = pack_response(response_raw.json())
            response['title'] = type_request[0].upper() + type_request[1:]
    return render_template('index.html', **response)
Ejemplo n.º 9
0
def get_balance(isdn):
    result = None

    try:
        xml = "<request><customer>%(isdn)s</customer><customer.system>ISDN</customer.system></request>" % {"isdn": isdn}

        result = api_request("customer", xml)

        if result and not result.has_error:
            result.balance = None
            root = xml_et.fromstring(result.body)
            result.balance = int(float(root.find("balance").text))
    except Exception as ex:
        logging.error("[candy api] [get balance] error: %s" % ex)

    return result
Ejemplo n.º 10
0
 def get_count(self):
     params = {"limit": 1, "page": 1}
     params.update(self.params)
     result = api_request(self.method, params)
     if result is None:
         return 0
     if "status" in result and result["status"] == 'ok':
         gevent.sleep(2)
         return self.get_count()
     elif 'recenttracks' in result:
         if '@attr' in result["recenttracks"]:
             meta = result["recenttracks"]["@attr"]
         else:
             meta = result["recenttracks"]
         return int(meta["total"].strip())
     else:
         return 0
Ejemplo n.º 11
0
def get_user_friends(username, limit=30, page=0):
    friends_dict = {}
    fetch_all = False

    if page == 0:
        page = 1
        fetch_all = True

    # make a request to get friends info
    method = "user.getFriends"
    params = {'user': username, 'limit': limit}

    while True:
        params['page'] = page
        if DEBUG:
            print '--- user=%s friends page=%d ---' % (username, page)
        result = api_request(method, params=params)
        if result is not None and 'friends' in result:
            obj = result['friends']
        else:
            return None
        if page == 1 and 'user' not in obj:  # no friends
            return (friends_dict, 0)
        else:
            attr = obj['@attr']
            total_friends = int(attr['total'])
            last_page = int(attr['totalPages'])
            if total_friends > 200:
                # pass this user
                # too many friends
                return None
            if isinstance(obj['user'], dict):
                u = obj['user']
                friends_dict[u['name']] = u
            else:
                for u in obj['user']:
                    friends_dict[u['name']] = u

            page += 1
            if len(friends_dict) > 1000 or not fetch_all or page > last_page:
                # just return the result
                return (friends_dict, total_friends)
                break
Ejemplo n.º 12
0
def sell_confirm(branch, isdn, tan):
    result = None

    try:
        xml = (
            '<request><branch>%(branch)s</branch><customer system="ISDN">%(isdn)s</customer><tancode>%(tan)s</tancode></request>'
            % {"branch": branch, "isdn": isdn, "tan": tan}
        )

        result = api_request("sell/confirm", xml)

        if result and not result.has_error:
            result.trans_id = None
            root = xml_et.fromstring(result.body)
            result.trans_id = root.find("transactionId").text
    except Exception as ex:
        logging.error("[candy api] [sell confirm] error: %s" % ex)

    return result
Ejemplo n.º 13
0
def get_user_tags(username):
    tags = []
    method = "user.getTopTags"
    params = {'user': username}
    result = api_request(method, params=params)
    if result is None:
        print Color.fail("----failed to get tags for %s----" % username)
    elif 'toptags' in result:
        result = result['toptags']
        if 'tag' in result:
            elem = result['tag']
            if isinstance(elem, list):
                for tag in elem:
                    tags.append((tag['name'], int(tag['count'])))
            else: # single dict
                tags.append((elem['name'], int(elem['count'])))
        else: # no tags
            print Color.emphasise("---- %s have no tags----" % username)

    return tags
Ejemplo n.º 14
0
    def get_page(self, page):
        params = {"limit": self.per_page, "page": page, 'extend': 1}
        params.update(self.params)
        r = api_request(self.method, params)
        if r is None or "recenttracks" not in r:
            return None

        if '@attr' in r["recenttracks"]:
            meta = r["recenttracks"]["@attr"]
        else:
            meta = r["recenttracks"]
        if int(meta['page']) != page:
            raise RuntimeError

        if "track" in r["recenttracks"]:
            result = r["recenttracks"]["track"]
            if isinstance(result, dict):  # only one item
                result = [result]
        else:
            result = None
        return result
Ejemplo n.º 15
0
def filter_target_info(user_info):
    gender = user_info['gender'].strip()
    age = user_info['age'].strip()
    name = user_info['name'].strip()
    if gender == "" or gender == "n":
        return False
    if age == "":
        return False

    # private listen or no history
    params = {'user': name, 'limit': 1, 'page': 1}
    method = "user.getRecentTracks"
    result = api_request(method, params)
    if result is None:
        return False

    # friends too much or something in friends fetching error
    result = get_user_friends(name, limit=1, page=1)
    if result is None:
        return False

    return True
Ejemplo n.º 16
0
def get_tasteometer(user1, user2):
    artists = []
    method = 'tasteometer.compare'
    params = {'type1': 'user', 'type2': 'user', 'value1': user1, 'value2': user2, 'limit': 10}
    result = api_request(method, params=params)
    score = 0.0
    if result is None:
        print Color.fail("----failed to compare %s and %s----" % (user1, user2))
    elif 'comparison' in result and 'result' in result['comparison']:
        result = result['comparison']['result']
        score = float(result['score'])
        arts = result['artists']
        if 'artist' in arts:
            elem = arts['artist']
            if isinstance(elem, list):
                for art in elem:
                    artists.append(art['name'])
            else: # single dict
                artists.append(elem['name'])
        else: #no common artist
            print Color.emphasise("---- %s and %s have common artist ----" % (user1, user2))

    return (score, artists)
Ejemplo n.º 17
0
import config
import utils

from_count = 1
username = input("Please input your Codeforces username:"******"user.status", data)

    calc_problem = []
    rank = 0
    contest_rank = 0

    if len(data['result']) == 0:
        break
    for i in data['result']:
        if i['verdict'] == 'OK':
            if i['problem']['name'] not in calc_problem:
                contest_request_data = {'contestId': i['contestId']}
                contest_data = utils.api_request("contest.standings", contest_request_data)
                contest_name = contest_data["result"]["contest"]["name"]
                div = 0
                if contest_name.find("Div. 1") != -1:
                    div = 1

                if contest_name.find("Div. 2") != -1:
                    div = 2

                if contest_name.find("Div. 3") != -1:
                    div = 3
Ejemplo n.º 18
0
 def _api_request(self, path='', method='get', \
     data=None, params={}):
     api_url = 'http://{0}:{1}'.format(self.settings.get('api', {}).get('host'),
         self.settings.get('api', {}).get('port'))
     return utils.api_request(host=api_url, path=path, method=method,
         data=data, params=params)
Ejemplo n.º 19
0
#--------------------------------------#

log.write('Loading Top-1000 artists...', skip_line=1)

''' Request 10 pages, with 100 artists each.
    The maximum allowd by the API is 1000.
'''
params['method'] = 'chart.getTopArtists'
params['limit']  = '100'

dataset_len = 0
cur = dbs.cursor()
for pg_num in xrange(1,11):
    params['page'] = str(pg_num)

    resp = utils.api_request( root_url, params )

    recnum = int(resp['artists']['@attr']['perPage'])
    log.write('Received pg# ' + str(resp['artists']['@attr']['page']) + ' with ' + str(recnum) + ' records.')
    dataset_len += recnum

    #-- generate and load record tuples
    cur.executemany("INSERT INTO artists VALUES (?,?,?)",
                    ((e['name'],int(e['listeners']),int(e['playcount'])) for e in resp['artists']['artist']))

    #-- pause 1.5 sec to avoid API request overload
    time.sleep(1.5)
cur.close()
dbs.commit()

log.write('Loaded %s records.'%fmt('%20d',dataset_len,True).strip())
Ejemplo n.º 20
0
 def __init__(self):
     self.api_data = api_request(gf_api_url)