Beispiel #1
0
def api_request(params):
    global wrapper
    try:
        return wrapper.api_request(*params)
    except requests.HTTPError:
        regen_auth()
        wrapper = IGDBWrapper(client_id, os.getenv("AUTHORIZATION"))
        return wrapper.api_request(*params)
Beispiel #2
0
    def get(self, request):

        wrapper = IGDBWrapper("2e0do9w27b1a3ds8ib2tx3979eke6w", "12znirzdkk072uxirvm5kwk6gc3o40")
        query = request.GET 
        game_id = query.get('id', '')

        if game_id in cache:
            data_cache = cache.get(game_id)

            return Response(data=data_cache)
        
        else:
            byte_array = wrapper.api_request(
                        'games',
                        'fields *; where id = ' + game_id  + ';'
            ).decode("utf-8")

            data = json.loads(byte_array)
            cover_id = str(data[0]['cover'])

            byte_array_cover = wrapper.api_request(
                        'covers',
                        'fields *; where id = ' + cover_id  + ';'
            ).decode("utf-8")

            byte_array_year = wrapper.api_request(
                        'release_dates',
                        'fields *; where game = ' + game_id + ';'
            ).decode("utf-8")

            data_year = json.loads(byte_array_year)

            year = str(data_year[0]['y'])

            cover_url = json.loads(byte_array_cover)
            cache.set(game_id, {'data': data, 'cover': cover_url, 'year': year}, 60)

            return Response(data = {
                'data': data,
                'cover': cover_url,
                'year': year
            })
Beispiel #3
0
def igdb_request(endpoint: str, query: str):
    """
    Sends an API request to IGDB (https://api-docs.igdb.com/).
    @param endpoint: The endpoint to send the request to.
    @param query: The body of the API request.
    @return: An object containing the contents of IGDB's response.
    """
    result_types = {"games": GameResult(), "platforms": PlatformResult()}

    wrapper = IGDBWrapper(client_id=os.getenv("IGDB_CLIENT_ID"),
                          auth_token=os.getenv("IGDB_AUTH_TOKEN"))
    results = result_types[endpoint]
    response = wrapper.api_request(endpoint=f'{endpoint}.pb', query=query)

    results.ParseFromString(response)
    return results
Beispiel #4
0
    def get(self, request):

        wrapper = IGDBWrapper("2e0do9w27b1a3ds8ib2tx3979eke6w", "12znirzdkk072uxirvm5kwk6gc3o40")
        query = request.GET 
        search = query.get('search', '')

        if search in cache:
            data_cache = cache.get(search)

            return Response(data=data_cache)
        
        else:
            byte_array = wrapper.api_request(
                            'search',
                            'search "' +  search + '";' + 'fields *;' + 'where game.version_parent = null;' 
            ).decode("utf-8")

            data = json.loads(byte_array)

            return Response(data=data)
def start_query():
    #print('query_callback.start_query')
    gamelist.set("")
    sys.stdout.flush()
    limit = 30   
    platform = gameplatform.get()
    if platform == 'Xbox':
        platformnum = 49
    if platform == 'Sony':
        platformnum = 48
    if platform == 'Switch':
        platformnum = 130
    if platform == 'Phone':
        platformnum = 34
    if platform == 'PC':
        platformnum = 6          
    if platform == "*":
        query = "fields name; limit 30; "
    else:
        query = "fields name; where platforms = " + str(platformnum) + "; limit "+ str(limit) + "; "
    #
    # 48 - PS4, 49 - Xbox one, 130 - switch, 34 - android , 39 - ios , windows - 6
    #
    # token good for 60 days.
    wrapper = IGDBWrapper("ab149we1sss225z73u22uknald6tkx","oeliv17vvkt778iesj0n7m3kvo807t")
    byte_array = wrapper.api_request(
            'games',
            query
            )
    #print(type(byte_array))
    #print(byte_array)
    jdata = json.loads(byte_array)
        
    #rtnlist = ""
    #for i in range(0,limit) :
    #    rtnlist += ( jdata[i]['name'] +"\n" ) 
    #print (rtnlist)
        
    for i in range(0,limit) :
        w.Scrolledlistbox1.insert(i+1,jdata[i]['name'])
