### Serve Documentation Source: https://github.com/tr4nt0r/habiticalib/blob/main/CONTRIBUTING.md Command to start the local Mkdocs development server. ```bash hatch run docs-serve ``` -------------------------------- ### Install Habiticalib using pip Source: https://github.com/tr4nt0r/habiticalib/blob/main/README.md Install the habiticalib package using pip. This command fetches and installs the latest version from PyPI. ```bash pip install habiticalib ``` -------------------------------- ### Basic Habiticalib Usage Example Source: https://github.com/tr4nt0r/habiticalib/blob/main/README.md Demonstrates basic asynchronous usage of the Habiticalib library. It shows how to log in, fetch user data, and retrieve different types of tasks. Ensure you have an active aiohttp ClientSession. ```python import asyncio from aiohttp import ClientSession from habiticalib import Habitica, TaskType async def main(): async with ClientSession() as session: habitica = Habitica(session) # Login to Habitica habitica.login(username="your_username", password="your_password") # Fetch user data user_data = await habitica.user() print(f"Your current health: {user_data.stats.hp}") # Fetch all tasks (to-dos, dailies, habits, and rewards) tasks = await habitica.get_tasks() print("All tasks:") for task in tasks: print(f"- {task.text} (type: {task.type})") # Fetch only to-dos todos = await habitica.get_tasks(task_type=TaskType.TODO) print("\nTo-Do tasks:") for todo in todos: print(f"- {todo.text} (due: {todo.date})") # Fetch only dailies dailies = await habitica.tasks(task_type=TaskType.DAILY) print("Dailies:") for daily in dailies: print(f"- {daily.text}") asyncio.run(main()) ``` -------------------------------- ### Manage Habitica Quests with Python Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Use this snippet to manage party quests, including inviting members, accepting/rejecting invitations, starting, aborting, and leaving quests. Ensure you have the correct API credentials and group IDs. ```python import asyncio from uuid import UUID from habiticalib import Habitica, NotFoundError, NotAuthorizedError async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: try: # Invite party members to a quest response = await habitica.invite_quest(quest_key="dilatory_derby") print(f"Quest invited: {response.data.key}") print(f"Quest leader: {response.data.leader}") # Accept a pending quest invitation response = await habitica.accept_quest() print(f"Accepted quest: {response.data.key}") # Reject a pending quest invitation response = await habitica.reject_quest() print("Quest invitation rejected") # Force-start a quest (skips pending invitations) response = await habitica.start_quest() print(f"Quest started: {response.data.active}") # Cancel a pending quest (before it starts) response = await habitica.cancel_quest() print("Pending quest cancelled, scroll returned") # Abort an active quest (progress is lost) response = await habitica.abort_quest() print("Quest aborted, scroll returned to leader") # Leave a quest (stop participating) response = await habitica.leave_quest() print("Left the quest") # Quest operations on a specific group group_id = UUID("group-uuid") response = await habitica.invite_quest( group_id, quest_key="golden_knight" ) except NotFoundError as e: print(f"Quest/group not found: {e.error.message}") except NotAuthorizedError as e: print(f"Not authorized: {e.error.message}") asyncio.run(main()) ``` -------------------------------- ### Handle Habitica API Errors with Python Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Implement robust error handling for API requests using typed exceptions. This example shows how to catch specific errors like authentication failures, resource not found, bad requests, and rate limiting, including retry logic for rate-limited requests. ```python import asyncio from habiticalib import ( Habitica, NotAuthorizedError, NotFoundError, BadRequestError, TooManyRequestsError ) async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: try: user = await habitica.get_user() except NotAuthorizedError as e: print(f"Authentication failed: {e.error.message}") print(f"Rate limit: {e.rate_limit_remaining}/{e.rate_limit}") except NotFoundError as e: print(f"Resource not found: {e.error.message}") except BadRequestError as e: print(f"Invalid request: {e.error.message}") except TooManyRequestsError as e: print(f"Rate limited! Retry after {e.retry_after} seconds") print(f"Rate limit resets at: {e.rate_limit_reset}") await asyncio.sleep(e.retry_after) # Retry the request user = await habitica.get_user() asyncio.run(main()) ``` -------------------------------- ### Task Management - Get Tasks Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Retrieve the authenticated user's tasks with optional filtering by task type and due date calculation. ```APIDOC ## Task Management - Get Tasks ### Description Retrieve the authenticated user's tasks with optional filtering by task type and due date calculation. ### Method GET ### Endpoint /tasks ### Parameters #### Query Parameters - **type** (string) - Optional. Filter tasks by type (habits, dailies, todos, completedTodos). - **startDate** (string) - Optional. Filter tasks by start date. - **endDate** (string) - Optional. Filter tasks by end date. - **due** (string) - Optional. Filter tasks by due date (e.g., 'today', 'tomorrow', '2024-12-25'). ### Request Example None ### Response #### Success Response (200) - **data** (array) - A list of tasks matching the filter criteria. - **Type** (string) - The type of the task (habit, daily, todo, completedTodo). - **text** (string) - The text of the task. - **value** (number) - The value of the task (for todos). - **counterUp** (integer) - For habits, the number of positive completions. - **counterDown** (integer) - For habits, the number of negative completions. - **completed** (boolean) - For dailies, indicates if the task is completed. - **date** (string) - For todos, the due date. #### Response Example ```json { "success": true, "data": [ { "_id": "task1_id", "text": "Exercise", "Type": "habit", "counterUp": 5, "counterDown": 0 }, { "_id": "task2_id", "text": "Pay bills", "Type": "daily", "completed": false }, { "_id": "task3_id", "text": "Buy groceries", "Type": "todo", "date": "2024-12-20" } ] } ``` ``` -------------------------------- ### Task Management - Get Single Task Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Retrieve a specific task by its UUID. ```APIDOC ## Task Management - Get Single Task ### Description Retrieve a specific task by its UUID. ### Method GET ### Endpoint /tasks/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The UUID of the task to retrieve. ### Request Example None ### Response #### Success Response (200) - **_id** (string) - The unique identifier of the task. - **text** (string) - The text of the task. - **Type** (string) - The type of the task (habit, daily, todo). - **notes** (string) - Additional notes for the task. - **value** (number) - The value of the task (for todos). - **createdAt** (string) - The date and time the task was created. - **tags** (array) - A list of tags associated with the task. #### Response Example ```json { "success": true, "data": { "_id": "12345678-1234-5678-1234-567812345678", "text": "Read a book", "Type": "todo", "notes": "Read at least 30 minutes.", "value": 1, "createdAt": "2024-01-15T10:00:00.000Z", "tags": ["reading", "personal"] } } ``` ``` -------------------------------- ### Create Habitica Tasks Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Demonstrates creating different task types including to-dos, habits, dailies with recurrence, and rewards using the Habitica client. ```python import asyncio from datetime import datetime, date from uuid import UUID from habiticalib import ( Habitica, Task, TaskType, TaskPriority, Attributes, Frequency, Repeat, Checklist, Reminders ) async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Create a simple to-do todo: Task = { "type": TaskType.TODO, "text": "Complete project report", "notes": "Include quarterly metrics", "priority": TaskPriority.HARD, "date": date(2024, 12, 31), } response = await habitica.create_task(todo) print(f"Created to-do: {response.data.id}") # Create a habit habit: Task = { "type": TaskType.HABIT, "text": "Drink water", "notes": "Stay hydrated!", "up": True, "down": False, "priority": TaskPriority.EASY, "attribute": Attributes.CON, } response = await habitica.create_task(habit) print(f"Created habit: {response.data.id}") # Create a daily with recurrence daily: Task = { "type": TaskType.DAILY, "text": "Morning exercise", "notes": "30 minutes workout", "priority": TaskPriority.MEDIUM, "attribute": Attributes.STR, "frequency": Frequency.WEEKLY, "repeat": Repeat(m=True, w=True, f=True), # Mon, Wed, Fri "startDate": date.today(), "checklist": [ Checklist(id=UUID("00000000-0000-0000-0000-000000000001"), text="Warm-up", completed=False), Checklist(id=UUID("00000000-0000-0000-0000-000000000002"), text="Main workout", completed=False), Checklist(id=UUID("00000000-0000-0000-0000-000000000003"), text="Cool-down", completed=False), ], } response = await habitica.create_task(daily) print(f"Created daily: {response.data.id}") # Create a reward reward: Task = { "type": TaskType.REWARD, "text": "Watch an episode", "notes": "Reward yourself!", "value": 20, # Cost in gold } response = await habitica.create_task(reward) print(f"Created reward: {response.data.id}") asyncio.run(main()) ``` -------------------------------- ### Initialize Habitica Client Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Initialize the Habitica client using an existing session, a managed session, or a custom API URL. ```python import asyncio from aiohttp import ClientSession from habiticalib import Habitica async def main(): # Method 1: Using context manager with existing session async with ClientSession() as session: habitica = Habitica( session=session, api_user="your-user-id", api_key="your-api-token" ) user = await habitica.get_user() print(f"Username: {user.data.auth.local.username}") # Method 2: Let Habitica manage its own session async with Habitica(api_user="user-id", api_key="api-token") as habitica: user = await habitica.get_user() print(f"HP: {user.data.stats.hp}") # Method 3: Custom API URL (for self-hosted instances) habitica = Habitica( api_user="user-id", api_key="api-token", url="https://my-habitica-server.com/" ) asyncio.run(main()) ``` -------------------------------- ### Run Tests and Linting Source: https://github.com/tr4nt0r/habiticalib/blob/main/CONTRIBUTING.md Commands to execute the test suite and run linting/type checking using Hatch. ```bash hatch run test ``` ```bash hatch run lint ``` -------------------------------- ### Clone and Branch Repository Source: https://github.com/tr4nt0r/habiticalib/blob/main/CONTRIBUTING.md Commands to clone a fork of the repository and create a new local development branch. ```bash git clone git@github.com:yourusername/habiticalib.git ``` ```bash git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Allocate Stat Points in Python Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Use these methods to distribute stat points individually, automatically, or in bulk to character attributes. ```python import asyncio from habiticalib import Habitica, Attributes async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Allocate a single point to Intelligence response = await habitica.allocate_single_stat_point(Attributes.INT) print(f"New INT: {response.data.Int}") # Allocate a single point to Strength (default) response = await habitica.allocate_single_stat_point() print(f"New STR: {response.data.Str}") # Auto-allocate all available points using user's preferred method response = await habitica.allocate_stat_points() print(f"Stats after auto-allocation:") print(f" STR: {response.data.Str}") print(f" INT: {response.data.Int}") print(f" CON: {response.data.con}") print(f" PER: {response.data.per}") # Bulk allocate specific amounts to each stat response = await habitica.allocate_bulk_stat_points( int_points=5, str_points=3, con_points=2, per_points=0 ) print(f"Remaining points: {response.data.points}") asyncio.run(main()) ``` -------------------------------- ### Manage Habitica Webhooks Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Create, update, and delete webhooks for task, user, quest, and group chat events. Requires an active Habitica client session. ```python import asyncio from uuid import UUID from habiticalib import ( Habitica, TaskActivity, TaskActivityOptions, UserActivity, UserActivityOptions, QuestActivity, QuestActivityOptions, GroupChatReceived, GlobalActivity ) async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Create a task activity webhook task_webhook = TaskActivity( url="https://my-server.com/habitica/tasks", label="My Task Webhook", enabled=True, options=TaskActivityOptions( scored=True, created=True, updated=True, deleted=True, checklistScored=True ) ) response = await habitica.create_webhook(task_webhook) webhook_id = response.data.id print(f"Created webhook: {webhook_id}") # Create a user activity webhook (pet/mount/levelup) user_webhook = UserActivity( url="https://my-server.com/habitica/user", label="User Events", enabled=True, options=UserActivityOptions( petHatched=True, mountRaised=True, leveledUp=True ) ) response = await habitica.create_webhook(user_webhook) # Create a quest activity webhook quest_webhook = QuestActivity( url="https://my-server.com/habitica/quests", label="Quest Events", enabled=True, options=QuestActivityOptions( questStarted=True, questFinished=True, questInvited=True ) ) response = await habitica.create_webhook(quest_webhook) # Create a group chat webhook (for a specific group) chat_webhook = GroupChatReceived( groupId=UUID("party-or-guild-uuid"), url="https://my-server.com/habitica/chat", label="Party Chat", enabled=True ) response = await habitica.create_webhook(chat_webhook) # Create a global activity webhook (receives ALL events) global_webhook = GlobalActivity( url="https://my-server.com/habitica/all", label="All Events", enabled=True ) response = await habitica.create_webhook(global_webhook) # Update a webhook task_webhook.id = webhook_id task_webhook.enabled = False response = await habitica.update_webhook(task_webhook) print(f"Webhook disabled: {not response.data.enabled}") # Delete a webhook response = await habitica.delete_webhook(webhook_id) print(f"Remaining webhooks: {len(response.data)}") asyncio.run(main()) ``` -------------------------------- ### Bump Project Version Source: https://github.com/tr4nt0r/habiticalib/blob/main/CONTRIBUTING.md Commands to increment the project version for patch, minor, or major releases. ```bash hatch version patch ``` ```bash hatch version minor ``` ```bash hatch version major ``` -------------------------------- ### Manage Character Classes in Python Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Methods for switching between character classes and disabling the class system, wrapped in error handling for authorization issues. ```python import asyncio from habiticalib import Habitica, HabiticaClass, NotAuthorizedError async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: try: # Change to Warrior class response = await habitica.change_class(HabiticaClass.WARRIOR) print(f"Changed to: {response.data.stats.Class}") print(f"New stats: STR={response.data.stats.Str}") # Change to Mage class response = await habitica.change_class(HabiticaClass.MAGE) print(f"Changed to: {response.data.stats.Class}") # Change to Healer class response = await habitica.change_class(HabiticaClass.HEALER) # Change to Rogue class response = await habitica.change_class(HabiticaClass.ROGUE) except NotAuthorizedError as e: print(f"Cannot change class: {e.error.message}") # Disable class system entirely response = await habitica.disable_classes() print(f"Class system disabled: {response.data.preferences.disableClasses}") asyncio.run(main()) ``` -------------------------------- ### Authenticate User via Login Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Authenticate using credentials to automatically update client headers for subsequent requests. ```python import asyncio from habiticalib import Habitica, NotAuthorizedError async def main(): async with Habitica() as habitica: try: response = await habitica.login( username="your_username_or_email", password="your_password" ) print(f"User ID: {response.data.id}") print(f"API Token: {response.data.apiToken}") print(f"Username: {response.data.username}") print(f"New User: {response.data.newUser}") # After login, the client is authenticated for subsequent calls user = await habitica.get_user() print(f"Level: {user.data.stats.lvl}") except NotAuthorizedError as e: print(f"Login failed: {e.error.message}") asyncio.run(main()) ``` -------------------------------- ### Fetch User Data Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Retrieve user profile information with support for optional field filtering to improve efficiency. ```python import asyncio from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Fetch full user profile user = await habitica.get_user() print(f"Username: {user.data.auth.local.username}") print(f"HP: {user.data.stats.hp}/{user.data.stats.maxHealth}") print(f"MP: {user.data.stats.mp}/{user.data.stats.maxMP}") print(f"Gold: {user.data.stats.gp:.2f}") print(f"Level: {user.data.stats.lvl}") print(f"Class: {user.data.stats.Class}") print(f"Experience: {user.data.stats.exp}/{user.data.stats.toNextLevel}") # Fetch specific fields only (more efficient) response = await habitica.get_user(user_fields=["stats", "items.currentPet"]) print(f"Current Pet: {response.data.items.currentPet}") # Fetch multiple specific fields response = await habitica.get_user( user_fields="achievements,items.mounts,preferences.background" ) print(f"Streak: {response.data.achievements.streak}") asyncio.run(main()) ``` -------------------------------- ### Manage Tags with Habitica API (CRUD) Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Perform create, retrieve, update, delete, and reorder operations on tags. Tags are used for organizing tasks. Requires tag IDs for specific operations. ```python import asyncio from uuid import UUID from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Get all tags response = await habitica.get_tags() for tag in response.data: print(f"Tag: {tag.name} (ID: {tag.id})") # Get a specific tag tag_id = UUID("12345678-1234-5678-1234-567812345678") response = await habitica.get_tag(tag_id) print(f"Tag name: {response.data.name}") # Create a new tag response = await habitica.create_tag("Work Tasks") new_tag_id = response.data.id print(f"Created tag with ID: {new_tag_id}") # Update a tag name response = await habitica.update_tag(new_tag_id, "Office Tasks") print(f"Updated tag name: {response.data.name}") # Reorder a tag (move to position 0 = top) response = await habitica.reorder_tag(new_tag_id, 0) # Delete a tag response = await habitica.delete_tag(new_tag_id) if response.success: print("Tag deleted successfully") asyncio.run(main()) ``` -------------------------------- ### Manage Health and Sleep with Habitica API Source: https://context7.com/tr4nt0r/habiticalib/llms.txt This snippet demonstrates how to purchase health potions, toggle sleep mode to pause damage from dailies, and revive from death using the Habitica API. It includes error handling for authorization issues. ```python import asyncio from habiticalib import Habitica, NotAuthorizedError async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Buy a health potion (costs 25 gold, heals 15 HP) try: response = await habitica.buy_health_potion() print(f"New HP: {response.data.hp}") print(f"Remaining gold: {response.data.gp:.2f}") except NotAuthorizedError as e: print(f"Cannot buy potion: {e.error.message}") # Toggle sleep mode (rest in the inn - pauses damage from dailies) response = await habitica.toggle_sleep() if response.data: print("Now sleeping - damage paused") else: print("Woke up - damage resumed") # Revive from death (when HP reaches 0) try: response = await habitica.revive() print("Revived successfully!") except NotAuthorizedError as e: print(f"Cannot revive: {e.error.message}") asyncio.run(main()) ``` -------------------------------- ### Export Habitica User Data with Python Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Use this snippet to export all user data, including tasks, settings, and profile details. Note that this uses a private API and may be subject to change. ```python import asyncio import json from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Export user data (private API - may change) export = await habitica.get_user_export() print(f"Username: {export.auth.local.username}") print(f"Total habits: {len(export.tasks.habits)}") print(f"Total dailies: {len(export.tasks.dailys)}") print(f"Total todos: {len(export.tasks.todos)}") print(f"Total rewards: {len(export.tasks.rewards)}") # Access all user data print(f"Level: {export.stats.lvl}") print(f"Gold: {export.stats.gp:.2f}") asyncio.run(main()) ``` -------------------------------- ### Trigger Daily Reset with Habitica API Source: https://context7.com/tr4nt0r/habiticalib/llms.txt This code snippet shows how to trigger the daily reset process using the Habitica API. This action applies damage for incomplete dailies and resets daily completion status. ```python import asyncio from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Run cron to apply daily reset response = await habitica.run_cron() if response.success: print("Cron executed - dailies reset and damage applied") asyncio.run(main()) ``` -------------------------------- ### Manage Party and Group Interactions Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Retrieve group information, list members, and send messages to parties, guilds, or individual users. ```python import asyncio from uuid import UUID from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Get party information party = await habitica.get_group() print(f"Party name: {party.data.name}") print(f"Member count: {party.data.memberCount}") print(f"Leader: {party.data.leader.profile.name}") # Get specific group by ID group_id = UUID("guild-or-group-uuid") group = await habitica.get_group(group_id) print(f"Group: {group.data.name}") # Get party members (with automatic pagination) members = await habitica.get_group_members(limit=30) for member in members.data: print(f"Member: {member.profile.name} - Level {member.stats.lvl}") # Get members with full public fields members = await habitica.get_group_members( public_fields=True, tasks=True # Include member tasks ) # Send message to party chat response = await habitica.send_group_message("Hello party members!") print(f"Message sent: {response.data.message.text}") # Send message to specific group response = await habitica.send_group_message( "Hello guild!", group_id=UUID("guild-uuid") ) # Send private message to a user response = await habitica.send_private_message( "Hello friend!", to_user_id=UUID("target-user-uuid") ) asyncio.run(main()) ``` -------------------------------- ### Fetch Habitica Game Content Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Retrieves Habitica's game content, including equipment, pets, and quests. Supports fetching content in different languages. ```python import asyncio from habiticalib import Habitica, Language async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Get content in English (default) content = await habitica.get_content() # List available quests for key, quest in content.data.quests.items(): print(f"Quest: {quest.text} - {quest.notes[:50]}...") # Get equipment info gear = content.data.gear.flat for key, item in list(gear.items())[:5]: print(f"Gear: {item.text} - STR: {item.Str}, INT: {item.Int}") # Get content in German content_de = await habitica.get_content(language=Language.DE) # Get content in other languages content_fr = await habitica.get_content(language=Language.FR) content_ja = await habitica.get_content(language=Language.JA) content_es = await habitica.get_content(language=Language.ES) asyncio.run(main()) ``` -------------------------------- ### Tag Management API Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Create, retrieve, update, delete, and reorder tags for organizing tasks. ```APIDOC ## Tag Management Operations ### Description Perform CRUD operations and reordering on task tags. ### Endpoints - GET /tags: Retrieve all tags. - GET /tags/:tagId: Retrieve a specific tag. - POST /tags: Create a new tag. - PUT /tags/:tagId: Update a tag name. - POST /tags/:tagId/move/:position: Reorder a tag. - DELETE /tags/:tagId: Delete a tag. ``` -------------------------------- ### Retrieve and Filter Tasks Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Fetches tasks with optional filtering by type and due date. Uses the TaskFilter enum for specific task categories. ```python import asyncio from datetime import datetime from habiticalib import Habitica, TaskFilter async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Get all tasks (excludes completed to-dos by default) all_tasks = await habitica.get_tasks() for task in all_tasks.data: print(f"{task.Type}: {task.text} (value: {task.value})") # Get only habits habits = await habitica.get_tasks(task_type=TaskFilter.HABITS) for habit in habits.data: print(f"Habit: {habit.text} (+{habit.counterUp}/-{habit.counterDown})") # Get only dailies dailies = await habitica.get_tasks(task_type=TaskFilter.DAILYS) for daily in dailies.data: print(f"Daily: {daily.text} - Completed: {daily.completed}") # Get only to-dos todos = await habitica.get_tasks(task_type=TaskFilter.TODOS) for todo in todos.data: print(f"To-Do: {todo.text} - Due: {todo.date}") # Get completed to-dos completed = await habitica.get_tasks(task_type=TaskFilter.COMPLETED_TODOS) print(f"Completed to-dos: {len(completed.data)}") # Get tasks with specific due date for nextDue calculation tasks = await habitica.get_tasks( task_type=TaskFilter.DAILYS, due_date=datetime(2024, 12, 25) ) asyncio.run(main()) ``` -------------------------------- ### Retrieve Single Task by UUID Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Fetches details for a specific task using its unique identifier. Requires the uuid module. ```python import asyncio from uuid import UUID from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: task_id = UUID("12345678-1234-5678-1234-567812345678") response = await habitica.get_task(task_id) task = response.data print(f"Task: {task.text}") print(f"Type: {task.Type}") print(f"Notes: {task.notes}") print(f"Value: {task.value}") print(f"Created: {task.createdAt}") print(f"Tags: {task.tags}") asyncio.run(main()) ``` -------------------------------- ### Reorder Task Position with Habitica API Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Move a task to a new position within its category list. Positions are zero-indexed, with -1 indicating the bottom of the list. ```python import asyncio from uuid import UUID from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: task_id = UUID("12345678-1234-5678-1234-567812345678") # Move task to top (position 0) response = await habitica.reorder_task(task_id, 0) print(f"New task order: {response.data}") # Move task to bottom (position -1) response = await habitica.reorder_task(task_id, -1) # Move task to specific position response = await habitica.reorder_task(task_id, 3) asyncio.run(main()) ``` -------------------------------- ### Cast Skills and Spells with Habitica API Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Use this snippet to cast various class skills and transformation spells. It supports targeting tasks, users, or the party, and includes error handling for insufficient mana and not found targets. ```python import asyncio from uuid import UUID from habiticalib import Habitica, Skill, NotAuthorizedError, NotFoundError async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: try: # Warrior skills response = await habitica.cast_skill(Skill.BRUTAL_SMASH, target_id=UUID("task-uuid-here")) # Target a task print(f"Dealt damage! MP remaining: {response.data.user.stats.mp}") response = await habitica.cast_skill(Skill.DEFENSIVE_STANCE) response = await habitica.cast_skill(Skill.VALOROUS_PRESENCE) # Party buff response = await habitica.cast_skill(Skill.INTIMIDATING_GAZE) # Party buff # Mage skills response = await habitica.cast_skill(Skill.BURST_OF_FLAMES, target_id=UUID("task-uuid")) # Target a task response = await habitica.cast_skill(Skill.ETHEREAL_SURGE) # Party MP heal response = await habitica.cast_skill(Skill.EARTHQUAKE) # Party buff response = await habitica.cast_skill(Skill.CHILLING_FROST) # Freeze streaks # Healer skills response = await habitica.cast_skill(Skill.HEALING_LIGHT) # Self heal response = await habitica.cast_skill(Skill.BLESSING) # Party heal response = await habitica.cast_skill(Skill.PROTECTIVE_AURA) # Party buff response = await habitica.cast_skill(Skill.SEARING_BRIGHTNESS, target_id=UUID("task-uuid")) # Target a task # Rogue skills response = await habitica.cast_skill(Skill.PICKPOCKET, target_id=UUID("task-uuid")) # Target a task for gold response = await habitica.cast_skill(Skill.BACKSTAB, target_id=UUID("task-uuid")) # Target a task for XP response = await habitica.cast_skill(Skill.TOOLS_OF_THE_TRADE) # Party buff response = await habitica.cast_skill(Skill.STEALTH) # Avoid dailies # Transformation items (target other users) response = await habitica.cast_skill(Skill.SNOWBALL, target_id=UUID("user-uuid")) response = await habitica.cast_skill(Skill.SPOOKY_SPARKLES, target_id=UUID("user-uuid")) response = await habitica.cast_skill(Skill.SEAFOAM, target_id=UUID("user-uuid")) response = await habitica.cast_skill(Skill.SHINY_SEED, target_id=UUID("user-uuid")) # Debuff potions (remove transformation from self) response = await habitica.cast_skill(Skill.SALT) # Remove snowball response = await habitica.cast_skill(Skill.OPAQUE_POTION) # Remove spooky response = await habitica.cast_skill(Skill.SAND) # Remove seafoam response = await habitica.cast_skill(Skill.PETAL_FREE_POTION) # Remove seed except NotAuthorizedError as e: print(f"Not enough mana: {e.error.message}") except NotFoundError as e: print(f"Target not found: {e.error.message}") asyncio.run(main()) ``` -------------------------------- ### Generate Composite Avatar Image Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Generates a composite avatar image by combining various elements. Supports saving to a file or returning as a bytes buffer. Can also customize avatar data before generation. ```python import asyncio from io import BytesIO from habiticalib import Habitica, extract_avatar async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: # Generate avatar and save to file avatar = await habitica.generate_avatar("avatar.png") print(f"Avatar saved! Class: {avatar.stats.Class}") print(f"Current mount: {avatar.items.currentMount}") print(f"Current pet: {avatar.items.currentPet}") # Generate avatar to bytes buffer (for web use) buffer = BytesIO() avatar = await habitica.generate_avatar(buffer, fmt="png") image_bytes = buffer.getvalue() print(f"Generated {len(image_bytes)} bytes") # Generate avatar using pre-fetched user data user_response = await habitica.get_user( user_fields=["preferences", "items", "stats"] ) avatar_data = extract_avatar(user_response.data) # Customize avatar data before generation avatar_data.preferences.background = "violet" await habitica.generate_avatar("custom_avatar.png", avatar=avatar_data) asyncio.run(main()) ``` -------------------------------- ### DELETE /tasks/user/completed-todos Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Remove all completed to-dos from the user's task list. ```APIDOC ## DELETE /tasks/user/completed-todos ### Description Remove all completed to-dos from the user's task list. ### Method DELETE ### Endpoint /tasks/user/completed-todos ``` -------------------------------- ### Delete Completed To-Dos with Habitica API Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Removes all completed to-dos from the user's task list. This operation is straightforward and requires no task-specific identifiers. ```python import asyncio from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: response = await habitica.delete_completed_todos() if response.success: print("All completed to-dos have been deleted") asyncio.run(main()) ``` -------------------------------- ### Score Task Up or Down with Habitica API Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Use this to score tasks up or down. For habits, this increases positive or negative counters. For dailies and to-dos, this marks them complete or incomplete. For rewards, scoring 'up' purchases the reward. Task aliases can be used instead of UUIDs. ```python import asyncio from uuid import UUID from habiticalib import Habitica, Direction async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: task_id = UUID("12345678-1234-5678-1234-567812345678") # Score task up (complete daily/todo, positive habit, buy reward) response = await habitica.update_score(task_id, Direction.UP) print(f"New HP: {response.data.hp}") print(f"New MP: {response.data.mp}") print(f"New Gold: {response.data.gp:.2f}") print(f"New XP: {response.data.exp}") print(f"Score delta: {response.data.delta}") # Check for item drops if response.data.tmp.drop.key: drop = response.data.tmp.drop print(f"Item dropped: {drop.key} ({drop.Type})") print(f"Message: {drop.dialog}") # Score task down (uncomplete daily/todo, negative habit) response = await habitica.update_score(task_id, Direction.DOWN) print(f"Score delta: {response.data.delta}") # You can also use task alias instead of UUID response = await habitica.update_score("my-task-alias", Direction.UP) asyncio.run(main()) ``` -------------------------------- ### POST /tasks/:taskId/move/:position Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Move a task to a new position in its category list. ```APIDOC ## POST /tasks/:taskId/move/:position ### Description Move a task to a new position in its category list. ### Method POST ### Endpoint /tasks/:taskId/move/:position ### Parameters #### Path Parameters - **taskId** (UUID) - Required - The ID of the task to move. - **position** (integer) - Required - The target index position (0 for top, -1 for bottom). ``` -------------------------------- ### Update Habitica Tasks Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Updates specific attributes of an existing task using its UUID. ```python import asyncio from uuid import UUID from habiticalib import Habitica, Task, TaskPriority async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: task_id = UUID("12345678-1234-5678-1234-567812345678") # Update task properties updated_task: Task = { "text": "Updated task title", "notes": "New detailed notes", "priority": TaskPriority.HARD, } response = await habitica.update_task(task_id, updated_task) print(f"Updated task: {response.data.text}") print(f"New priority: {response.data.priority}") asyncio.run(main()) ``` -------------------------------- ### Fetch Anonymized User Data Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Retrieves user profile and task data while excluding sensitive information. Requires valid API credentials. ```python import asyncio from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: response = await habitica.get_user_anonymized() # Access anonymized user data user = response.data.user print(f"Level: {user.stats.lvl}") print(f"Class: {user.stats.Class}") # Access user's tasks (also anonymized) tasks = response.data.tasks for task in tasks: print(f"Task: {task.text} - Type: {task.Type}") asyncio.run(main()) ``` -------------------------------- ### POST /tasks/:taskId/score/:direction Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Score a task up or down. For habits, this increases positive or negative counters. For dailies and to-dos, this marks them complete or incomplete. For rewards, scoring "up" purchases the reward. ```APIDOC ## POST /tasks/:taskId/score/:direction ### Description Score a task up or down. For habits, this increases positive or negative counters. For dailies and to-dos, this marks them complete or incomplete. For rewards, scoring "up" purchases the reward. ### Method POST ### Endpoint /tasks/:taskId/score/:direction ### Parameters #### Path Parameters - **taskId** (UUID/string) - Required - The ID or alias of the task. - **direction** (string) - Required - The direction to score: "up" or "down". ### Response #### Success Response (200) - **data** (object) - Contains updated user stats (hp, mp, gp, exp), score delta, and potential item drops. ``` -------------------------------- ### Fetching Anonymized User Data Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Retrieve the user's profile data while excluding sensitive and personally identifiable information such as authentication details, profile data, purchased items, contributor information, and webhooks. ```APIDOC ## Fetching Anonymized User Data ### Description Retrieve the user's profile data while excluding sensitive and personally identifiable information such as authentication details, profile data, purchased items, contributor information, and webhooks. ### Method GET ### Endpoint /user/anonymized ### Parameters None ### Request Example None ### Response #### Success Response (200) - **user** (object) - Anonymized user data including stats and tasks. - **stats** (object) - User's statistics. - **lvl** (integer) - User's level. - **Class** (string) - User's class. - **tasks** (array) - Anonymized list of user's tasks. - **text** (string) - The text of the task. - **Type** (string) - The type of the task (e.g., habit, daily, todo). #### Response Example ```json { "success": true, "data": { "user": { "stats": { "lvl": 10, "Class": "Warrior" }, "tasks": [ { "text": "Meditate", "Type": "habit" }, { "text": "Read a book", "Type": "todo" } ] } } } ``` ``` -------------------------------- ### Delete Habitica Tasks Source: https://context7.com/tr4nt0r/habiticalib/llms.txt Removes a task from the user's account by providing its UUID. ```python import asyncio from uuid import UUID from habiticalib import Habitica async def main(): async with Habitica(api_user="user-id", api_key="api-token") as habitica: task_id = UUID("12345678-1234-5678-1234-567812345678") response = await habitica.delete_task(task_id) if response.success: print("Task deleted successfully") asyncio.run(main()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.