def itunes_api(self):
        for country in self._countries:
            request_params = {'term': self._name,
                              'entity': self._entity,
                              'country': country}
            try:
                request = requests.get("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch",
                                       params=request_params)
            except requests.exceptions.Timeout:
                logger.error("No connection to iTunes API - check your Internet connection")
                return False

            if request.status_code != 200:
                logger.error("Error from iTunes API - Error Code {} - {}".format(request.status_code, request.text))
                return False

            if len(request.json()['results']) == 0:
                logger.info("No search results  in iTunes {} for {}".format(country, self._name))
                return False
            else:
                logger.debug("Found iTunes results for {} in {} iTunes Store".format(self._name, country))
                break
        
        self._highres_url = request.json()['results'][0].get('artworkUrl100').replace("100x100", "1200x1200")
        self._normres_url = request.json()['results'][0].get('artworkUrl100').replace("100x100", "600x600")
        logger.info("Found iTunes Artwork for {}, - {}".format(self._name, self._highres_url))
        self._source = "iTunes"
        return True
Example #2
0
def check_updates():
    global offset
    data = {'offset': offset + 1, 'limit': 5, 'timeout': 0}  # Формируем параметры запроса
    request = requests_http('/getUpdates', data)

    if request:
        if not request.json()['ok']:
            return False
    else:
        return False

    for update in request.json()['result']:  # Проверка каждого элемента списка
        offset = update['update_id']  # Извлечение ID сообщения

        # Ниже, если в обновлении отсутствует блок 'message'
        # или же в блоке 'message' отсутствует блок 'text', тогда
        # if not 'message' in update or not 'text' in update['message']:
        mtype = type_message(update)
        if not mtype:
            log_event('Unknown update: %s' % update)  # сохраняем в лог пришедшее обновление
            continue  # и переходим к следующему обновлению

        from_id = update['message']['chat']['id']  # Извлечение ID чата (отправителя)
        name = update['message']['chat']['username']  # Извлечение username отправителя
        if from_id != Settings.adminId:  # Если отправитель не является администратором, то
            send_text("You're not autorized to use me!", from_id)  # ему отправляется соответствующее уведомление
            log_event('Unautorized: %s' % update)  # обновление записывается в лог
            continue  # и цикл переходит к следующему обновлению
        message = update['message'][mtype]  # Извлечение текста сообщения
        parameters = (offset, name, from_id, message)
        log_event('Message (id%s) from %s (id%s): "%s"' % parameters)  # Вывод в лог ID и текста сообщения

        # В зависимости от сообщения, выполняем необходимое действие
        run_command(*parameters)
Example #3
0
    def get_all(self, query=None, page=None, per_page=None):
        """Fetches all models that satisfy some condition.
        
        :param query: query string
        :param page: number of the page used in pagination
        :param per_page: number of the items to be fetched
        :returns: a list of returned models
        """
        results = []
        if not page:
            page = self.config.api_page
        if not per_page:
            per_page = self.config.api_per_page
        with self.config.session as session:
            request = session.get(
                f"{self.config.api_url}/models/",
                params={
                    "page": page,
                    "per_page": per_page
                },
            )
            if "data" in request.json():
                results = request.json()["data"]
                logger.debug(f"Response body: {results}")
            else:
                logger.error("Could not fetch any models.")

        return results
Example #4
0
def get_provisioning_csv(account_id):
    """generates a provisioning report and returns url and file name"""
    report_id = 0
    progress = 0

    payload = {'parameters[courses]': True}
    request = requests.post(ACCOUNT_URL + str(account_id) +
                            '/reports/provisioning_csv',
                            params=payload,
                            headers=HEADER)
    response = request.json()
    #print(response)
    print(response['report'], response['id'], response['parameters'],
          response['created_at'], '\n')

    report_id = response['id']

    while progress != 100:
        request = requests.get(ACCOUNT_URL + str(account_id) +
                               '/reports/provisioning_csv/' + str(report_id),
                               params=payload,
                               headers=HEADER)
        response = request.json()
        progress = response['progress']
        print('	provisioning report progress is at:', progress)

        if progress != 100:
            time.sleep(10)
        elif progress == 100:
            file_name = response['attachment']['display_name']
            file_url = response['attachment']['url']
            break

    return file_url, file_name