Beispiel #6
0
def get_video_game(title='Dogou Souken'):
    """Get video game data and clean up API response from IGDB.

    Parameters
    ----------
    title : str

    Returns
    -------
    json_response : dict
    """
    wrapper = IGDBWrapper(CLIENT_ID, access_token)
    base_query = 'fields id, first_release_date, game_modes, genres, involved_companies, multiplayer_modes, platforms, summary, keywords, themes;'
    where = f' where name="{title}";'
    byte_array = wrapper.api_request('games', base_query + where)

    default_bad_response = fill_missing_fields({'name': title, 'id': None})

    # check for presence of data
    try:
        json_response = json.loads(
            byte_array.decode('utf8').replace("'", '"'))[0]
    except IndexError:
        slack_message(f'{title} did not return any results from IGDB.')
        return default_bad_response

    # ensure we retrieved a game with an id
    if json_response.get('id') is None:
        slack_message(f'{title} did not return an ID from IGDB.')
        return default_bad_response

    json_response['name'] = title

    # convert to datetime if date was retrieved
    if json_response.get('first_release_date') is not None:
        json_response['first_release_date'] = unix_to_datetime(
            json_response['first_release_date'])

    return fill_missing_fields(json_response)
Beispiel #7
0
class GameDBController():
    def __init__(self):
        self.id = os.getenv("IGDBID")
        self.key = os.getenv("IGDBKEY")
        self.token = os.getenv("IGDBTOKEN")
        self.timeout = None
        self.active = False

        self.token = self.getAccessToken()
        if (self.token == None):
            print("IGDB Connection failed")
        else:
            self.wrapper = IGDBWrapper(self.id, self.token)
            self.active = True

    def ok(self):
        if (not self.active):
            return False
        return self.testTimeout()

    def testTimeout(self):
        if (self.timeout == None or time.time() > self.timeout):
            self.getAccessToken()
            if (self.token == None):
                return False
        return True

    def getGame(self, gameid):
        if (self.ok()):
            req = [
                'games',
                'fields slug, name, cover; where id = {0};'.format(int(gameid))
            ]
            result = self.dump(req)
            if (len(result) > 0):
                return result[0]
        return []

    def findGames(self, name):
        if (self.ok()):
            req = ['games', 'fields id, slug, name; search "' + name + '";']
            result = self.dump(req)
            return result
        return None

    def getAccessToken(self):
        print("renewing..")
        uri = "https://id.twitch.tv/oauth2/token?client_id=" + self.id + "&client_secret=" + self.key + "&grant_type=client_credentials"
        result = requests.post(uri).json()
        if ("access_token" in result):
            self.timeout = int(time.time() + result["expires_in"])
            print("token: ", result["access_token"], " timeout: ",
                  self.timeout)
            return result["access_token"]
        return None

    def dump(self, req):
        target = req[0]
        request = req[1]

        byteArr = self.wrapper.api_request(target, request)
        res = byteArr.decode('utf8').replace("'", '"')
        data = json.loads(res)
        return data
Beispiel #8
0
## Requests for IGDB, don't post this to github 
## TODO: remove tokens to file
r = requests.post("https://id.twitch.tv/oauth2/token?client_id="+os.environ('CLIENT_ID')+"&client_secret="+os.environ('CLIENT_SECRET')+"&grant_type=client_credentials")
access_token = json.loads(r._content)['access_token']
wrapper = IGDBWrapper(os.environ('CLIENT_SECRET'), access_token)

#Setting Variables
game_ids = {}
system_ids_dict = {}
system_ids = []

#Get Game information to be used for later parsing
print("Getting game information.")
for i in slugs_list:
    byte_array = wrapper.api_request(
                'games',
                'fields id, cover, platforms, name; offset 0; where slug="'+i+'";'
                )
   
    info = json.loads(byte_array)

    if not info:
        print(i +" cannot be found")
    else:
        game_ids[int(info[0]['id'])] = {}

        game_ids[int(info[0]['id'])]['name'] = info[0]['name']
        game_ids[int(info[0]['id'])]['slug'] = i

        game_ids[int(info[0]['id'])]['cover_id'] = ""
        if 'cover' in info[0]:
            game_ids[int(info[0]['id'])]['cover_id'] = info[0]['cover']
