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)
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 igdb_wrapper(): url = Prefs['url_IgdbCreds'] authorization = JSON.ObjectFromURL(url, values=None, headers={}, cacheTime=86400, encoding=None, errors=None, timeout=60, sleep=0) wrapper = IGDBWrapper(authorization['client_id'], authorization['access_token']) return wrapper
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
def refresh_token(client_id, client_secret): global next_twitch_refresh global igdb_wrapper if (next_twitch_refresh - 10000 <= time.process_time()): refresh_url = "https://id.twitch.tv/oauth2/token" response = requests.post(url=refresh_url, params={ 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'client_credentials' }) refreshToken = response.json() access_token = refreshToken['access_token'] expires_in = refreshToken['expires_in'] next_twitch_refresh = time.process_time() + expires_in twitch_token = access_token igdb_wrapper = IGDBWrapper(client_id, twitch_token)
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 get(self, request): wrapper = IGDBWrapper("2e0do9w27b1a3ds8ib2tx3979eke6w", "12znirzdkk072uxirvm5kwk6gc3o40") query = request.GET offset = query.get('offset', '') platforms = query.get('platforms', '') category = query.get('category', '') url_str = "?page[limit]="+"20"+"&page[offset]="+offset if category: url_str += "&filter%5Bcategory%5D=" for cat in category.split(','): url_str += category + "" pass
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 })
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 gameArticleTemplate(request, game_id): wrapper = IGDBWrapper("2zu4l0leu7rrc9i8ysagqlxuu5rh89", "h5cqps8rmc4j5zrmeln9jp82d6595m") gameArticle = Game_Model.objects.get(game_id=game_id) summary = getSummary(game_id, wrapper) if request.method == 'POST': rating_value = int(request.POST.get('overall_rating')) print(rating_value) if request.user.is_authenticated: saveRating = Ratings_Model(user_id_id=request.user.id, game_id=game_id, overall_rating=rating_value) saveRating.save() messages.success(request, 'Rating Saved Successfully!') return HttpResponseRedirect(reverse("library")) else: return HttpResponseRedirect(reverse("login")) else: return render(request, 'home/game-article-template.html', {'gameArticle': gameArticle, "gameSummary": summary})
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'])
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)
from igdb.wrapper import IGDBWrapper import shutil import time import requests import json import os slugs_list = [line.rstrip('\n') for line in open('slugs.txt')] ## 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:
import requests import json from igdb.wrapper import IGDBWrapper # Get credentials f = open('credentials.txt') credentials = json.load(f) token = credentials['token'] id_ = credentials['id'] wrapper = IGDBWrapper(id_, token) def getGames(offset): # Returns 500 games from IGDB relative to offset offset = str(offset:int) byte_array = wrapper.api_request( 'games', f'fields *; limit 500; offset {offset}; sort id;' ) return json.loads(byte_array) # Pull game data offset = 0 limit = 150000 data = [] while offset < limit: batch = getGames(offset)
import json, requests.exceptions from igdb.wrapper import IGDBWrapper from practice.local_settings import igdbapi_key from datetime import datetime wrapper = IGDBWrapper(igdbapi_key) def igdbapi_search(game_title): try: byte_array = wrapper.api_request( 'games', 'search "' + game_title + '"; fields name, first_release_date, url, genres, storyline, summary;' ) json_api_data = json.loads(byte_array) genres_list = [] # Checking for emptiness if not json_api_data: return None else: useless_results = ("Collector's Edition", "Collection", "Trilogy", "Golden Edition", "Legacy Collection") for result in json_api_data: # Checking for useless results for useless in useless_results: if useless in result["name"]: result.clear() break else: if 'first_release_date' in result: # formatting date from unix to default format
for i in range(len(game[key])): #game[key][i] is a platform ID in the array that must be extracted with the getter game[key][i] = getPlatforms(game[key][i]) elif key == "genres": for i in range(len(game[key])): game[key][i] = getGenres(game[key][i]) elif key == "involved_companies": for i in range(len(game[key])): game[key][i] = getInvolvedCompanies(game[key][i]) #We parse the hashtable information to a .json file we deliver as output using json.dump() with open(f'../res/data_{fileNumber}.json', 'w') as outfile: json.dump(games, outfile, indent=4) print(f"Games Extracted: {gamesExtracted}") print(f"Finished, check your data_{fileNumber}.json") #Command to initialize game extraction every time this file is ran if __name__ == "__main__": wrapper = IGDBWrapper("2zu4l0leu7rrc9i8ysagqlxuu5rh89", "h5cqps8rmc4j5zrmeln9jp82d6595m") # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=48 & category=0; limit 200;',1) #PS4 # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=49 & category=0; limit 200;', 2) #XB1 # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=130 & category=0; limit 200;',3) #Switch # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=6 & category=0; limit 200;', 4) #PC # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=167; limit 200;', 5) #PS5 # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=169; limit 200;',6) #XB Series X
game_ids = set(game_ids) game_ids = '(' + ','.join([str(g) for g in game_ids]) + ')' game_query = f'fields name; sort rating desc; where id={game_ids} & category=0 & rating != null;' game_data = self.query_endpoint('games', game_query) games = [] for element in game_data: games.append(element['name']) return games def get_all_game_modes(self): game_mode_list = self.query_endpoint('game_modes', 'fields name; limit 50;') game_mode_map = {g['name']: g['id'] for g in game_mode_list} return game_mode_map def get_all_platforms(self): platform_list = self.query_endpoint('platforms', 'fields name; limit 50; where platform_family = (1,2,3,4,5) & platform_family != null;') platform_map = {p['name']: p['id'] for p in platform_list} return platform_map def get_all_genres(self): genre_list = self.query_endpoint('genres', 'fields name; limit 50;') genre_map = {g['name']: g['id'] for g in genre_list} return genre_map if __name__ == '__main__': wrapper = IGDBWrapper(os.environ.get('TWITCH_ID'), get_token()) print(isinstance(wrapper, IGDBWrapper))
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)
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)
def _igdb(): wrapper = IGDBWrapper(os.environ.get('TWITCH_ID'), get_token()) return IGBDAPI(wrapper)
game[key][i] = getPlatforms(game[key][i]) elif key == "genres": for i in range(len(game[key])): game[key][i] = getGenres(game[key][i]) elif key == "involved_companies": for i in range(len(game[key])): game[key][i] = getInvolvedCompanies(game[key][i]) #We parse the hashtable information to a .json file we deliver as output using json.dump() with open(f'../res/data_{fileNumber}.json', 'w') as outfile: json.dump(games, outfile, indent=4) print(f"Games Extracted: {gamesExtracted}") print(f"Finished, check your data_{fileNumber}.json") #Command to initialize game extraction every time this file is ran if __name__ == "__main__": wrapper = IGDBWrapper("2zu4l0leu7rrc9i8ysagqlxuu5rh89", "r2raogtcmwho8ja4fv6b8si2h7u7ag") # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=48 & category=0; limit 200;',1) #PS4 # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=49 & category=0; limit 200;', 2) #XB1 # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=130 & category=0; limit 200;',3) #Switch # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=6 & category=0; limit 200;', 4) #PC # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=167; limit 200;', 5) #PS5 # extractAPIGames('games', 'fields name,genres,platforms,cover,involved_companies; where platforms=169; limit 200;',6) #XB Series X
from flask import session, redirect from functools import wraps import requests import os from random import randint import json from igdb.wrapper import IGDBWrapper client_id = os.getenv("CLIENT_ID") client_secret = os.getenv("CLIENT_SECRET") authorization = os.getenv("AUTHORIZATION") global wrapper wrapper = IGDBWrapper(client_id, authorization) 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) def regen_auth(): response = requests.post( f"https://id.twitch.tv/oauth2/token?grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}" )