Example #5
0
    def upload(
        self,
        name: str,
        filename: str,
        hyperparameters: Union[str, dict],
        parameters: Union[str, dict],
        metrics: Union[str, dict],
        private: bool = False,
        dataset_name: str = "",
        dataset_description: str = "",
    ):
        """Posts a single model.

        :param name: name of model to upload
        :param filename: path to file with a model
        :param hyperparameters: dictionary or path to file with hyperparameters
        :param metrics: dictionary or path to file with metrics
        :param private: 
        :param dataset_name:
        :param dataset_description:

        :returns: posted model
        """
        hyperparameters = self._determine_input(hyperparameters)
        parameters = self._determine_input(parameters)
        metrics = self._determine_input(metrics)

        with self.config.session as session:
            files = {}
            try:
                files["file"] = open(filename, "rb")
            except FileNotFoundError:
                logger.error(f"Model `{filename}` could not be found.")

            git = GitProvider(self.config.git_local_repo)
            payload = {
                "name": name,
                "hyperparameters": json.dumps(hyperparameters),
                "parameters": json.dumps(parameters),
                "metrics": json.dumps(metrics),
                "private": private,
                "user_id": 1,
                "project_id": self.config.selected_project,
                "git_active_branch": git.active_branch,
                "git_commit_hash": git.latest_commit,
            }
            request = session.post(f"{self.config.api_url}/models/",
                                   files=files,
                                   data=payload)

            results = []
            # print(payload)
            # print(request.text)
            if "data" in request.json():
                results.append(request.json()["data"])
            else:
                logger.error("Could not upload selected model.")

            return results
Example #6
0
def get_rank():
    request = requests.get(
        r'https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/' +
        get_summoner_name()[1] + "?api_key=" + key)
    if len(request.json()) == 0:
        print("No ranked data found.")
    else:
        print(request.json())
    def get(self, id: int):
        with self.config.session as session:
            request = session.get(f"{self.config.api_url}/models/{id}/")
            results = []
            if "data" in request.json():
                results.append(request.json()["data"])
            else:
                logger.error("Could not fetch any models.")

        return results
Example #8
0
    def manifest_get(self, ):
        request_uri = self.base_uri + self.__config.endpoint_get('manifest')
        request = requests.get(request_uri, headers=self.headers)

        path = self.base_uri + request.json()['Response']['mobileWorldContentPaths']['en']

        manifest = DestinyManifest(
            path[path.find('world_sql_content'):],
            path,
            request.json()['Response']['version']
        )

        return manifest
Example #9
0
    def get(self, id: int) -> list:
        """Fetches a single model.

        :param id: id of the model to get
        :returns: requested model
        """
        with self.config.session as session:
            request = session.get(f"{self.config.api_url}/models/{id}/")
            results = []
            if "data" in request.json():
                results.append(request.json()["data"])
            else:
                logger.error("Could not fetch any models.")

        return results
Example #10
0
def send_text(chat_id, text):
    log_event('Sending to %s: %s' % (chat_id, text))
    data = {'chat_id': chat_id, 'text': text}
    request = requests.post(URL + TOKEN + '/sendMessage', data=data)
    if not request.status_code == 200:
        return False
    return request.json()['ok']
Example #11
0
def get_proxy_list():
    try:
        url = 'https://www.proxy-list.download/api/v0/get?l=en&t=http'
        request = requests.get(url)
        json_lst = request.json()
    except:
        print('Não foi possível baixar lista de proxies...')
        exit()

    #pprint(json)
    DICT = json_lst[0]
    UPDATED = DICT.get('UPDATED')
    UPDATEDAV = DICT.get('UPDATEDAV')
    TOTAL = DICT.get('TOTAL')
    PAISES = DICT.get('PAISES')
    LISTA = DICT.get('LISTA')

    # CARREGA LISTA DE PROXIES
    # RETORNA UMA LISTA DE OBJETOS
    proxyset = set()
    for server in LISTA:
        proxy = Proxy(server.get('IP'), server.get('PORT'), server.get('ANON'),
                      server.get('COUNTRY'), server.get('ISO'))
        #print('adicionado=',proxy)s
        proxyset.add(proxy)
    return list(proxyset)
