Exemplo n.º 1
0
    def get_external_game(bgg_id):
        bgg = BGGClient()
        max_count = 10
        while max_count:
            try:
                return bgg.game(game_id=bgg_id)

            except bgg_exceptions.BGGValueError:
                print("[ERROR] Invalid parameters")
                raise

            except bgg_exceptions.BGGApiRetryError:
                print("[ERROR] Retry after delay, retrying...")
                BoardGameGeek._retry(max_count)

            except bgg_exceptions.BGGApiError:
                print("[ERROR] API response invalid or not parsed")
                BoardGameGeek._retry(max_count)

            except bgg_exceptions.BGGApiTimeoutError:
                print("[ERROR] Timeout")
                BoardGameGeek._retry(max_count)

            except Exception as err:
                print("[ERROR] Exception caught getting external game: " +
                      str(err))
                BoardGameGeek._retry(max_count)

        raise Exception
Exemplo n.º 2
0
    def retrieve(self, request, pk=None):
        """Handle GET requests for single game

        Returns:
            Response -- JSON serialized game instance
        """
        try:
            game = Game.objects.get(pk=pk)
            bgg = BGGClient()
            player = Player.objects.get(user=game.player.user)

            BGGObj = bgg.game(game_id=str(game.game))
            game1={}
            game1['name'] = game.name
            game1["api_id"] = game.game
            game1["api_game_name"]= BGGObj.name
            playerObj = PlayerSerializer(player, context={'request': request})
            game1['player'] = playerObj.data
            game1['host_descrip'] = game.host_descrip
            game1['max_players'] = BGGObj.max_players
            game1['min_players'] = BGGObj.min_players
            game1['category_ids'] = game.category_ids
            game1['categories'] = []
            for category in BGGObj.categories:
                game1['categories'].append(category)
            game1['image'] = BGGObj.image
            game1['thumb_nail'] = BGGObj.thumbnail
            return Response(game1)
        except Exception as ex:
            return HttpResponseServerError(ex)
Exemplo n.º 3
0
 def category_ids(self):
     bgg = BGGClient()
     id_list = []
     api_game = bgg.game(game_id=str(self.game))
     for category in api_game.categories:
         cat = Category.objects.get(name=category)
         id_list.append(cat.id)
     return id_list
Exemplo n.º 4
0
    def is_full(self):
        gameObj = Game.objects.get(pk=self.game_id)
        bgg= BGGClient()
        game = bgg.game(game_id=str(gameObj.game))

        if len(self.player_list) >= int(game.max_players):
            return True
        else:
            return False
Exemplo n.º 5
0
    def need_players(self):
        gameObj = Game.objects.get(pk=self.game_id)
        bgg= BGGClient()
        game = bgg.game(game_id=str(gameObj.game))

        if len(self.player_list) < int(game.min_players):
            players_needed = int(game.min_players)- len(self.player_list)
            return players_needed
        else:
            return 0
Exemplo n.º 6
0
def get_game_info(game_id, bgg=None):
    """Fetch the BGG info for game having game_id"""
    if bgg is None:
        bgg = BGGClient()

    print 'Fetching info for game', str(game_id)

    game = None
    while game is None:
        try:
            game = bgg.game(game_id=game_id)
        except Exception:
            print 'Trying to fetch again...'
            continue

    return game
