import requests from misskey.exceptions import MisskeyAPIException from client import client_connection from db_utils import insert_card from custom_types import Card from config import RARITY_TO_WEIGHT def add_card( name: str, rarity: int, image_url: str) -> tuple[int, str]: ''' Adds a card to the database, uploading the image from a public URL to the bot's Misskey Drive. Args: name (str): Card name. rarity (int): Card rarity (e.g., 1-5). image_url (str): Public URL of the image from the post (e.g., from note['files'][i]['url']). Returns: tuple[int, str]: Card ID and bot's Drive file_id. Raises: ValueError: If inputs are invalid. RuntimeError: If image download/upload or database operation fails. ''' stripped_name = name.strip() # Validate inputs if not stripped_name: raise ValueError('Card name cannot be empty.') if rarity < 1: raise ValueError('Rarity must be a positive integer.') if rarity not in RARITY_TO_WEIGHT.keys(): raise ValueError(f'Invalid rarity: {rarity}') if not image_url: raise ValueError('Image URL must be provided.') # Download image response = requests.get(image_url, stream=True, timeout=30) if response.status_code != 200: raise RuntimeError(f'Failed to download image from {image_url}') # Upload to bot's Drive mk = client_connection() try: media = mk.drive_files_create(response.raw) file_id = media['id'] except MisskeyAPIException as e: raise RuntimeError(f'Failed to upload image to bot\'s Drive: {e}')\ from e # Insert into database card_id = insert_card( stripped_name, rarity, RARITY_TO_WEIGHT[rarity], file_id ) return card_id, file_id