Example #12
0
def weather():
    # 获取用户输入城市
    city = entry.get()
    if city == '':
        messagebox.askokcancel("提示", '请输入要查询的城市')
    else:
        # 加码
        if type(city) != str:
            print("请输入正确的城市名")
        else:
            city = urllib.request.quote(city)
            host = 'https://jisutqybmf.market.alicloudapi.com/weather/query'
            app_code = 'd75dfb3bac434086a2f1c2c62ffa9c4e'
            query_s = 'city=' + city
            header = {'Authorization': 'APPCODE ' + app_code}
            url = host + '?' + query_s
            request = requests.get(url, headers=header)
            print(request.status_code)
            info = request.json()['result']
            print(info)
            lis.delete(0, END)
            lis.insert(0, '风力:%s' % info['windpower'])
            lis.insert(0, '风向:%s' % info['winddirect'])
            lis.insert(0, '最低温度:%s℃' % info['templow'])
            lis.insert(0, '最高温度:%s℃' % info['temphigh'])
            lis.insert(0, '温度:%s℃' % info['temp'])
            lis.insert(0, '天气:%s' % info['weather'])
            lis.insert(0, '星期:%s' % info['week'])
            lis.insert(0, '更新时间:%s' % info['updatetime'])
Example #13
0
    def perform_rest_action(self, endpoint, hdrs, params, regions):
        """ construct the POST or GET request"""
        if params:
            endpoint += '?' + urllib.parse.urlencode(params)
        else:
            endpoint += '?'
        data = None
        # check if rate limit is needed
        if self.req_count >= self.reqs_per_sec:
            delta = time.time() - self.last_req
            if delta < 1:
                time.sleep(1 - delta)
            self.last_req = time.time()
            self.req_count = 0

        # submit the POST or GET request to Ensembl REST API server
        # and try to catch errors returned by the server

        if regions:
            request = requests.post(self.server + endpoint,
                                    headers=hdrs,
                                    data=json.dumps(regions))
        else:
            request = requests.get(self.server + endpoint, headers=hdrs)

        if not request.ok:
            request.raise_for_status()
            sys.exit()

        data = request.json()
        self.req_count += 1

        return data
Example #14
0
def send_request(data_matrix, API_key):

    headers = {
        'Content-type': 'application/json',
    }

    instruct = 'computeBestOrder=true&'\
        'vehicleHeading=90&'\
        'sectionType=traffic&'\
        'routeRepresentation=polyline&'\
        'computeTravelTimeFor=all&'\
        'report=effectiveSettings&'\
        'instructionsType=text&'\
        'routeType=fastest&'\
        'traffic=true&'\
        'avoid=unpavedRoads&'\
        'travelMode=car&'\
        'vehicleMaxSpeed=120&'\
        'key='

    request = requests.get('https://api.tomtom.com/routing/1/calculateRoute/' +
                           data_matrix + '/json?' + instruct + API_key,
                           headers=headers)
    json_response = request.json()

    if request.status_code != 200:
        try:
            print(json_response["error"]["description"])
            return
        except:
            print("Something Went Wrong")

    return request