Exemplo n.º 7
0
    def list(self, request):
        """Handle GET requests to game Categories resource

        Returns:
            Response -- JSON serialized list of park ProductCategorys
        """
        # Creating game dictionary of custom info from game object and API boardgame object so user can see info from both
        bgg = BGGClient()
        search_term = self.request.query_params.get('search', None)
        game_list = []
        if search_term is None:
            games = Game.objects.all()
            collection = []

            for game in games:
                BGGObj = bgg.game(game_id=str(game.game))
                game1={}
                game1['id'] = game.id
                game1['name'] = game.name
                game1["api_id"] = game.game
                owner = Player.objects.get(user=game.player.user)
                playerObj = PlayerSerializer(owner, context={'request': request})
                game1['player'] = playerObj.data
                game1['host_descrip'] = game.host_descrip
                game1['game_descrip'] = BGGObj.description
                game1['max_players'] = BGGObj.max_players
                game1['min_players'] = BGGObj.min_players
                game1['category_ids'] = game.category_ids
                game1['category_names'] = []
                for category in BGGObj.categories:
                    game1['category_names'].append(category)
                game1['image'] = BGGObj.image
                game1['thumb_nail'] = BGGObj.thumbnail
                game_list.append(game1)
        else:
            # If there is a search query param, we are searching BGG API for game results for user to choose from
            results = bgg.games(search_term)
            for result in results:
                game1={}
                game1["name"] = result.name
                game1["min_players"] = result.min_players
                game1["max_players"] = result.max_players
                game1["api_id"] = result.id
                game1["description"] = result.description
                game1["image"] = result.image
                game_list.append(game1)


        # Query param to fetch a logged in user's games
        user_game = self.request.query_params.get('user_game', None)
        # query param to fetch games by category
        category = self.request.query_params.get('category', None)



        if (user_game is not None) or (category is not None):
            if user_game is not None:
                for game in game_list:
                    if (+game['player']['id'] == +request.auth.user_id) & (game not in collection):
                        collection.append(game)


            if category is not None:
                for game in game_list:
                    for id in game["category_ids"]:
                        if (str(id) ==category) & (game not in collection):
                            collection.append(game)

            game_list = collection
        else:
            pass





        return Response(game_list)
    "C:/Users/jerem.DESKTOP-GGM6Q2I/Documents/UNH Data Analytics/r programming 2/final_project"
)
# with open("game_names.txt", "wb") as fp:   #Pickling
#     pickle.dump(testset2, fp)
with open("game_names.txt", "rb") as fp:  # Unpickling
    full_list = pickle.load(fp)

# In[1]:

#get board game data
bgg = BGGClient()
datalists1 = list()
start = time.time()
for i in range(0, "number of games"):
    try:
        datalists1.append(bgg.game(game_id=ids[i]))
    except:
        try:
            datalists1.append(bgg.game(game_id=ids[i]))
        except:
            try:
                datalists1.append(bgg.game(game_id=ids[i]))
            except:
                pass
    if i % 50 == 0:
        print(i)
end = time.time()
print(end - start)

# In[2]:
Exemplo n.º 9
0
# print my_list
# for item in my_list:
#     item.get_name()

bgg = BGGClient()

# mygame = bgg.game('Catan')
# print mygame.name
# print mygame.id

gameplaycount_d = {}

myplays = bgg.plays(username)

for item in myplays:
    # print '%d %s' % (item.game_id, item.game_name)
    if not item.game_id in gameplaycount_d:
        gameplaycount_d[item.game_id] = 1
    else:
        gameplaycount_d[item.game_id] += 1

# print gameplaycount_d

# for game in gameplaycount_d:
#     print game

for game in sorted(gameplaycount_d.items(), key=lambda x: x[1]):
    # print(game)
    print(bgg.game(game_id=game.key).name)

# print(bgg.game(game_id=36218).name)
Exemplo n.º 10
0
print(allIds)

n = 0
while n < len(allIds):
    print("n: ", n)
    try:
        print(">Select")
        cursor.execute("SELECT id FROM alldata WHERE id = ?", (allIds[n], ))
        data = cursor.fetchall()
        if len(data) != 0:
            n += 1
            continue

        now = time.time()
        print(">Get game")
        g = bgg.game(game_id=allIds[n], rating_comments=True)
        print(g.name)
        # print(g.data())
        end_time = time.time()

        # print(gamedata)
        # print(g.comments)
        print(">Concat comments")
        allComments = []
        for comment in g.comments:
            allComments.append(comment.data())
        # print(allComments)

        g.data()['comments'] = allComments
        gamedata = str(g.data())