Beispiel #9
0
async def search(ctx, *, arg=None):
    # Input validation
    if arg == None:
        return await ctx.channel.send('Please provide a game.')
    # Establish authentication through Twitch
    twitch = requests.post(
        f'https://id.twitch.tv/oauth2/token?client_id={os.environ.get("TWITCH_ID")}&client_secret={os.environ.get("TWITCH_SECRET")}&grant_type=client_credentials'
    )
    oAuth = twitch.json()
    # Create a new IGDBWrapper object with Twitch access token.
    wrapper = IGDBWrapper(os.environ.get("TWITCH_ID"), oAuth['access_token'])
    # JSON API request
    byte_array = wrapper.api_request(
        'games',
        f'fields name,first_release_date,platforms.name,cover.url;search "{arg}";limit 5;'
    )

    # Parse JSON
    game_info = json.loads(byte_array)

    # Loop through platforms and extract platform name
    platforms = []
    try:
        for n in game_info[0]['platforms']:
            name = n['name']
            platforms.append(name)
    except Exception:
        pass

    # Parse and format release date and determine if game is eligible (15 years old or oler)

    release_date = datetime.datetime.fromtimestamp(
        int(game_info[0]['first_release_date'])).strftime("%B %d, %Y")

    def eligible():
        if datetime.datetime.fromtimestamp(
                int(game_info[0]['first_release_date'])
        ) <= datetime.datetime.now() - datetime.timedelta(days=15 * 365):
            return emoji.emojize(':white_check_mark:')
        else:
            return emoji.emojize(':no_entry_sign:')

    # Fetch thumbnail if it exists
    def thumbnail():
        cover = discord.Embed.Empty
        try:
            if game_info[0]['cover']:
                cover = f"https:{game_info[0]['cover']['url']}"
                return cover
            else:
                return discord.Embed.Empty
        except Exception:
            return cover
        else:
            return cover

    # Search Retro Master List with Google Sheets API
    def on_list():
        try:
            sheets.main()
            if game_info[0]['name'] in searched_titles:
                return 'Yes'
            else:
                embed.set_footer(
                    name='Note:',
                    value=
                    'You will be able to add this game by reating in future iterations of this bot.'
                )
                return 'No'
        except Exception:
            pass

    # Set up embeded message
    embed = discord.Embed(title=game_info[0]['name'], color=0x1f436e)
    embed.set_thumbnail(url=thumbnail())
    embed.add_field(name='Platform(s)', value=' / '.join(platforms))
    embed.add_field(name='Release Date', value=release_date, inline=False)
    embed.add_field(name='Eligible?', value=eligible())
    embed.add_field(name='On list?', value=on_list(), inline=True)

    print(game_info[0])
    await ctx.channel.send(embed=embed)
Beispiel #10
0
def api_call(endpoint, fields_string):
	wrapper = IGDBWrapper(client_id, response['access_token'])
	res = wrapper.api_request(endpoint, fields_string)
	raw_json = res.decode('utf8').replace("'", '"')
	return json.loads(raw_json)
Beispiel #11
0
class igdbHelper(object):
    def __init__(self, client_id: str, client_secret: str, db: DBHelper):
        self.db = db
        db_response = db.get_igdb_app_access_token()
        if db_response:
            app_access_token, expire = db_response
        else:
            app_access_token, expire = None, None

        if not app_access_token or time.time() >= expire:
            response = requests.post(
                f"https://id.twitch.tv/oauth2/token?client_id={client_id}&client_secret={client_secret}&grant_type=client_credentials")
            if response.status_code == 200:
                auth = json.loads(response.text)
                app_access_token = auth['access_token']
                expires_in = auth['expires_in']
                expire = int(time.time()) + expires_in
                db.set_igdb_app_access_token(app_access_token, expire)

        self.wrapper = IGDBWrapper(client_id, app_access_token)

    def search(self, game_name: str):
        byte_array = self.wrapper.api_request(
            'games',
            f'fields id, name, cover.url; search "{game_name}";'
        )
        raw_response: Dict = json.loads(byte_array)

        def get_cover_ulr(item):
            url = None
            try:
                url = 'https:' + \
                    item['cover']['url'].replace('thumb', 'cover_big', 1)
            except:
                pass
            return url

        info = [{
            'coverImage': get_cover_ulr(item),
            'title': item['name'],
            'id': item['id']
        }for item in raw_response]

        return info

    def get(self, game_id: int):
        byte_array = self.wrapper.api_request(
            'games',
            f'fields name, platforms.name, genres.name, summary, game_modes.name, cover.url; where id={game_id};'
        )
        raw_response = json.loads(byte_array)
        raw_response: Dict = raw_response[0]
        #print(json.dumps(raw_response, indent=2))

        def get_cover_ulr(item):
            url = None
            try:
                url = 'https:' + \
                    item['cover']['url'].replace('thumb', 'cover_big', 1)
            except:
                pass
            return url

        info = {
            'id': raw_response['id'],
            'coverImage': get_cover_ulr(raw_response),
            'title': raw_response['name'],
            'genres': (['#{0}'.format(x) for x in (y['name'] for y in raw_response['genres'])]) if raw_response.get('genres') else None,
            'game_modes': (', '.join(x for x in (y['name'] for y in raw_response['game_modes']))) if raw_response.get('game_modes') else None,
            'description': (translate.traducir(str(re.sub('<.*?>', '', raw_response.get("summary", ''))))) if raw_response.get('summary') else None,
            'platforms': raw_response.get('platforms', None)
        }
        return info

    def get_date(self, game_id: int, platform_id: int):
        byte_array = self.wrapper.api_request(
            'release_dates',
            f'fields y; where game={game_id} & platform={platform_id};'
        )
        raw_response: Dict = json.loads(byte_array)
        return sorted([y["y"] for y in raw_response])[0]