def __init__(self, data_path='gamedata/', class_path='gamedata/igdb_class/'): self.classes = [] self.data_path = Path(data_path) self.class_path = Path(class_path) self.igdb = igdb(settings.igdb_key)
def get_games(request): search_query = request.GET.get("query") if search_query: query = search_query return redirect('search_results', query) form = IgdbSearchForm() r = igdb(os.environ.get("IGDB_API_KEY")) games = [] igdb_search = request.GET.get("igdb_search") if igdb_search: result = r.games({ 'search': igdb_search, 'fields': [ 'name', 'summary', 'rating', 'url', 'screenshots', 'cover', 'first_release_date' ] }) for game in result.body: if 'first_release_date' in game: game['first_release_date'] = datetime.utcfromtimestamp( int(game['first_release_date'] / 1000)).strftime('%Y/%m/%d') games.append(game) return render(request, "bible/search_bible.html", { 'games': games, 'form': form }) return render(request, "bible/search_bible.html", { 'games': games, 'form': form })
def igdb_with_name(gamename): ig = igdb(igdbkey) result = ig.games({'search': gamename}).json() i = 0 while i < len(result): try: if not 6 in result[i]['platforms'] or 13 in result[i][ 'platforms']: # 3 linux, 6 pc-windows, 13 pc-dos, 14 mac del result[i] i -= 1 except KeyError: del result[i] i = -1 i += 1 for r in result: r['category'] = gamecategory[r['category']] i = 0 try: for g in r['genres']: for gn in gamegenre: if g == gn['id']: r['genres'][i] = gn['name'] i += 1 except: pass try: r['total_rating'] = round(r['total_rating'], 2) r['cover']['url'] = r['cover']['url'].replace( "thumb", "cover_small") except: pass return result
async def gamelookup(self, ctx, *,game: str): igdb1 = igdb(self.key) result = igdb1.games({ 'search': "{}".format(game), 'fields': ['name','game', 'first_release_date','summary', 'cover','platforms','url'] }) result = result.body GameInfo=result[0] cover = GameInfo['cover'] platformconvert = GameInfo['platforms'] gameurl = GameInfo['url'] platformconvert.sort() plat = "\n".join([Platform_Lookup[x] for x in platformconvert]) gt_dict = UserTime.getUserTime( ctx.author, self.settings, datetime.fromtimestamp(time.mktime(time.localtime(GameInfo["first_release_date"]/1000.))) ) game_time = "{} {}".format(gt_dict['time'], gt_dict['zone']) await Message.Embed( title=GameInfo["name"], thumbnail="http:{}".format(cover["url"]), url=gameurl, color=ctx.author, fields=[ {"name":"Summary", "value":GameInfo['summary'] if len(GameInfo['summary']) <= 1024 else GameInfo['summary'][:1021]+'...'}, {"name":"Release Date", "value":game_time}, {"name":"Platforms", "value":plat} ] ).send(ctx)
def downloadSwitch(): """Download games for the Nintendo Switch platform.""" if not os.path.exists(cfg.databasePath() + '/Games'): os.makedirs(cfg.databasePath() + '/Games') config = cfg.readConfig() fields = config['Database']['fields'].split(',') api = igdb(config['Database']['api_key']) res = api.games({ 'fields': fields, 'filters': { '[release_dates.platform][any]': 130 }, 'scroll': 1, 'limit': 50 }) for game in res.body: filename = cfg.databasePath() + '/Games/{}.json'.format(game['id']) with open(filename, 'w') as outFile: json.dump(game, outFile, indent='\t') nPages = round(int(res.headers['X-Count']) / 50) for _ in range(nPages): scrolled = api.scroll(res) if type(scrolled.body) is list: for game in scrolled.body: filename = cfg.databasePath() + '/Games/{}.json'.format(game['id']) with open(filename, 'w') as outFile: json.dump(game, outFile, indent='\t')
def game_detail(request): search_query = request.GET.get("query") if search_query: query = search_query return redirect('search_results', query) game_id = request.GET.get("game_id") if game_id: game_id = int(game_id) form = IgdbSearchForm() r = igdb(os.environ.get("IGDB_API_KEY")) result = r.games(game_id) for g in result.body: game = g if 'cover' in game: game['cover']['url'] = game['cover']['url'].replace( "t_thumb", "t_cover_big") if 'first_release_date' in game: game['first_release_date'] = datetime.utcfromtimestamp( int(game['first_release_date'] / 1000)).strftime('%Y/%m/%d') if 'rating' in game: game['rating'] = round(game['rating']) if 'screenshots' in game: for i in game['screenshots']: i['url'] = i['url'].replace("t_thumb", "t_original") return render(request, "bible/game_detail.html", { 'game': game, 'form': form }) return redirect('get_games')
def igdb_api_connect(): """ Establish a connection to the IGDB API :return: active IGDB API connection object """ try: api_file = open(igdb_key_file, "rt") except FileNotFoundError: sys.exit( "API key file '{}' not found. Aborting.".format(igdb_key_file)) return igdb.igdb(api_file.read().splitlines()[0])
def get_game_detail(): data = request.get_json(silent=True) game = data['queryResult']['parameters']['game'] print(game) db = igdb(api_key) game_detail = db.games({'search': game, 'fields': 'name'}).body game_detail = db.games(int(game_detail[0]['id'])).body[0] summary = "None" if 'summary' in game_detail: summary = game_detail['summary'] response = """ Title : {0} Summary: {1} """.format(game_detail['name'], summary) reply = { "fulfillmentText": response, } return jsonify(reply)
def send_detsearch(): if request.method == "POST": key = request.form['keyword'] genre = request.form['genre'] category = request.form['category'] rating = request.form['rating'] ig = igdb(igdbkey) result = ig.games({ 'search': key, 'filters': { "[genres][eq]": genre, "[category][eq]": gamecategory.index(category), "[total_rating][gte]": rating, } }).json() i = 0 while i < len(result): try: if not 6 in result[i]['platforms'] or 13 in result[i][ 'platforms']: # 3 linux, 6 pc-windows, 13 pc-dos, 14 mac del result[i] i -= 1 except KeyError: del result[i] i = -1 i += 1 for r in result: i = 0 r['category'] = gamecategory[r['category']] try: for g in r['genres']: for gn in gamegenre: if g == gn['id']: r['genres'][i] = gn['name'] i += 1 except: pass try: r['total_rating'] = round(r['total_rating'], 2) except: pass return render_template('search.html', keyword=key, result=result)
def get_games(request): r = igdb(os.environ.get("igdb_api_key")) games = [] # result=r.games(3192) result = r.games({ 'search': "final fantasy", 'fields': [ 'name', 'summary', 'rating', 'url', 'screenshots', 'cover', 'first_release_date' ] }) for game in result.body: if 'first_release_date' in game: game['first_release_date'] = datetime.utcfromtimestamp( int(game['first_release_date'] / 1000)).strftime('%Y/%m/%d') games.append(game) return render(request, "games/get_games.html", {'games': games})
def handle(self, *args, **options): from igdb_api_python.igdb import igdb igdb = igdb('0cc499afcdb8b8076835350cd909f9f1') result = igdb.platforms({ 'ids': '6', 'fields': 'games' }) games = ast.literal_eval(result.content) games = [str(g) for g in games[0]['games']] i = 0 content = [] while i < 1000: result = igdb.games({ 'ids': games[i + 1:min(i + 1000, 23769)], 'fields': ['name', 'first_release_date', 'url', 'cover', 'summary'], }) content += (ast.literal_eval(result.content)) i += 1000 Game.objects.all().delete() for game in content: try: game['year'] = convert_release_date(game['first_release_date']) g = Game(id=game['id'], name=game['name'], year=game['year'], url = game['url']) except KeyError: g = Game(id=game['id'], name=game['name'], url = game['url']) try: if game['cover']['url'][0] == 'h': g.cover_url = game['cover']['url'].replace('t_thumb','t_cover_big') else: g.cover_url = 'https:' + game['cover']['url'].replace('t_thumb','t_cover_big') except KeyError: pass try: g.summary=game['summary'] except KeyError: pass g.save()
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False ## APP SETUP manager = Manager(app) db = SQLAlchemy(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) ## LOGIN CONFIG login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'login' login_manager.init_app(app) ## IGDB CONFIG igdb = igdb('a062d7e1124df2be5e3847535974b8cc') ## MODELS ## ## ASSOCIATION TABLES games_list = db.Table('games_list',db.Column('list_id',db.Integer, db.ForeignKey('lists.id')),db.Column('game_id',db.Integer, db.ForeignKey('games.id'))) profiles_list = db.Table('profiles_list',db.Column('profile_id',db.Integer, db.ForeignKey('profiles.id')),db.Column('user_id',db.Integer, db.ForeignKey('users.id'))) class Games(db.Model): __tablename__ = "games" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(225)) games = db.relationship('Lists',secondary=games_list,backref=db.backref('games',lazy='dynamic'),lazy='dynamic')
import json from igdb_api_python.igdb import igdb igdb = igdb("CHAVE_DA_IPA") for i in range (0, 100): result = igdb.games({ 'filters' :{ "[summary][exists]": '', "[storyline][exists]": '', "[genres][exists]": '', "[themes][exists]": '', "[game_modes][exists]": '', "[player_perspectives][exists]": '', "[aggregated_rating][exists]": '' }, 'limit': 50, 'offset': i*50, 'order':"date:asc", 'fields': [ 'summary', 'storyline', 'genres', 'themes', 'game_modes', 'player_perspectives', 'aggregated_rating' ] }) filename = 'datasetigdb.json' with open(filename, 'a') as outfile: json.dump(result.body, outfile)
from igdb_api_python.igdb import igdb as igdb def get_key(): filename = '/Users/DarthVader/Desktop/GamerHub/game_key' file = open(filename, "r") key = file.readline() file.close() return key api_key = get_key() igdb = igdb(api_key) def get_platforms(platform_name): result = igdb.platforms({ 'search': platform_name, 'fields': ["games", "name"] }) return result def get_platform_games(plat_name): platform = get_platforms(plat_name) for plat in platform.body: if plat['name'] == plat_name:
import json from igdb_api_python.igdb import igdb as igdb import time, os import pymongo from pymongo import MongoClient client = MongoClient() client = MongoClient('localhost', 27017) db = client.gameDB modes = db.modes perspectives = db.perspectives #ENTER YOUR KEY HERE igdb = igdb('a5b58ad9a031a212726ac14390047c4f') # id_list = [] # id_list.extend(range(1, 50)) # result = igdb.game_modes({ # 'fields':['id','name'], # 'limit': 50, # 'ids': id_list # }) # modeList = [] # modeList.extend(result.body) # print(modeList) # modes.insert_many(modeList) id_list = [] id_list.extend(range(1, 50)) result = igdb.player_perspectives({ 'fields': ['id', 'name', 'games'], 'limit': 50, 'ids': id_list
from igdb_api_python.igdb import igdb import sys import random # In order for the algorithm to work, you must sign up for the API on https://api.igdb.com/ # You will receive a key to the API once you sign up. Next, type the key in between the quotations on line 9. # This activates the API and stores the data from it in variable igdb. The algorithm will correctly work now. igdb = igdb("") def gameslist_genres(genres): for i in range(len(genres)): result = igdb.genres({ 'ids': genres[i], 'fields': 'games', }) gameslist = [] for game in result.body: gameslist.append(game['games']) gameslist = gameslist[0] return(gameslist) def ids(fav1, fav2, fav3): favgames = [fav1, fav2, fav3] id = [] result = igdb.games({ 'search': fav1, 'fields': 'id', }) for game in result.body:
import json from igdb_api_python.igdb import igdb as igdb import time, os import pymongo from pymongo import MongoClient client = MongoClient() client = MongoClient('localhost', 27017) db = client.gameDB companies = db.companies #ENTER YOUR KEY HERE igdb = igdb('f7274ba495a7897e39cc471d61b368aa') data = {} a = 0 ## La lista va en el #4899 company_list = [] for i in range(): id_list = [] b = a + 50 id_list.extend(range(a, b)) result = igdb.companies({ 'fields': ['id', 'name', 'country', 'description', 'published', 'developed'], 'limit': 50, 'ids': id_list }) company_list.extend(result.body) a += 50 companies.insert_many(company_list)
def test_result_of_igdb_search_in_get_games(self): r = igdb(os.environ.get("IGDB_API_KEY")) response = self.client.get("/bible/?igdb_search=test") result = r.games({'search': "427"}) assert result.body != []
# -*- coding: utf-8 -*- from igdb_api_python.igdb import igdb igdb = igdb("c00b1bbc30c379f30337f726be119a69") import json import os #ids_list = [130, 87,99,33,22,19,58,21,4,5,159,20,37,41,137,18,24] #nintendo #ids_list = [7, 8, 38, 46, 48, 9] #sony #ids_list = [12, 11, 49] #microsoft # ids_list = [64, 29, 78, 35, 30, 32, 23] #sega platform_names = open('platform_names.txt', 'w') ids = [ 130, 87, 99, 33, 22, 19, 58, 21, 4, 5, 159, 20, 37, 41, 137, 18, 24, 7, 8, 38, 46, 48, 9, 12, 11, 49, 64, 29, 78, 35, 30, 32, 23, 6 ] for id in ids: result = igdb.platforms({'ids': id, 'fields': 'name'}) platform_names.write(result.body[0]['name'] + ' ' + str(id) + '\n') platform_names.close()
from django.shortcuts import render, get_object_or_404 from .models import Category, Product, Comment from cart.forms import CartAddProductForm from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import UserRegistrationForm, ProfileEditForm, UserEditForm, CommentForm from .models import Profile from igdb_api_python.igdb import igdb from twitch import TwitchClient import json igdb = igdb("d1299d9ef9359fa3d5dcc112abf4b956") #igdb = igdb("03af7252c1029ac5f2235e4d92e9ab4d") def home(request): return render(request, 'shop/home.html', {'home': home}) def about(request): return render(request, 'shop/about.html', {}) def contact(request): return render(request, 'shop/contact.html', {}) @login_required def product_list(request, category_slug=None):
import wikipediaapi from google import google from igdb_api_python.igdb import igdb as igdb wiki = wikipediaapi.Wikipedia('en') reddit = praw.Reddit(username='******', user_agent='THONKING Bot v1.0', client_id='your reddit client id here', client_secret='your reddit client secret here') igdb = igdb("Your igdb key here") class search: def __init__(self,bot): self.bot = bot @commands.command(pass_context=True) @commands.cooldown(1.0, 5.0,commands.BucketType.user) async def hmeme(self,ctx): '''Displays a random hot meme'''
import codecs from igdb_api_python.igdb import igdb import json import sys import os reload(sys) sys.setdefaultencoding('utf8') igdb = igdb(os.environ.get("IGDB_KEY")) def get_all_games(): """Makes API calls to get game information""" platforms = [ 130, 48, 49, 37, 46, 41, 5, 47, 56, 4, 21, 19, 18, 58, 20, 22, 33, 24, 87, 7, 8, 9, 38, 45, 11, 12, 36, 92, 14, 6, 13, 64, 29, 35, 32, 23, 34, 39, 86, 51, 15, 13, 79, 80, 119, 120, 135, 136 ] # get the list of games per platform systems_json = igdb.platforms({'ids': platforms, 'fields': 'games'}) # dump the data into a file with open('systemsfile2.json', 'w') as fp: json.dump(systems_json, fp) for platform_id in platforms: # loop through each platform and get the game info game_ids = igdb.platforms({ 'ids': platform_id, 'fields': ['games', 'name'] })[0]["games"]
def get_igdb() -> igdb: if not hasattr(g, 'igdb'): g.igdb = igdb(current_app.config['IGDB_API_KEY']) return g.igdb
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import User, Theme, Game, Base from igdb_api_python.igdb import igdb engine = create_engine('sqlite:///gamedatabasewithusers.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() igdb = igdb("5383da4777e121af7911808a1d437772") # Add User1 into the database user1 = User(username="******", email="*****@*****.**", picture='static/img/black_user.GIF') session.add(user1) session.commit() # Get 10 themes from the igdb api result = igdb.themes({ 'ids': [18, 19, 20, 21, 22, 23, 27, 28, 31, 32] }) counter = 1 # Iterate from one theme, get game_id from theme for theme in result.body: for i in range(40): # Get properties from each game on that theme r = igdb.games(theme['games'][i]) # Make sure the game we gather has all the properties we want if 'summary' not in r.body[0]: print "summary"
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.template import loader import json from igdb_api_python.igdb import igdb igdb = igdb("KEY") def index(request): return render(request, 'index.html') def searchgames(request): key = request.GET.get('term', None) games = {} if key != None: key = key.strip() #print key result = igdb.games({ 'search': [key], 'fields': ['name'], 'limit': 10, }) games = result.body # for game in games: # game['text'] = game.pop('name') return HttpResponse(json.dumps({
def __init__(self): self.__igdb = igdb(igdb_key)
from igdb_api_python.igdb import igdb from discord import Colour, Embed from config import config igdb = igdb(config['igdb_api_key']) def get_game(title): result = igdb.games({'search': title, 'fields': 'name'}).body[0] result = igdb.games({'ids': result['id'], 'expand': ['developers']}) return result.body[0] def embed_game(game): embed = Embed() embed.type = 'rich' embed.color = Colour.green() embed.title = game['name'] embed.description = game['summary'] embed.url = game['url'] embed.set_footer(text='Game info powered by igdb.com') try: cover = game['cover']['url'] if cover[0] == '/': cover = 'https:' + cover embed.set_thumbnail(url=cover)
import random import threading from igdb_api_python.igdb import igdb ##getting access to the igdb video game database igdb = igdb("dc4da56a02c6038e2ea17b7b1ff4ce7d") ##key for using api def mixer(game_name, misconduct): """This is an internal function that will be used to actually mix up the game titles and the misconducts that the bigger function for this assignment will use.""" game_array = game_name.split(" ") ##splits the game name into an array if len( game_array ) == 1: ##if the game title only has 1 word in it, it puts the misconduct at the end of it game_array.append(misconduct) else: placement = random.randint( 0, len(game_array) - 1 ) ##picks a random word in the game title for the misconduct to replace game_array[ placement] = misconduct ##puts the misconduct in the randomly assigned place mixed_game_name = " ".join( game_array ) ##joins the list back into a string and saves it as a variable print(mixed_game_name) def bot(): """The actual "twitter bot" that will use the mixer function above after grabbing a random game from the video game database and a random misconduct from a list and putting them into the mixer function. """
# t1 = datetime.strptime(timestamp1, "%b %d %H:%M:%S %Y") # t2 = datetime.strptime(timestamp2, "%b %d %H:%M:%S %Y") # # difference = t1 - t2 # # print(difference.days) # 380, in this case # # latest = max((t1, t2)) # t1, in this case #ENTER YOUR KEY HERE API_KEY = secrets.API_KEY igdb = igdb(API_KEY) #DB starts DBNAME = 'game.db' #CACHE_FNAME games_cache_2013 = '2013games.json' games_cache_2014 = '2014games.json' games_cache_2015 = '2015games.json' games_cache_2016 = '2016games.json' games_cache_2017 = '2017games.json' genre_cache = 'genre.json' platform_cache = 'platform.json' CACHE_FNAME = "cache.json" ### Set up CACHE
import requests from rest_framework import generics, status from rest_framework.views import APIView from consolelog_app.models import Game, User, UserProfile from consolelog_app.serializers import GameSerializer, UsersSerializer, LoginSerializer, UserProfileSerializer from rest_framework.response import Response from django.conf import settings from django.utils.text import slugify from consolelog_app.permissions import IsOwnerOrReadOnly from django.db.models import Q from django.core.mail import send_mail ###################### IGDB API ###################################### from igdb_api_python.igdb import igdb as igdb #ENTER YOUR KEY HERE igdb = igdb("857a9df19e79338f5a1f9d88bb6a5a4b") # IndexView class IndexView(TemplateView): template_name = "index.html" #User Profile Page -- CURRENT USERS PROFILE class UserProfileAPIView(generics.RetrieveUpdateAPIView): queryset = User.objects.all() serializer_class = UsersSerializer def get_object(self): logged_in_user = self.request.user user = User.objects.get(pk=logged_in_user.pk)