Exemplo n.º 11
0
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"],
        )

        games = [
            self.game(game_in_collection.id)
            for game_in_collection in collection.items
        ]

        # Print linebreak to terminal, since each game has print(..., end="")
        print()

        return games

    def _num_players_is_recommended(self, num, votes):
        if int(votes['best_rating']) + int(votes['recommended_rating']) > int(
                votes['not_recommended_rating']):
            return True

        return False

    def _facet_for_num_player(self, num, num_with_maybe_plus, votes):
        if int(votes['best_rating']) > 10 and int(votes['best_rating']) > int(
                votes['recommended_rating']):
            best_or_recommended = f"{num} > Best with {num_with_maybe_plus}"
        else:
            best_or_recommended = f"{num} > Recommended with {num_with_maybe_plus}"

        return {
            "level1": num,
            "level2": best_or_recommended,
        }

    def game(self, game_id):
        game = self.client.game(game_id=game_id)

        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)]

        # Print progress to terminal
        print(".", end="", flush=True)

        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,
        )
Exemplo n.º 12
0
    def retrieve(self, request, pk=None):
        """Handle GET requests for order

        Returns:
            Response -- JSON serialized order
        """
        try:

            event = Event.objects.get(pk=pk)

            bgg = BGGClient()

            BGGObj = bgg.game(game_id=str(event.game.game))
            event1 = {}
            event1["id"] = event.id
            event1['name'] = event.name
            event1['description'] = event.description
            event1['address'] = event.address
            event1['zip_code'] = event.zip_code
            # event1['date']=event.date
            event1['date'] = event.date.strftime("%a %b %d, %Y")
            event1['real_date'] = event.date
            event1['time'] = event.time
            event1['recurring'] = event.recurring
            event1['recurring_days'] = event.recurring_days

            # Creating custom game object out of BGG API and game info from user
            game1 = {}
            game1['name'] = event.game.name
            player = Player.objects.get(user=event.game.owner.user.id)
            playerObj = PlayerSerializer(player, context={'request': request})
            game1['owner'] = playerObj
            game1['owner_descrip'] = event.game.host_descrip
            game1['min_players'] = BGGObj.min_players
            game1['max_players'] = BGGObj.max_players
            game1['categories'] = []
            for category in BGGObj.categories:
                game1['categories'].append(category)
            game1['image'] = BGGObj.image
            game1['thumb_nail'] = BGGObj.thumbnail
            event1['game'] = game1

            event1['need_players'] = event.need_players

            # Event model method compairing game max_players against player_list and returning a boolean of True if player_list >= max_players
            event1['is_full'] = event.is_full

            # sending request into event .user_player method to obtain info about logged in user to determine if they are a player on the player_list
            event.user_player = request
            event1['user_player'] = event.user_player

            event1['player_list'] = []

            # serializing each player in the event method that gathers a list of approved players----NOT SURE I TO DO THIS
            for player in event.player_list:
                playerObj = PlayerSerializer(player,
                                             context={'request': request})
                event1['player_list'].append(playerObj.data)

            return Response(event1)
        except Exception as ex:
            return HttpResponseServerError(ex)
Exemplo n.º 13
0
    def list(self, request):
        """Handle GET requests to events resource

        Returns:
            Response -- JSON serialized list of park areas
        """
        events = Event.objects.all().order_by("date")
        bgg = BGGClient()
        event_list = []
        new_list = []

        # Building my own event dictionary using BGG API and Event object created by user
        for event in events:

            BGGObj = bgg.game(game_id=str(event.game.game))
            event1 = {}
            event1["id"] = event.id
            event1['name'] = event.name
            event1['description'] = event.description
            event1['address'] = event.address
            event1['zip_code'] = event.zip_code
            event1['date'] = event.date.strftime("%a %b %d, %Y")
            event1['real_date'] = event.date
            event1['time'] = event.time.strftime("%I:%M %p")
            event1['real_time'] = event.time
            event1['recurring'] = event.recurring
            event1['recurring_days'] = event.recurring_days

            # Creating custom game object out of BGG API and game info from user
            game1 = {}
            game1['name'] = event.game.name
            player = Player.objects.get(user=event.game.player.user)
            playerObj = PlayerSerializer(player, context={'request': request})
            game1['owner'] = playerObj.data
            game1['owner_descrip'] = event.game.host_descrip
            game1['min_players'] = BGGObj.min_players
            game1['max_players'] = BGGObj.max_players
            game1['categories'] = []
            for category in BGGObj.categories:
                game1['categories'].append(category)
            game1['image'] = BGGObj.image
            game1['thumb_nail'] = BGGObj.thumbnail
            event1['game'] = game1

            event1['need_players'] = event.need_players

            # Event model method compairing game max_players against player_list and returning a boolean of True if player_list >= max_players
            event1['is_full'] = event.is_full
            event.pending_request = request
            event1['pending_request'] = event.pending_request

            # sending request into event .user_player method to obtain info about logged in user to determine if they are a player on the player_list
            event.user_player = request
            event1['user_player'] = event.user_player

            event1['player_list'] = []

            # serializing each player in the event method that gathers a list of approved players----NOT SURE I TO DO THIS
            for player in event.player_list:
                playerObj = PlayerSerializer(player,
                                             context={'request': request})
                event1['player_list'].append(playerObj.data)

            # comparing date of event to today's date. If event has happened--it is not added to event_list and sent back to user
            today = datetime.datetime.now(pytz.utc)
            compare = event1['date']
            if event.date >= today:
                event_list.append(event1)
        # query params for:
        #  getting events a user is participating in
        user_player = self.request.query_params.get('user_player', None)
        # getting events that have a game with a category query
        category = self.request.query_params.get('category', None)
        # getting events that are taking place in a zip code query
        zip_code = self.request.query_params.get('zip_code', None)
        # getting events that are playing a certain game
        game = self.request.query_params.get('game', None)
        # getting events that are not full
        is_full = self.request.query_params.get('is_full', None)

        user = self.request.query_params.get('user', None)

        # if there is any query_param then  query param fills up new_list and event_list becomes new list--if not, event_list stays event_list
        if self.request.query_params:

            if user_player is not None:
                for event in event_list:
                    if (str(event['user_player'])
                            == user_player) & (event not in new_list):
                        new_list.append(event)

            if category is not None:
                if user_player:
                    for event in new_list:
                        if category in event['game']['categories']:
                            pass
                        else:
                            new_list.remove(event)
                else:
                    for event in event_list:
                        for cat in event['game']['categories']:
                            if (str(cat) == str(category)) & (event
                                                              not in new_list):
                                new_list.append(event)

            if zip_code is not None:
                if user_player:
                    for event in new_list:
                        if (str(event['zip_code']) == str(zip_code)):
                            pass
                        else:
                            new_list.remove(event)
                else:
                    for event in event_list:
                        if (str(event['zip_code'])
                                == zip_code) & (event not in new_list):
                            new_list.append(event)

            if game is not None:
                if user_player:
                    for event in new_list:
                        if (event['game']['name'].lower() == game.lower()):
                            pass
                        else:
                            new_list.remove(event)
                else:
                    for event in event_list:
                        if (event['game']['name'].lower()
                                == game.lower()) & (event not in new_list):
                            new_list.append(event)

            if user is not None:
                if user_player:
                    for event in new_list:
                        if (event['game']['owner']['user']['username'].lower()
                                == user.lower()):
                            pass
                        else:
                            new_list.remove(event)
                else:
                    for event in event_list:
                        if (event['game']['owner']['user']['username'].lower()
                                == user.lower()) & (event not in new_list):
                            new_list.append(event)

            if is_full is not None:
                if user_player:
                    for event in event_list:
                        if (str(event['is_full']) == is_full):
                            pass
                    else:
                        new_list.remove(event)
                else:

                    for event in event_list:
                        if (str(event['is_full'])
                                == is_full) & (event not in new_list):
                            new_list.append(event)

            event_list = new_list

        else:
            pass
        return Response(event_list)
Exemplo n.º 14
0
from boardgamegeek import BGGClient
# see https://lcosmin.github.io/boardgamegeek/ for documentation

bgg = BGGClient()
hot = bgg.hot_items("boardgame")

hot.items

hot.items[1].rank

hot.items[1].thumbnail

ex_id = hot.items[1].id

g = bgg.game(game_id = ex_id)

dir(g)

# see https://boardgamegeek.com/browse/boardgame for list of top 100 board games
# can use this list to get rank:name and then use above to get info on that game

import pandas as pd

hot_games = pd.read_html("https://boardgamegeek.com/browse/boardgame")[3]
top100 = pd.read_html("https://boardgamegeek.com/browse/boardgame", header = 0)[5]
list(top100) # gets column names

print(tables[3]) #gives hottest games

# Can do same for these pages to get more than top 100
# https://boardgamegeek.com/browse/boardgame/page/2
Exemplo n.º 15
0
class BGGCog(commands.Cog, name="BGG"):
    def __init__(self, bot):
        self.bot = bot
        self._bgg = BGGClient()

    @staticmethod
    def game_path(game):
        return f"https://boardgamegeek.com/boardgame/{game.id}"

    async def fetch_game(self, name: str=None, id: int=None):
        if id:
            return [self._bgg.game(game_id=id)]
        if name:
            return self._bgg.games(name)
        return []

    @commands.command(name='bg', help='Lookup a board game')
    async def lookup(self, ctx: commands.Context, *, message: str):
        if len(message) == 0:
            return

        user = ctx.message.author
        game_name = message

        logger.info(f"Looking up game '{message}' for user {user.id}")
        await ctx.trigger_typing()

        games = []
        if game_name.isdigit():
            games = await self.fetch_game(id=int(game_name))
        else:
            games = await self.fetch_game(name=game_name)

        if len(games) == 0:
            response = "Hmm... not heard of that one!"
            await ctx.send(response)
        elif len(games) == 1:
            response = f"{user.mention} I found this game with the {'id' if game_name.isdigit() else 'name'} {game_name}!"
            await ctx.send(response)

            game = games[0]
            recommend = max((rank.best, rank.player_count)
                            for rank in game._player_suggestion)[1]
            link = BGGCog.game_path(game)
            description = game.description
            if len(game.description) > 300:
                description = description[:297] + "..."

            embed = discord.Embed(title=game.name, url=link)
            embed.add_field(
                name="Players", value=f"{game.min_players}-{game.max_players}", inline=True)
            embed.add_field(name="Best", value=recommend, inline=True)
            embed.add_field(name="Description", value=description)
            embed.set_thumbnail(url=game.thumbnail)

            await ctx.send(embed=embed)
        else:
            response = f"{user.mention} I found {len(games)} games with the name {game_name}!"
            await ctx.send(response)
            embed = discord.Embed(title=f"Games matching '{game_name}'")

            for game in sorted(games, key=lambda g: g.boardgame_rank or float('inf')):
                embed.add_field(name=f"{game.name} ({game.year})",
                                value=BGGCog.game_path(game))

            embed.set_footer(text="Sorted by descending rank")
            await ctx.send(embed=embed)
Exemplo n.º 16
0
    except:
        return ""


df = pd.read_csv("games_input.csv", dtype=str)
df["BGG_ID"] = df["BGG_URL"].apply(get_id)

bgg = BGGClient(requests_per_minute=30)
newdf = pd.DataFrame(columns=df.columns)
for i, row in tqdm(df.iterrows(), total=df.shape[0], ascii=True):
    # print(row.TITLE)
    newdf.loc[i, :] = row
    if not row.BGG_ID:
        continue
    try:
        game = bgg.game(game_id=row.BGG_ID)
    except:
        game = None

    if game:

        newdf.loc[i, "TITLE"] = game.name
        newdf.loc[i, "MINPLAYERS"] = game.min_players
        newdf.loc[i, "MAXPLAYERS"] = game.max_players
        newdf.loc[i, "THUMBNAIL"] = game.thumbnail
        newdf.loc[i, "IMAGE"] = game.image
        newdf.loc[i, "DESCRIPTION"] = game.description.replace("\n", "")
        newdf.loc[i, "YEAR"] = game.year
        if game.expansion:
            newdf.loc[i, "TYPE"] = "Expansion"
            newdf.loc[i, "BASEGAME"] = " AND ".join(