### Install BGG-API Library Source: https://github.com/sukicz/boardgamegeek/blob/master/README.md Command to install the bgg-api package using pip. This is the primary method to add the library to a Python environment. ```bash pip install bgg-api ``` -------------------------------- ### Development and Testing Workflow Source: https://github.com/sukicz/boardgamegeek/blob/master/README.md Commands to set up the development environment, including installing dependencies, configuring pre-commit hooks, and executing test suites via pytest or tox. ```bash # Install dependencies pip install -r requirements/develop.txt # Install pre-commit hooks pre-commit install # Run tests pytest . # Run tests with tox tox ``` -------------------------------- ### GET /search Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Searches for games on BoardGameGeek based on a query string. ```APIDOC ## GET /search ### Description Search for a game using a query string. ### Method GET ### Endpoint /search ### Parameters #### Query Parameters - **query** (str) - Required - The string to search for. - **exact** (bool) - Optional - If True, match the name exactly. ### Response #### Success Response (200) - **results** (list) - List of SearchResult objects. #### Error Handling - **BGGValueError**: Invalid parameter provided. - **BGGApiRetryError**: Request should be retried after a delay. - **BGGApiError**: Response could not be parsed. - **BGGApiTimeoutError**: Request timed out. ``` -------------------------------- ### GET /user Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves detailed information about a specific BoardGameGeek user. ```APIDOC ## GET /user ### Description Retrieves profile details, buddies, guilds, and lists for a user. ### Method GET ### Endpoint /user ### Parameters #### Query Parameters - **name** (str) - Required - User's login name. - **buddies** (bool) - Optional - Include user's buddies. - **guilds** (bool) - Optional - Include user's guilds. - **hot** (bool) - Optional - Include user's hot list. - **top** (bool) - Optional - Include user's top list. - **domain** (str) - Optional - Restrict hot/top lists to a specific domain. ### Response #### Success Response (200) - **User** (object) - User details object. #### Error Handling - **BGGItemNotFoundError**: User not found. - **BGGValueError**: Invalid parameter provided. - **BGGApiRetryError**: Request should be retried after a delay. - **BGGApiError**: Response could not be parsed. ``` -------------------------------- ### GET /guild Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves details about a specific BGG guild. ```APIDOC ## GET /guild ### Description Fetches metadata and member information for a guild by its ID. ### Method GET ### Endpoint /guild ### Parameters #### Query Parameters - **guild_id** (int) - Required - The ID of the guild. - **members** (bool) - Optional - Whether to fetch member names. ### Response #### Success Response (200) - **Guild** (object) - A Guild object containing the requested data. ``` -------------------------------- ### GET /plays Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves play records for a specific user or a specific game. ```APIDOC ## GET /plays ### Description Retrieves the plays for a user (if using name) or for a game (if using game_id). ### Method GET ### Endpoint /plays ### Parameters #### Query Parameters - **name** (str) - Optional - Username to retrieve plays for. - **game_id** (int) - Optional - Game ID to retrieve plays for. - **min_date** (date) - Optional - Return plays from this date or later. - **max_date** (date) - Optional - Return plays from this date or earlier. - **subtype** (str) - Optional - Limit results to specified subtype (default: 'boardgame'). ### Response #### Success Response (200) - **Plays** (object) - Object containing all retrieved plays. #### Error Handling - **BGGValueError**: Invalid parameter provided. - **BGGApiRetryError**: Request should be retried after a delay. - **BGGApiError**: Response could not be parsed. - **BGGApiTimeoutError**: Request timed out. ``` -------------------------------- ### Fetch Game Information by Name Source: https://context7.com/sukicz/boardgamegeek/llms.txt Retrieve board game details using a name string. Includes examples of accessing game properties, statistics, and handling multiple search results using different selection strategies. ```python from boardgamegeek import BGGClient, BGGChoose bgg = BGGClient("your_access_token_here") # Get game by exact name match (default) game = bgg.game("Catan") # Access game properties print(f"Game: {game.name}") print(f"ID: {game.id}") print(f"Year Published: {game.year}") print(f"Players: {game.min_players}-{game.max_players}") print(f"Playing Time: {game.playing_time} minutes") print(f"Minimum Age: {game.min_age}") print(f"Description: {game.description[:200]}...") # Ratings and statistics print(f"Average Rating: {game.rating_average}") print(f"BGG Rank: {game.bgg_rank}") print(f"Users Rated: {game.users_rated}") print(f"Users Owned: {game.users_owned}") print(f"Weight: {game.rating_average_weight}") # Game metadata print(f"Categories: {', '.join(game.categories)}") print(f"Mechanics: {', '.join(game.mechanics)}") print(f"Designers: {', '.join(game.designers)}") print(f"Publishers: {', '.join(game.publishers)}") print(f"Artists: {', '.join(game.artists)}") # Handle multiple results with different strategies game_first = bgg.game("Monopoly", choose=BGGChoose.FIRST) # First result game_recent = bgg.game("Monopoly", choose=BGGChoose.RECENT) # Most recent game_best = bgg.game("Monopoly", choose=BGGChoose.BEST_RANK) # Best ranked # Non-exact name matching game_fuzzy = bgg.game("Catan", exact=False) ``` -------------------------------- ### GET /games Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Searches for all games matching a specific name string. ```APIDOC ## GET /games ### Description Returns a list of all games found that match the provided search string. ### Method GET ### Endpoint /games ### Parameters #### Query Parameters - **name** (str) - Required - The name to search for. ### Response #### Success Response (200) - **list** (list[BoardGame]) - A list of matching BoardGame objects. ``` -------------------------------- ### GET /games/{id} Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves detailed information about a specific board game, including designers, mechanics, and marketplace listings. ```APIDOC ## GET /games/{id} ### Description Provides comprehensive details about a board game, including metadata like designers, categories, and expansions. ### Method GET ### Endpoint /games/{id} ### Parameters #### Path Parameters - **id** (int) - Required - The unique identifier for the board game. ### Response #### Success Response (200) - **name** (str) - Game title - **designers** (list[str]) - List of designers - **mechanics** (list[str]) - List of game mechanics - **min_age** (int) - Minimum recommended age #### Response Example { "name": "Terraforming Mars", "designers": ["Jacob Fryxelius"], "mechanics": ["Drafting", "Hand Management"], "min_age": 12 } ``` -------------------------------- ### GET /game_list Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves a list of board game objects based on a provided list of BGG IDs. ```APIDOC ## GET /game_list ### Description Fetches data for multiple games simultaneously using a list of IDs. ### Method GET ### Endpoint /game_list ### Parameters #### Request Body - **game_id_list** (list[int]) - Required - List of unique game IDs. - **versions** (bool) - Optional - Include version information. - **videos** (bool) - Optional - Include videos. - **historical** (bool) - Optional - Include historical data. - **marketplace** (bool) - Optional - Include marketplace data. ### Response #### Success Response (200) - **list** (list[BoardGame]) - A list of BoardGame objects. ``` -------------------------------- ### GET /game Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves detailed information about a specific board game using its name or unique ID. ```APIDOC ## GET /game ### Description Fetches comprehensive data for a board game. Allows for optional inclusion of versions, videos, historical data, marketplace info, and comments. ### Method GET ### Endpoint /game ### Parameters #### Query Parameters - **name** (str) - Optional - The name of the game. - **game_id** (int) - Optional - The unique ID of the game. - **choose** (str) - Optional - Selection method for multiple results ('first', 'recent', 'best-rank'). - **versions** (bool) - Optional - Include version information. - **videos** (bool) - Optional - Include videos. - **historical** (bool) - Optional - Include historical data. - **marketplace** (bool) - Optional - Include marketplace data. - **comments** (bool) - Optional - Include comments. - **exact** (bool) - Optional - Limit results to exact name matches. ### Response #### Success Response (200) - **BoardGame** (object) - A BoardGame object containing all requested game details. ``` -------------------------------- ### GET /collection/items Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves the list of items within a user's board game collection, including user-specific metadata. ```APIDOC ## GET /collection/items ### Description Returns the items in a user's collection, represented as a list of CollectionBoardGame objects. ### Method GET ### Endpoint /collection/items ### Response #### Success Response (200) - **items** (list[CollectionBoardGame]) - The collection items. - **owner** (str) - The owner of the collection. #### Response Example { "owner": "username", "items": [ { "owned": true, "rating": 8.5, "wishlist": false, "comment": "Great game!" } ] } ``` -------------------------------- ### GET /hot_items Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves a list of currently trending items on BoardGameGeek based on the specified category. ```APIDOC ## GET /hot_items ### Description Returns the list of "Hot Items" from BoardGameGeek. ### Method GET ### Endpoint /hot_items ### Parameters #### Query Parameters - **item_type** (str) - Required - Valid values: "boardgame", "rpg", "videogame", "boardgameperson", "rpgperson", "boardgamecompany", "rpgcompany", "videogamecompany" ### Response #### Success Response (200) - **HotItems** (object) - A collection of hot items. #### Error Handling - **BGGValueError**: Invalid parameter provided. - **BGGApiRetryError**: Request should be retried after a delay. - **BGGApiError**: Response could not be parsed. - **BGGApiTimeoutError**: Request timed out. ``` -------------------------------- ### Get List of Games by IDs Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Fetches a list of board games based on a provided list of game IDs. This function allows for the inclusion of additional details such as versions, videos, historical data, and marketplace information for each game in the returned list. ```python from boardgamegeek import BoardGameGeek bgg = BoardGameGeek() game_ids = [184854, 84876] games_list = bgg.game_list(game_id_list=game_ids, historical=True) ``` -------------------------------- ### GET /get_game_id Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves the unique BGG ID for a game by searching for its name. ```APIDOC ## GET /get_game_id ### Description Resolves a game name to its corresponding BGG ID. ### Method GET ### Endpoint /get_game_id ### Parameters #### Query Parameters - **name** (str) - Required - The name of the game. - **choose** (str) - Optional - Selection method for multiple results. - **exact** (bool) - Optional - Require exact match. ### Response #### Success Response (200) - **id** (int) - The BGG ID of the game. ``` -------------------------------- ### Get Guild Details Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Fetches detailed information about a specific guild on BoardGameGeek using its ID. Optionally includes a list of guild members if the 'members' parameter is set to True. Returns a Guild object or None if the information cannot be retrieved. ```python from boardgamegeek import BoardGameGeek bgg = BoardGameGeek() guild_details = bgg.guild(guild_id=1234, members=True) ``` -------------------------------- ### Get Game Information by Name or ID Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves detailed information about a specific board game using its name or unique ID. Supports various options to include related data like versions, videos, historical data, marketplace listings, and comments. It handles multiple results by allowing selection via 'first', 'recent', or 'best-rank'. ```python from boardgamegeek import BoardGameGeek bgg = BoardGameGeek() # Get game by name game_by_name = bgg.game(name='Terraforming Mars') # Get game by ID with extra details game_by_id = bgg.game(game_id=184854, versions=True, videos=True) ``` -------------------------------- ### Get Game ID by Name Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Retrieves the unique BoardGameGeek ID for a game by searching for its name. It offers options to choose the 'first' result, the 'recent' one, or the 'best-rank' if multiple games share the same name, and can enforce exact name matching. Returns the game ID as an integer or None if not found. ```python from boardgamegeek import BoardGameGeek bgg = BoardGameGeek() game_id = bgg.get_game_id(name='Wingspan', choose='best-rank', exact=True) ``` -------------------------------- ### Initialize BGGClient Source: https://context7.com/sukicz/boardgamegeek/llms.txt Demonstrates how to instantiate the BGGClient with various configurations, including different caching backends (Memory, SQLite, None) and custom request settings like timeouts and rate limits. ```python from boardgamegeek import ( BGGClient, CacheBackendNone, CacheBackendMemory, CacheBackendSqlite, ) # Basic initialization with access token (uses in-memory cache by default) bgg = BGGClient("your_access_token_here") # Disable caching entirely bgg_no_cache = BGGClient( access_token="your_access_token_here", cache=CacheBackendNone() ) # Use SQLite for persistent caching (TTL in seconds) bgg_sqlite = BGGClient( access_token="your_access_token_here", cache=CacheBackendSqlite(path="/path/to/cache.db", ttl=3600) ) # Custom configuration with all options bgg_custom = BGGClient( access_token="your_access_token_here", cache=CacheBackendMemory(ttl=7200), # 2 hour cache timeout=30, # 30 second timeout retries=5, # retry 5 times on 202 responses retry_delay=10, # wait 10 seconds between retries requests_per_minute=30 # rate limit to 30 requests/minute ) ``` -------------------------------- ### Initialize BGGClient with various caching and authentication options Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Demonstrates how to instantiate the BGGClient, showcasing different caching backends (in-memory, none, SQLite) and the use of an access token for authentication. The client can be configured with timeouts, retries, and request rate limiting. ```python from boardgamegeek.cache import CacheBackendNone, CacheBackendSqlite bgg = BGGClient("") game = bgg.game("Android: Netrunner") print(game.id) bgg_no_cache = BGGClient(cache=CacheBackendNone()) bgg_sqlite_cache = BGGClient(cache=CacheBackendSqlite(path="/path/to/cache.db", ttl=3600)) bgg_with_token = BGGClient(access_token="your_bgg_access_token") ``` -------------------------------- ### Initialize BGGClient and Fetch Game Data Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/index.md Demonstrates how to initialize the BGGClient with an access token and retrieve information about a specific game by its name. It then prints the game's release year and average rating. ```python from boardgamegeek import BGGClient bgg = BGGClient("access_token") game = bgg.game("Monopoly") print(game.year) # 1935 print(game.rating_average) # 4.36166 ``` -------------------------------- ### BGGClient Initialization Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Initializes the BGGClient with various configuration options, including access token, caching, timeouts, and rate limiting. ```APIDOC ## BGGClient Initialization ### Description Initializes the BGGClient for interacting with the BoardGameGeek XML API 2. Supports authentication via an access token and offers flexible caching mechanisms. ### Method Constructor ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **access_token** (str) - Required - BGG access token for API authentication. Obtain from the [BGG applications page](https://boardgamegeek.com/applications). - **cache** (CacheBackend) - Optional - An object for caching requests. Defaults to `CacheBackendMemory`. Supports `CacheBackendNone` and `CacheBackendSqlite`. - **timeout** (float) - Optional - Timeout for network operations in seconds. Defaults to 15. - **retries** (int) - Optional - Number of retries for HTTP 202 responses or timeouts. Defaults to 3. - **retry_delay** (float) - Optional - Time to sleep between retries in seconds. Defaults to 5. - **disable_ssl** (bool) - Optional - Ignored, left for backwards compatibility. - **requests_per_minute** (int) - Optional - Maximum requests per minute to BGG to prevent throttling. Defaults to 30. ### Request Example ```python from boardgamegeek.api import BGGClient from boardgamegeek.cache import CacheBackendNone, CacheBackendSqlite # Basic initialization with access token bgg = BGGClient("") # Initialization without cache bgg_no_cache = BGGClient(cache=CacheBackendNone()) # Initialization with SQLite cache bgg_sqlite_cache = BGGClient(cache=CacheBackendSqlite(path="/path/to/cache.db", ttl=3600)) # Initialization with access token and custom settings bgg_with_token = BGGClient(access_token="your_bgg_access_token", timeout=10, retries=5) ``` ### Response #### Success Response (200) N/A (Constructor does not return a response) #### Response Example N/A ``` -------------------------------- ### Accessing Game Marketplace and Expansion Information Source: https://context7.com/sukicz/boardgamegeek/llms.txt Demonstrates how to iterate through a game's marketplace listings, check if a game is an expansion, and list its related base games or other expansions. It also shows how to access player suggestions based on community poll data. ```python for listing in game.marketplace: print(f"Price: {listing.price} {listing.currency}") print(f"Condition: {listing.condition}") print(f"Link: {listing.link}") if game.expansion: print(f"{game.name} is an expansion for:") for base_game in game.expands: print(f" - {base_game.name} (ID: {base_game.id})") for expansion in game.expansions: print(f"Expansion: {expansion.name} (ID: {expansion.id})") for suggestion in game.player_suggestions: print(f"Players: {suggestion.player_count}") print(f" Best: {suggestion.best}, Recommended: {suggestion.recommended}") ``` -------------------------------- ### Publishing and Versioning Source: https://github.com/sukicz/boardgamegeek/blob/master/README.md Commands used to manage project versioning and synchronization with the remote repository. It utilizes bump2version to update the project version and pushes tags to GitHub. ```bash # Bump version (patch, minor, major) bump2version patch # Push to github git push --tags origin master ``` -------------------------------- ### Fetch Game Data using BGGClient Source: https://github.com/sukicz/boardgamegeek/blob/master/README.md Demonstrates how to initialize the BGGClient with an access token and retrieve specific game information. The client returns a game object containing attributes like release year and average rating. ```python from boardgamegeek import BGGClient bgg = BGGClient("") game = bgg.game("Monopoly") print(game.year) # 1935 print(game.rating_average) # 4.36166 ``` -------------------------------- ### Fetching User Game Collections with Filters Source: https://context7.com/sukicz/boardgamegeek/llms.txt Demonstrates how to retrieve a user's entire game collection or filter it by various criteria such as owned games, wishlist status, games for trade, and minimum user or BGG ratings. Provides access to detailed game attributes within the collection. ```python from boardgamegeek import BGGClient, BGGRestrictCollectionTo bgg = BGGClient("your_access_token_here") # Get user's complete collection collection = bgg.collection("username_here") print(f"Owner: {collection.owner}") print(f"Total Items: {len(collection)}") # Iterate through collection items for game in collection: print(f"Game: {game.name}") print(f" ID: {game.id}") print(f" Year: {game.year}") print(f" My Rating: {game.rating}") print(f" Plays: {game.numplays}") print(f" Owned: {game.owned}") print(f" For Trade: {game.for_trade}") print(f" Want to Play: {game.want_to_play}") print(f" Wishlist: {game.wishlist}") print(f" Comment: {game.comment}") # Filter collection - owned games only owned_games = bgg.collection("username_here", own=True) # Filter by various criteria wishlist = bgg.collection( "username_here", wishlist=True, wishlist_prio=1 # Priority 1-5 ) # Games for trade for_trade = bgg.collection("username_here", trade=True) # Highly rated games top_rated = bgg.collection( "username_here", min_rating=8.0, # User rating >= 8 own=True ) # Filter by BGG rating well_regarded = bgg.collection( "username_here", min_bgg_rating=7.5 ) ``` -------------------------------- ### RateLimitingAdapter Class Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md An adapter for the Requests library that enforces a delay between requests to prevent rate limiting by the BGG site. ```APIDOC ## `boardgamegeek.utils.RateLimitingAdapter` ### Description Adapter for the Requests library which makes sure there’s a delay between consecutive requests to the BGG site so that we don’t get throttled. ### Methods #### `send(request: PreparedRequest, *args: Any, **kwargs: Any)` Sends PreparedRequest object. * **Parameters:** * **request** (PreparedRequest) - The `PreparedRequest` being sent. * **stream** (bool, optional) - Whether to stream the request content. * **timeout** (float or tuple or urllib3 Timeout object, optional) - How long to wait for the server to send data before giving up. * **verify** (bool or str, optional) - Controls whether to verify the server’s TLS certificate or a path to a CA bundle. * **cert** (any, optional) - Any user-provided SSL certificate to be trusted. * **proxies** (dict, optional) - The proxies dictionary to apply to the request. * **Returns:** Response - Response object. * **Raises:** Various exceptions from the requests library if the request fails. ``` -------------------------------- ### Implement Error Handling Source: https://context7.com/sukicz/boardgamegeek/llms.txt Demonstrates how to catch and handle specific BGG API exceptions, such as item not found, timeout errors, and invalid parameter validation. ```python try: game = bgg.game("NonexistentGameXYZ123") except BGGItemNotFoundError: print("Game not found") except BGGApiTimeoutError: print("Request timed out") except BGGValueError as e: print(f"Invalid parameter: {e}") ``` -------------------------------- ### request_and_parse_xml Function Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Downloads, parses, and returns an XML ElementTree from a given URL, with retry logic. ```APIDOC ## `boardgamegeek.utils.request_and_parse_xml(requests_session: Session, url: str, params: dict[str, Any] | None = None, timeout: float = 15.0, retries: int = 3, retry_delay: float = 5.0, headers: dict[str, str] | None = None)` ### Description Downloads an XML from the specified URL, parses it, and returns the xml ElementTree. * **Parameters:** * **requests_session** (Session) - A Session of the `requests` library, used to fetch the URL. * **url** (str) - The address where to get the XML from. * **params** (dict[str, Any], optional) - Dictionary containing the parameters to be sent with the request. * **timeout** (float, optional) - Number of seconds after which the request times out. Defaults to 15.0. * **retries** (int, optional) - Number of retries to perform in case of timeout. Defaults to 3. * **retry_delay** (float, optional) - The amount of seconds to sleep when retrying an API call that returned 202. Defaults to 5.0. * **headers** (dict[str, str], optional) - Dictionary containing the headers to be sent with the request. * **Returns:** Element - `xml.etree.ElementTree()` corresponding to the XML. * **Raises:** `BGGApiRetryError` - If this request should be retried after a short delay. `BGGApiError` - If the response was invalid or couldn’t be parsed. `BGGApiTimeoutError` - If there was a timeout. ``` -------------------------------- ### Searching for Games by Name Source: https://context7.com/sukicz/boardgamegeek/llms.txt Explains how to search the BoardGameGeek database for games using a query string. Supports exact matching and retrieving full game objects or just their BGG IDs. ```python from boardgamegeek import BGGClient bgg = BGGClient("your_access_token_here") # Search for games results = bgg.search("Catan") for result in results: print(f"ID: {result.id}") print(f"Name: {result.name}") print(f"Type: {result.type}") # boardgame, boardgameexpansion, etc. print(f"Year: {result.year}") print("---") # Exact match search results = bgg.search("Catan", exact=True) # Get all games with exact name match as full BoardGame objects games = bgg.games("Catan") for game in games: print(f"{game.name} ({game.year}) - Rating: {game.rating_average}") # Get just the BGG ID for a game game_id = bgg.get_game_id("Catan") print(f"Catan's BGG ID: {game_id}") ``` -------------------------------- ### Filter and Retrieve User Collections Source: https://context7.com/sukicz/boardgamegeek/llms.txt Demonstrates how to fetch a user's board game collection with various filters such as play counts, subtypes, version information, and modification dates. ```python frequently_played = bgg.collection("username_here", min_plays=10) expansions = bgg.collection( "username_here", subtype=BGGRestrictCollectionTo.BOARD_GAME_EXTENSION ) collection_with_versions = bgg.collection("username_here", version=True) for game in collection_with_versions: if game.version: print(f"{game.name} - Version: {game.version.name}") recent_changes = bgg.collection("username_here", modified_since="2024-01-01") ``` -------------------------------- ### Fetch Play Sessions and History Source: https://context7.com/sukicz/boardgamegeek/llms.txt Retrieves play logs for users or specific games, including filtering by date ranges and game subtypes. It demonstrates how to iterate through play details and associated player data. ```python plays = bgg.plays(name="username_here") for play in plays.plays[:10]: print(f"Game: {play.game_name} (ID: {play.game_id})") for player in play.players: print(f" Player: {player.name}, Score: {player.score}") plays_2024 = bgg.plays( name="username_here", min_date=datetime.date(2024, 1, 1), max_date=datetime.date(2024, 12, 31) ) ``` -------------------------------- ### Fetching Multiple Games by ID Source: https://context7.com/sukicz/boardgamegeek/llms.txt Shows how to retrieve information for multiple games simultaneously using their BGG IDs. This method is limited to 20 games per request and can include optional parameters like versions and marketplace data. ```python from boardgamegeek import BGGClient bgg = BGGClient("your_access_token_here") # Fetch multiple games by ID list game_ids = [174430, 167791, 224517, 161936, 169786] # Top games games = bgg.game_list(game_ids) for game in games: print(f"{game.name}: Rank #{game.bgg_rank}, Rating: {game.rating_average:.2f}") # With additional options games = bgg.game_list( game_id_list=[13, 822, 2651], versions=True, marketplace=True ) ``` -------------------------------- ### fix_url Function Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Corrects URLs that are missing the scheme (e.g., '//example.com/image.jpg'). ```APIDOC ## `boardgamegeek.utils.fix_url(url: str | None)` ### Description The BGG API started returning URLs like `//cf.geekdo-images.com/images/pic55406.jpg` for thumbnails and images. This function fixes them. * **Parameters:** * **url** (str or None) - The URL to fix. * **Returns:** str or None - The fixed URL, or None if the input was None. ``` -------------------------------- ### Fetching User Information and Lists Source: https://context7.com/sukicz/boardgamegeek/llms.txt Details how to retrieve comprehensive information about a BoardGameGeek user, including their profile, gaming accounts, buddies, guild memberships, and top/hot game lists. Allows customization of fetched data and domain restriction. ```python from boardgamegeek import BGGClient, BGGRestrictDomainTo bgg = BGGClient("your_access_token_here") # Get user information user = bgg.user("username_here") # Profile information print(f"Username: {user.name}") print(f"User ID: {user.id}") print(f"Name: {user.firstname} {user.lastname}") print(f"Country: {user.country}") print(f"State: {user.state}") print(f"Last Login: {user.last_login}") print(f"Avatar: {user.avatar}") print(f"Homepage: {user.homepage}") # Gaming accounts print(f"Xbox: {user.xbox_account}") print(f"PSN: {user.psn_account}") print(f"Steam: {user.steam_account}") # Buddies print(f"Total Buddies: {user.total_buddies}") for buddy in user.buddies[:10]: print(f" - {buddy.name} (ID: {buddy.id})") # Guild memberships print(f"Total Guilds: {user.total_guilds}") for guild in user.guilds: print(f" - {guild.name} (ID: {guild.id})") # User's top 10 games print("Top 10 Games:") for item in user.top10: print(f" - {item.name} (ID: {item.id})") # User's hot 10 games print("Hot 10 Games:") for item in user.hot10: print(f" - {item.name} (ID: {item.id})") # Customize what data to fetch user = bgg.user( "username_here", buddies=True, guilds=True, hot=True, top=True, domain=BGGRestrictDomainTo.BOARD_GAME # or RPG, VIDEO_GAME ) ``` -------------------------------- ### Retrieve User Details Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Fetches comprehensive profile information for a BGG user, including buddies, guilds, and top/hot lists. ```python from boardgamegeek import BGGClient bgg = BGGClient() user_profile = bgg.user(name="username") ``` -------------------------------- ### Fetch Game Information by ID Source: https://context7.com/sukicz/boardgamegeek/llms.txt Retrieve detailed game data using a unique BGG ID. This method supports fetching additional data points such as versions, videos, comments, and marketplace listings. ```python from boardgamegeek import BGGClient bgg = BGGClient("your_access_token_here") # Basic fetch by ID game = bgg.game(game_id=13) # Catan's ID # Fetch with additional data game = bgg.game( game_id=174430, # Gloomhaven versions=True, # Include version/edition info videos=True, # Include video links comments=True, # Include user comments marketplace=True, # Include marketplace listings historical=True # Include historical data ) # Access versions for version in game.versions: print(f"Version: {version.name}") print(f" Language: {version.language}") print(f" Publisher: {version.publisher}") print(f" Year: {version.year}") # Access videos for video in game.videos: print(f"Video: {video.name}") print(f" Link: {video.link}") print(f" Category: {video.category}") print(f" Uploader: {video.uploader}") # Access comments for comment in game.comments[:5]: # First 5 comments print(f"{comment.commenter} (Rating: {comment.rating})") print(f" {comment.comment[:100]}...") ``` -------------------------------- ### Search for Games Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Performs a search query against the BGG database. Returns a list of search results matching the provided query string. ```python from boardgamegeek import BGGClient bgg = BGGClient() results = bgg.search(query="Catan", exact=False) ``` -------------------------------- ### Error Handling Source: https://context7.com/sukicz/boardgamegeek/llms.txt Details on the specific exception types provided by the library for handling various API and value errors. ```APIDOC ## Error Handling ### Description The BoardGameGeek client library provides specific exception types to help you gracefully handle different error scenarios, from item not found to API-level issues like timeouts or rate limiting. ### Exception Types - **BGGError**: Base exception for all library-specific errors. - **BGGValueError**: Raised when an invalid parameter value is provided. - **BGGItemNotFoundError**: Raised when a requested item (e.g., game, user) does not exist on BoardGameGeek. - **BGGApiError**: Base exception for errors returned by the BoardGameGeek API. - **BGGApiRetryError**: Raised when the API indicates that the request should be retried (e.g., due to rate limiting). - **BGGApiTimeoutError**: Raised when the request to the API times out. ### Request Example ```python from boardgamegeek import ( BGGClient, BGGError, BGGValueError, BGGItemNotFoundError, BGGApiError, BGGApiRetryError, BGGApiTimeoutError, ) bgg = BGGClient("your_access_token_here") try: game = bgg.game("NonexistentGameXYZ123") except BGGItemNotFoundError: print("Game not found on BoardGameGeek") except BGGValueError as e: print(f"Invalid parameter: {e}") except BGGApiTimeoutError: print("Request timed out - try again later") except BGGApiRetryError: print("API requested retry - too many requests") except BGGApiError as e: print(f"API error: {e}") except BGGError as e: print(f"General BGG error: {e}") # Validate parameters before calling try: # guild_id must be an integer guild = bgg.guild(guild_id="invalid") except BGGValueError: print("Invalid guild ID provided") # Handle collection for non-existent user try: collection = bgg.collection("") except BGGValueError: print("Username cannot be empty") ``` ### Response #### Error Responses - **BGGItemNotFoundError**: Indicates the requested item could not be found. - **BGGValueError**: Indicates a problem with the input parameters provided. - **BGGApiTimeoutError**: Indicates the API request took too long to complete. - **BGGApiRetryError**: Indicates the API suggested retrying the request. - **BGGApiError**: Catches general API communication issues. - **BGGError**: Catches any other library-specific errors. ``` -------------------------------- ### Guild Information API Source: https://context7.com/sukicz/boardgamegeek/llms.txt Retrieve detailed information about a specific BoardGameGeek guild, including its members. ```APIDOC ## Guild Information API ### Description This API allows you to fetch detailed information about a specific BoardGameGeek guild. You can retrieve general information, location details, and a list of its members. The `members` parameter can be set to `False` for a faster retrieval of guild info only. ### Method GET ### Endpoint `/guild` (This is a conceptual endpoint; actual implementation is via the `bgg.guild` method) ### Parameters #### Query Parameters - **guild_id** (integer) - Required - The unique identifier for the guild. - **members** (boolean) - Optional - If `True` (default), fetch guild members. If `False`, only fetch guild information. ### Request Example ```python from boardgamegeek import BGGClient bgg = BGGClient("your_access_token_here") # Get guild information with members guild = bgg.guild(guild_id=1229) # Get guild without fetching members (faster) guild_info_only = bgg.guild(guild_id=1229, members=False) ``` ### Response #### Success Response (200) - **Guild Object**: Contains details such as guild name, ID, category, manager, website, description, location (country, state, city, address, postal code), member count, and a list of members. #### Response Example ```json { "id": "1229", "name": "The Dice Tower", "category": "General", "manager": "Geoff", "website": "http://www.dicetower.com", "description": "A guild for fans of The Dice Tower.", "country": "USA", "state": "FL", "city": "Orlando", "address": "", "postalcode": "", "members_count": 500, "members": [ "user1", "user2", "..." ] } ``` ``` -------------------------------- ### Play Sessions API Source: https://context7.com/sukicz/boardgamegeek/llms.txt Retrieve play history for a user, optionally filtered by game, date range, or game type (expansions). ```APIDOC ## Play Sessions API ### Description This API allows you to fetch a user's play session history. You can retrieve all plays for a user, filter plays for a specific game, specify a date range, or filter by game subtype (e.g., expansions). ### Method GET ### Endpoint `/plays` (This is a conceptual endpoint; actual implementation is via the `bgg.plays` method) ### Parameters #### Query Parameters - **name** (string) - Optional - The username of the BGG user. - **game_id** (integer) - Optional - Filter plays for a specific game ID. - **min_date** (date) - Optional - Filter plays on or after this date. - **max_date** (date) - Optional - Filter plays on or before this date. - **subtype** (string) - Optional - Filter by game subtype (e.g., `BOARD_GAME_EXTENSION`). ### Request Example ```python from boardgamegeek import BGGClient, BGGRestrictPlaysTo import datetime bgg = BGGClient("your_access_token_here") # Get all plays for a user plays = bgg.plays(name="username_here") # Get plays for a specific game game_plays = bgg.plays(game_id=174430) # Gloomhaven plays # Filter by date range plays_2024 = bgg.plays( name="username_here", min_date=datetime.date(2024, 1, 1), max_date=datetime.date(2024, 12, 31) ) # Filter by game type expansion_plays = bgg.plays( name="username_here", subtype=BGGRestrictPlaysTo.BOARD_GAME_EXTENSION ) ``` ### Response #### Success Response (200) - **plays_count** (integer) - The total number of plays recorded. - **plays** (array) - A list of play session objects, each containing details like play ID, game name, date, quantity, duration, players, etc. #### Response Example ```json { "plays_count": 150, "plays": [ { "id": 12345, "game_name": "Gloomhaven", "game_id": "174430", "date": "2024-05-15", "quantity": 1, "duration": 120, "location": "Home", "incomplete": false, "comment": "First session.", "players": [ { "name": "Player One", "username": "user1", "score": 50, "win": true, "color": "Blue" } ] } ] } ``` ``` -------------------------------- ### Access Guild Information Source: https://context7.com/sukicz/boardgamegeek/llms.txt Retrieves details about a specific BGG guild, including member lists and location data. Includes an option to disable member fetching for faster performance. ```python guild = bgg.guild(guild_id=1229) print(f"Guild: {guild.name}, Members: {guild.members_count}") # Faster fetch without members guild_info_only = bgg.guild(guild_id=1229, members=False) ``` -------------------------------- ### Manage Collection Objects Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Handles collection data structures, allowing for the initialization of a collection object and the addition of game data dictionaries. ```python from boardgamegeek.objects.collection import Collection collection = Collection(data={}) collection.add_game(game={"id": 123, "name": "Example Game"}) ``` -------------------------------- ### DictObject Class Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md A simple wrapper around a dictionary to provide attribute-like access to its data. ```APIDOC ## `boardgamegeek.utils.DictObject` ### Description Just a fancy wrapper over a dictionary. ### Methods #### `data()` Access to the internal data dictionary, for easy dumping. * **Returns:** dict[str, Any] - The internal data dictionary. ``` -------------------------------- ### Retrieve Hot Items Source: https://context7.com/sukicz/boardgamegeek/llms.txt Fetches current trending items from BGG across various categories like board games, RPGs, and companies. ```python hot_games = bgg.hot_items("boardgame") for item in hot_games: print(f"Rank #{item.rank}: {item.name}") hot_rpgs = bgg.hot_items("rpg") hot_designers = bgg.hot_items("boardgameperson") ``` -------------------------------- ### Retrieve User's Game Collection (Python) Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md Fetches a user's game collection from BoardGameGeek. Supports filtering by various criteria such as subtype, ownership, ratings, play counts, and modification date. Requires a valid username and can return a Collection object or None. Raises exceptions for invalid parameters or API issues. ```python from boardgamegeek import BGGClient bgg = BGGClient() user_name = "your_username" try: collection = bgg.collection(user_name=user_name, own=True, rated=True) for item in collection: print(f"Game: {item.name}, Rating: {item.rating}") except Exception as e: print(f"An error occurred: {e}") ``` -------------------------------- ### BoardGameGeek Guild Object Properties Source: https://github.com/sukicz/boardgamegeek/blob/master/docs/modules.md This snippet outlines the properties of the Guild class, which holds information about a BoardGameGeek guild. It includes address details (addr1, addr2, address, city, country, postalcode, state), category, description, manager, members, members_count, and website. These properties return strings, integers, or sets, with None indicating unavailable data. ```python class Guild: @property def addr1(self) -> str | None: """Returns the first field of the address.""" # ... implementation ... return None @property def addr2(self) -> str | None: """Returns the second field of the address.""" # ... implementation ... return None @property def address(self) -> str | None: """Returns the address (both fields concatenated).""" # ... implementation ... return None @property def category(self) -> str | None: """Returns the category.""" # ... implementation ... return None @property def city(self) -> str | None: """Returns the city.""" # ... implementation ... return None @property def country(self) -> str | None: """Returns the country.""" # ... implementation ... return None @property def description(self) -> str | None: """Returns the description.""" # ... implementation ... return None @property def manager(self) -> str | None: """Returns the manager.""" # ... implementation ... return None @property def members(self) -> set[str]: """Returns the members of the guild.""" # ... implementation ... return set() @property def members_count(self) -> int: """Returns the number of members, as reported by the server.""" # ... implementation ... return 0 @property def postalcode(self) -> int | None: """Returns the postal code.""" # ... implementation ... return None @property def state(self) -> str | None: """Returns the state or province.""" # ... implementation ... return None @property def website(self) -> str | None: """Returns the website address.""" # ... implementation ... return None ```