Example #15
0
def tag_index():
    # Read in all image IDs, and the current tag cache
    imageIDs = list(file_search().keys())
    cache = tags_read()

    # Write a dictionary entry for each ID to its corresponding path
    for index in range(len(imageIDs)):
        if imageIDs[index] not in cache:
            # Print a status message for each image
            print("Tagging image " + str(imageIDs[index]) + "... ", end = "")

            try:
                # Send a get request to the server for the images json file
                request = get("https://derpibooru.org/api/v1/json/images/" + str(imageIDs[index]))

                # If status code is not okay, back off on the requests
                if request.status_code != 200:
                    print("Failed! \n Request failed, gracefully backing off")
                    tags_write(cache)
                    break

                # Extract the images takes from the json file and add it to the cache
                tags = request.json()["image"]["tags"]
                cache[imageIDs[index]] = tags
                print("Done")

            except:
                # Print a failed message and flush the cache if a tag lookup fails
                print("FAILED")
                tags_write(cache)
    
    # If all else succeeds, write the cache to disk
    tags_write(cache)
Example #16
0
def get_document_from_url(url, headers=None):
    with requests.get(url, headers={'X-Requested-With':
                                    'XMLHttpRequest'}) as request:
        #     with urllib.request.urlopen(url) as request:
        #         content = request.read().decode()
        doc = lxml.html.fromstring(request.json()['content'])
        return doc
Example #17
0
def do_it(i):
    while (True):
        q = query[random.randint(0, len(query) - 1)]
        call = 'https://api.unsplash.com/photos/random/?query=' + q + '&content_filter=high&orientation=landscape&count=1&featured=true&client_id=' + api_key
        print('Query=' + q)
        request = requests.get(call)
        data = request.json()
        url = data[0]['urls']['full']
        print('Saving image')
        download_image(url, i)

        print('Converting image')
        img = Image.open('E:/Python projects/Twitter_LyricBot/' + str(i) +
                         '.jpg').convert('RGBA')
        arr = np.array(img)

        violet1_hue = 300 / 360.0

        new_img = Image.fromarray(shift_hue(arr, violet1_hue), 'RGBA')
        new_img = new_img.convert('RGB')
        new_img.save('E:/Python projects/Twitter_LyricBot/' + str(i) + '.jpg')

        print('Checking size')
        if (os.path.getsize(str(i) + '.jpg') >= 3072000):
            print('File size was ' + str(os.path.getsize(str(i) + '.jpg')) +
                  '. Retrying for a new image')
            continue
        else:
            print('Saved!')
            break
Example #18
0
def get_lyrics_by_api_call(song_name, artist_name):
    # initializing for making a dataframe
    href_list = []
    icon_list = []
    song_name_list = []
    artist_name_list = []
    lyrics_list = []
    column_list = [
        'title', 'artist', 'lyrics_url', 'lyrics', 'icon_url', 'mood'
    ]
    songs_df = pd.DataFrame(columns=column_list)
    song_name_list.append(song_name)
    artist_name_list.append(artist_name)
    artist_name = artist_name
    track_name = song_name
    api_call = base_url + lyrics_matcher + format_url + artist_search_parameter + artist_name + track_search_parameter + track_name + api_key
    request = requests.get(api_call)
    data = request.json()
    data = data['message']['body']
    lyrics = data['lyrics']['lyrics_body']
    lyrics_list.append(format(lyrics))
    # creating dataframe
    songs_df['title'] = song_name_list
    songs_df['artist'] = artist_name_list
    songs_df['lyrics'] = lyrics_list
    new_df = predict_top_k_list(songs_df)
    return new_df
Example #19
0
def verify_api_copy(course_id):
    """makes an API call to see if content has been copied into course"""
    request = requests.get(COURSE_URL + str(course_id) + '/content_migrations',
                           headers=HEADER)
    response = request.json()

    return bool(response)
