class Downloader(): def __init__(self, project_name, cache_bgg): if cache_bgg: self.client = BGGClient(cache=CacheBackendSqlite( path=f"{project_name}-cache.sqlite", ttl=60 * 60 * 24, )) else: self.client = BGGClient() def collection(self, user_name, extra_params): collection = [] if isinstance(extra_params, list): for params in extra_params: collection += self.client.collection( user_name=user_name, **params, ) else: collection = list( self.client.collection( user_name=user_name, **extra_params, )) games_data = self.client.game_list( [game_in_collection.id for game_in_collection in collection]) games = list(filter(lambda x: not x.expansion, games_data)) expansions = list(filter(lambda x: x.expansion, games_data)) game_id_to_expansion = {game.id: [] for game in games} for expansion_data in expansions: for expands_game in expansion_data.expands: if expands_game.id in game_id_to_expansion: game_id_to_expansion[expands_game.id].append( expansion_data) game_id_to_tags = {game.id: [] for game in games} for stats_data in collection: if stats_data.id in game_id_to_tags: for tag in [ 'preordered', 'prevowned', 'want', 'wanttobuy', 'wanttoplay', 'fortrade', 'wishlist' ]: if int(getattr(stats_data, tag)): game_id_to_tags[stats_data.id].append(tag) return [ BoardGame( game_data, tags=game_id_to_tags[game_data.id], expansions=[ BoardGame(expansion_data) for expansion_data in game_id_to_expansion[game_data.id] ]) for game_data in games ]
def get_games(username): """ Get games and game collection using bgg API2 returns: list of games and collection object """ bgg = BGGClient(timeout=120, requests_per_minute=20) print("Getting collection from BGG..") collection = bgg.collection(username, exclude_subtype='boardgameexpansion', own=True, wishlist=None) ids = [x.id for x in collection.items] game_list = [] # get games from BGG try: print("Getting games from BGG..") game_list = bgg.game_list(ids) if not game_list: print("Error: empy list returned.") except: print("An Error occured..") raise TimeoutError else: print("Done.") return game_list, collection
def get_collection(username: str) -> BGGClient.collection: bgg = BGGClient() for n in range(0, 8): try: return bgg.collection(username) except Exception as error: logging.warning( str(error) + ' error received, trying again in ' + str(3**n) + ' seconds') time.sleep(3**n) logging.error('too many errors, gg')
def get_user_ratings(username, bgg=None): """Returns a dict: gameid -> rating""" if bgg is None: bgg = BGGClient() collection = bgg.collection(username) user_ratings = dict() for item in collection: if item.rating: user_ratings[item.id] = item.rating return user_ratings
class Downloader(): def __init__(self, cache_bgg): project_name = SETTINGS["project"]["name"] if cache_bgg: self.client = BGGClient(cache=CacheBackendSqlite( path=f"{SETTINGS['project']['name']}-cache.sqlite", ttl=60 * 60 * 24, )) else: self.client = BGGClient() def collection(self, user_name): collection = self.client.collection( user_name=user_name, **SETTINGS["boardgamegeek"]["extra_params"]) games_data = self.client.game_list( [game_in_collection.id for game_in_collection in collection.items]) return [BoardGame(game_data) for game_data in games_data]
def user(request, username, owned, rating): bgg = BGGClient(retries=10, retry_delay=10) coll = bgg.collection(username) running_score = defaultdict(float) n = 0 for game in coll: game_obj, game_created = BoardGame.objects.get_or_create( title=game.name, bgg_id=game.id) coll_obj, created = BGGCollection.objects.update_or_create( boardgame=game_obj, rating=game.rating, owned=bool(game.owned), comment=game.comment, ) if game_created: # Newly added board games would not have genre and mechanism continue if bool(owned) and not bool(game.owned): continue if game.rating is not None: if rating > game.rating: continue combined_score = _recommend_boardgames(game_obj) n += 1 for k, v in combined_score.items(): running_score[k] += v running_score = {k: v / n for k, v in running_score.items()} running_score = sorted(running_score.items(), key=lambda x: -x[1]) return render( request, 'genome/user.html', { 'username': username, 'recs': running_score, 'form': form, 'user_form': user_form, })
from boardgamegeek import BGGClient bgg = BGGClient() my_col = bgg.collection('DarkyLondon', exclude_subtype='boardgameexpansion') games = my_col.items def get_game_dict(): ''' Returns a dictionary mapping games to ids. ''' game_dict = {} for g in games: if g.id not in game_dict: game_dict[g.id] = g.name return game_dict
class Downloader(): def __init__(self): project_name = SETTINGS["project"]["name"] self.client = BGGClient(cache=CacheBackendSqlite( path=f"{project_name}-cache.sqlite", ttl=60 * 60 * 24)) def collection(self, user_name): collection = self.client.collection( user_name=user_name, exclude_subtype=u'boardgameexpansion', **SETTINGS["boardgamegeek"]["extra_params"]) game_data = self.client.game_list( [game_in_collection.id for game_in_collection in collection.items]) return [self.game_data_to_boardgame(game) for game in game_data] def _num_players_is_recommended(self, num, votes): return int(votes['best_rating']) + int( votes['recommended_rating']) > int(votes['not_recommended_rating']) def _facet_for_num_player(self, num, num_with_maybe_plus, votes): is_best = int(votes['best_rating']) > 10 and int( votes['best_rating']) > int(votes['recommended_rating']) best_or_recommended = "Best" if is_best else "Recommended" return { "level1": num, "level2": f"{num} > " + best_or_recommended + f" with {num_with_maybe_plus}", } def game_data_to_boardgame(self, game): num_players = [] for num, votes in game.suggested_players['results'].items(): if not self._num_players_is_recommended(num, votes): continue if "+" not in num: num_players.append(self._facet_for_num_player(num, num, votes)) else: for i in range(int(num.replace("+", "")) + 1, 11): num_players.append( self._facet_for_num_player(i, num, votes)) playing_time_mapping = { 30: '< 30min', 60: '30min - 1h', 120: '1-2h', 180: '2-3h', 240: '3-4h', } for playing_time_max, playing_time in playing_time_mapping.items(): if playing_time_max > int(game.playing_time): break else: playing_time = '> 4h' weight_mapping = { 0: "Light", 1: "Light", 2: "Light Medium", 3: "Medium", 4: "Medium Heavy", 5: "Heavy", } weight = weight_mapping[math.ceil(game.rating_average_weight)] return BoardGame( id=game.id, name=game.name, description=game.description, image=game.thumbnail, categories=[cat for cat in game.categories], mechanics=[mec for mec in game.mechanics], players=num_players, weight=weight, playing_time=playing_time, )
#!/usr/bin/env python3 from math import ceil from boardgamegeek import BGGClient, BGGRestrictCollectionTo as restrict from boardgamegeek.cache import CacheBackendSqlite INCH_TO_CM = 2.54 # Exactly! bgg = BGGClient(cache=CacheBackendSqlite(path=".cache.bgg2", ttl=3600 * 24)) collection = bgg.collection('arnauldvm', own=True, exclude_subtype=restrict.BOARD_GAME_EXTENSION, version=True) print(f"{collection}") unknown_boxes_count = 0 longest_dimension = 0 long_boxes_count = 0 long_boxes_total_height = 0 average_boxes_count = 0 average_boxes_total_height = 0 small_boxes_count = 0 small_boxes_total_height = 0 for game in collection:
def search_match(col): """ Generator for finding games that match filter criteria """ for i, game in enumerate(col, 1): numfit = suggest_playernum(game.suggested_numplayers) if (game.max_players >= num_player and game.min_players <= num_player and game.max_playing_time <= playtime and num_player in numfit[0] and num_player not in numfit[1] and round(game.rating_average_weight) == weight): yield i, game.name bgg = BGGClient() USERNAME = eval(input("BGG Username: ")) collection = bgg.collection(USERNAME, exclude_subtype='boardgameexpansion', own=True, wishlist=None) shuffle(collection.items) ids = [x.id for x in collection.items] print('Hello ' + USERNAME + ', you have ' + str(len(collection)) + ' games in your collection ' '(expansions not counting)') # get games from BGG try: print('Collecting games.. ') game_list = bgg.game_list(ids) except: print('Error!') else: print('Done.\n')
from boardgamegeek import BGGClient from lib import BoardGame def csv_writer(data, path): with open(path, "w", newline='') as csv_file: writer = csv.writer(csv_file, delimiter=';') for line in data: writer.writerow(line) bgg = BGGClient() collection = bgg.collection('Oniwa', exclude_subtype='boardgameexpansion', own=True) foo = [] game_id = [] for item in collection: game_id.append(item.id) games = bgg.game_list(game_id) for personal_game, db_game in zip(collection, games): game = BoardGame.BoardGame() game.collection_to_game(personal_game, db_game) foo.append(game)
from boardgamegeek import BGGClient from PIL import Image import requests from io import BytesIO USER = "******" def show_image(url): """Display an image from the web on the iOS Python terminal""" response = requests.get(url) img = Image.open(BytesIO(response.content)) img.show() bgg = BGGClient() user_collection = bgg.collection(USER, exclude_subtype="boardgameexpansion", own=True) number_of_games = len(user_collection.items) print(f"{USER} has {number_of_games} games in their collection\n\n") for i in range(number_of_games): game = user_collection.items[i] show_image(url=game.thumbnail) # image is nicer, but slow to fetch data = (f"{game.name} \n" f"Players {game.min_players} - {game.max_players} \n" f"Time {game.min_playing_time} - {game.max_playing_time} \n") print(data)
cache = CacheBackendSqlite(path=".cache.bgg", ttl=effective_cache_ttl) bgg1 = BGGClientLegacy(cache=cache) list = bgg1.geeklist(args.list_id, comments=True) print(f"[{list.id}] {list.name}\n{list.description}") bgg2 = BGGClient(cache=cache) games_id_list = [ item.object.id for item in list if item.object.type == 'thing' and item.object.subtype == 'boardgame' ] games = bgg2.game_list(games_id_list) games_dict = {game.id: game for game in games} collection = bgg2.collection(user_name=args.username) collection_dict = {colgame.id: colgame for colgame in collection} def text_formatter(game, effective_name, effective_imageid): print(f" [{game.id}]" f" img:{effective_imageid} {effective_name}", end='') print(f" #{game.bgg_rank}", end='') print(f" year:{game.year}", end='') print(f" players:[{game.min_players}-{game.max_players}]", end='') print(f" age:>={game.min_age}yr", end='') print(f" time:{game.playing_time}'", end='') print(f" weight:{game.rating_average_weight:.1f}/5", end='') print(f" by:{', '.join(game.designers)}", end='') print() if item.description: