Exemple #1
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)
Exemple #2
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)