Example #20
0
def get_observations_by_stid_datetime(stid,firstdt,lastdt,db_object):
    # Get a set of observations from a specified weather station in a specified time range.
    # Zulu time is used for the timestamps. 
    # Checks whether the database contains a complete record. If not, re-fills from time range.

    get_station_by_stid(stid,db_object)
    obs = db_object.get_observations(stid,firstdt,lastdt)
    firzdt = TimeUtils(firstdt)
    laszdt = TimeUtils(lastdt)
    needsapi = False
    if obs != []:
        nobs = len(obs)
        if nobs > 1:
            secobtime = obs[1]['DATE_TIME']
            secztime = TimeUtils(secobtime)
            tdelta = secztime.datetime - firzdt.datetime
            trange = laszdt.datetime - firzdt.datetime 
            ticks = int(trange.seconds / tdelta.seconds)
            difobsticks = abs(nobs-ticks)
            if difobsticks > 1:
                needsapi = True
    else:
        needsapi = True
        
    if needsapi:
        # There are missing observations within the time range.
        # Call the API to get missing data over the entire range.
        api_arguments = {"token":token,"start":firzdt.synop(),"end":laszdt.synop(),"stid":stid,"units":units}
        api_request_url = get_base_api_request_url("timeseries")
        req = requests.get(api_request_url, params=api_arguments)
        data = req.json()
        db_object.add_observations(data)
        obs = db_object.get_observations(stid,firstdt,lastdt)

    return(obs)
Example #21
0
def get_champion_abilities():
    for champs in champions:
        request = requests.get('http://ddragon.leagueoflegends.com/cdn/' +
                               patch + '/data/en_US/champion/' + champs.name +
                               '.json')
        for x in request.json()['data'][champs.name]['spells']:
            print(x['id'] + '- ' + x['name'] + ': ' + x['description'] + '\n')
Example #22
0
def get_example_radius_dataset():
    radius = (38.09,-122.65,3)
    st_radius = ",".join(map(str,radius))
    api_arguments = {"token":token,"start":"201910092300","end":"201910100400","radius":st_radius,"units":"metric"}
    api_request_url = get_base_api_request_url("timeseries")
    req = requests.get(api_request_url, params=api_arguments)
    data = req.json()
    return(data)
Example #23
0
def api_request(page_token, country_code):
    """Builds the URL and requests the JSON from it"""
    request_url = f"https://www.googleapis.com/youtube/v3/videos?part=id,statistics,contentDetails,snippet{page_token}chart=mostPopular&regionCode={country_code}&maxResults=10&key={cf.api_key}"
    request = requests.get(request_url)
    if request.status_code == 429:
        print("Temp-Banned due to excess requests, please wait and continue later")
        sys.exit()
    return request.json()
def run_query(query):
    request = requests.post('http://localhost:5000/graphql?', json=query)
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception(
            "Query failed to run by returning code of {}. {}".format(
                request.status_code, query))
Example #25
0
    def upload_recorded_show(self, files, show_id):
        logger = self.logger
        response = ''

        retries = int(self.config["upload_retries"])
        retries_wait = int(self.config["upload_wait"])

        url = self.construct_rest_url("upload_file_url")

        logger.debug(url)

        for i in range(0, retries):
            logger.debug("Upload attempt: %s", i + 1)
            logger.debug(files)
            logger.debug(ApiRequest.API_HTTP_REQUEST_TIMEOUT)

            try:
                request = requests.post(
                    url,
                    files=files,
                    timeout=float(ApiRequest.API_HTTP_REQUEST_TIMEOUT))
                response = request.json()
                logger.debug(response)
                """
                FIXME: We need to tell LibreTime that the uploaded track was recorded for a specific show

                My issue here is that response does not yet have an id. The id gets generated at the point
                where analyzer is done with it's work. We probably need to do what is below in analyzer
                and also make sure that the show instance id is routed all the way through.

                It already gets uploaded by this but the RestController does not seem to care about it. In
                the end analyzer doesn't have the info in it's rabbitmq message and imports the show as a
                regular track.

                logger.info("uploaded show result as file id %s", response.id)

                url = self.construct_url("upload_recorded")
                url = url.replace('%%fileid%%', response.id)
                url = url.replace('%%showinstanceid%%', show_id)
                request.get(url)
                logger.info("associated uploaded file %s with show instance %s", response.id, show_id)
                """
                break

            except requests.exceptions.HTTPError as e:
                logger.error("Http error code: %s", e.code)
                logger.error("traceback: %s", traceback.format_exc())
            except requests.exceptions.ConnectionError as e:
                logger.error("Server is down: %s", e.args)
                logger.error("traceback: %s", traceback.format_exc())
            except Exception as e:
                self.logger.exception(e)

            #wait some time before next retry
            time.sleep(retries_wait)

        return response
