kemoverse/bot/add_character.py
2025-06-01 12:24:53 +01:00

65 lines
1.9 KiB
Python

import requests
from misskey.exceptions import MisskeyAPIException
from client import client_connection
from db_utils import insert_character
from custom_types import Character
def add_character(
name: str,
rarity: int,
weight: float,
image_url: str) -> tuple[int, str]:
'''
Adds a character to the database, uploading the image from a public URL to
the bot's Misskey Drive.
Args:
name (str): Character name.
rarity (int): Character rarity (e.g., 1-5).
weight (float): Pull weight (e.g., 0.02).
image_url (str): Public URL of the image from the post (e.g., from
note['files'][i]['url']).
Returns:
tuple[int, str]: Character 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('Character name cannot be empty.')
if rarity < 1:
raise ValueError('Rarity must be a positive integer.')
if weight <= 0:
raise ValueError('Weight must be a positive number.')
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
character_id = insert_character(
stripped_name,
rarity,
float(weight),
file_id
)
return character_id, file_id