Example #26
0
def free_rotation():
    freeChamps = []
    request = requests.get(
        r'https://na1.api.riotgames.com/lol/platform/v3/champion-rotations' +
        "?api_key=" + key)
    for champ in champions:
        if int(champ.id) in request.json()['freeChampionIds']:
            freeChamps.append(champ.name)
    return freeChamps
Example #27
0
def ground(link):
    request = requests.get(link)
    data = request.json()
    t1 = json.dumps(data)
    t = json.loads(t1)
    data = t['results']
    return data
    #pprint.pprint(data)
    ''' i=0
Example #28
0
def send_text(chat_id, text):
    """Отправка текстового сообщения по chat_id
    ToDo: повторная отправка при неудаче"""
    log_event('Sending to %s: %s' % (chat_id, text))  # Запись события в лог
    data = {'chat_id': chat_id, 'text': text}  # Формирование запроса
    request = requests_http('/sendMessage', data)  # HTTP запрос
    if not request.status_code == 200:  # Проверка ответа сервера
        return False  # Возврат с неудачей
    return request.json()['ok']  # Проверка успешности обращения к API
Example #29
0
def getTwitchClips(clipsUrl, clipParams, clipHeaders,
                   minsDiffForDuplicateDetection, numClips, whiteListFile):
    request = requests.get(clipsUrl, params=clipParams, headers=clipHeaders)
    clips = request.json()["clips"]
    nonDuplicateClips = removeDuplicateClips(clips,
                                             minsDiffForDuplicateDetection)
    whiteListedClips = applyWhiteList(nonDuplicateClips, numClips,
                                      whiteListFile)
    return whiteListedClips
Example #30
0
def post_topCharts():
    '''Post Topcharts with lyrics of song and image.'''
    trackList = topCharts()
    flag = 0
    print("Printing from topCharts!")
    while flag != 1:
        try:
            # line = getLine(str(trackList))
            rand_ind = random.randint(0, len(trackList) - 1)
            line = str(trackList[rand_ind])
            separator = line.find('-')
            track = line[:separator]
            artist = line[separator + 1:]

            print(artist + ' + ' + track)

            if artist == read_file('lastartist.txt'):
                continue

            n = len(artist) + len(track) + 6
            msg = lyric_matcher(track, artist, n)
            if "Lyric not found" in msg:
                continue
            elif "Lyric too " in msg:
                continue

            msg += '\n' + get_track_artist(track, artist)
            print(msg)

            while True:
                q = query[random.randint(0, len(query) - 1)]
                call = 'https://api.unsplash.com/photos/random/?query=' + q + '&content_filter=high&orientation=landscape&count=1&featured=true&client_id=' + api_key
                request = requests.get(call)
                data = request.json()
                url = data[0]['urls']['full']
                download_image(url)
                print('Checking size')
                if os.path.getsize('temp.jpg') >= 3072000:
                    print('File size was ' + str(os.path.getsize('temp.jpg')) +
                          '. Retrying for a new image')
                    continue
                else:
                    print('Saved!')
                    break

            api.update_with_media('temp.jpg', msg)
            print('Posted')

            flag = 1

            store_lastseen('lastartist.txt', artist)

        except Exception as E:
            flag = 0
            print("Duplicate status averted")
            print(E)
            continue
Example #31
0
def run_command(offset, name, from_id, cmd):
    if cmd == '/ping':  # Ответ на ping
        send_text(from_id, 'pong work')  # Отправка ответа

    elif cmd == '/help':  # Ответ на help
        send_text(from_id, Settings.baseDir)  # Ответ

    elif 'file_id' in cmd:  # Действие если прислан файл
        request = requests_http('/getFile', {'file_id': cmd['file_id']})

        if not request.json()['ok']:
            return False

        loadFile(request.json()['result'], cmd['file_name'], cmd['mime_type'], from_id)
        # log_event(request.json()['result'])
        send_text(from_id, 'Ok!')  # Отправка ответа

    else:
        send_text(from_id, 'Got it.')  # Отправка ответа
def get_human_genes():

    scigraph_service = SCIGRAPH_URL + "/cypher/execute.json"
    query = "MATCH (gene:gene)-[tax:RO:0002162]->(taxon{iri:'http://purl.obolibrary.org/obo/NCBITaxon_9606'}) " \
            "RETURN DISTINCT gene.iri"
    params = {
        "cypherQuery": query,
        "limit": 100000
    }

    request = requests.get(scigraph_service, params=params)
    results = request.json()

    genes = [key["gene.iri"] for key in results]
    gene_set = {map_iri_to_curie(val) for val in genes if not val.startswith("http://flybase.org")}

    return gene_set
def get_orthology_stats(taxon_iri):

    stats = dict()

    query = "MATCH ({{iri:'http://purl.obolibrary.org/obo/NCBITaxon_9606'}})<-[:RO:0002162]-(gene:gene)" \
            "-[rel:RO:HOM0000017|RO:HOM0000020]-(ortholog:gene)-[:RO:0002162]->" \
            "({{iri:'{0}'}}) " \
            "RETURN COUNT(DISTINCT(ortholog)) as ortholog, COUNT(DISTINCT(gene)) as human".format(taxon_iri)

    scigraph_service = SCIGRAPH_URL + "/cypher/execute.json"
    params = {
        "cypherQuery": query,
        "limit": 10
    }
    request = requests.get(scigraph_service, params=params)
    results = request.json()

    stats['human_gene_count'] = results[0]['human']
    stats['model_gene_count'] = results[0]['ortholog']
    return results
Example #34
0
def mcuser(text, bot):
    """<username> - gets information about the Minecraft user <account>"""
    headers = {"User-Agent": bot.user_agent}
    text = text.strip()

    # check if we are looking up a UUID
    cleaned = text.replace("-", "")
    if re.search(r"^[0-9a-f]{32}\Z$", cleaned, re.I):
        # we are looking up a UUID, get a name.
        try:
            name = get_name(cleaned)
        except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError, KeyError) as e:
            return "Could not get username from UUID: {}".format(e)
    else:
        name = text

    # get user data from fishbans
    try:
        request = requests.get(HIST_API.format(requests.utils.quote(name)), headers=headers)
    except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
        return "Could not get profile status: {}".format(e)

    # read the fishbans data
    try:
        results = request.json()
    except ValueError:
        return "Could not parse profile status"

    # check for errors from fishbans and handle them
    if not results["success"]:
        if results["error"] == "User is not premium.":
            return "The account \x02{}\x02 is not premium or does not exist.".format(text)
        else:
            return results["error"]

    username = results["data"]["username"]
    id = uuid.UUID(results["data"]["uuid"])

    return "The account \x02{}\x02 ({}) exists. It is a \x02paid\x02" " account.".format(username, id)
Example #35
0
def getTrackInfo(track):
    request = requests.get("http://api.soundcloud.com/resolve.json?url={0}&client_id={1}".format(track, apikey))
    return request.json()
Example #36
0
def getTrackDownloadLink(trackid):
    request = requests.get("http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}".format(trackid, apikey))
    return request.json()['http_mp3_128_url']
import urllib.request,json.requests
from bs4 import BeautifulSoup

request=urllib.request.urlopen("https://graph.facebook.com/me/posts?access_token={access_token}")
a=request.read()
req=request.json()

msg_id_array=[]
for msg in req['data']['msg']:
	if(msg['message']=="Happy Birthday"):
	    msg_id_array.append(msg['id'])	
	
for i in msg_array:
	current_id=i
	payload={'access_token':'acc_tok',message:'Thank you'}	
    post_reg=req.post("https://graph.facebook.com/me/posts"+current_id+"/"+params=payload)
	
Example #38
0
def get_name(uuid):
    # submit the profile request
    request = requests.get(UUID_API.format(uuid))
    data = request.json()
    return data[uuid]