Authentication

Authentication credential loading functions

scriptabit.authentication.load_habitica_authentication_credentials(config_file_name=u'.auth.cfg', section=u'habitica')[source]

Loads authentication credentials from an ini-style configuration file.

Parameters:
  • config_file_name (str) – Basename of the configuration file.
  • section (str) – Configuration file section name.
Returns:

the selected credentials

Return type:

dict

{
'x-api-user': 'the user name',
'x-api-key':  'the user API key',
}
Raises:ConfigError – specified file section or options are missing

Configuration

Configuration and command-line arguments

scriptabit.configuration.__add_min_max_value(parser, basename, default_min, default_max, initial, help_template)[source]

Generates parser entries for options with a min, max, and default value.

Parameters:
  • parser – the parser to use.
  • basename – the base option name. Generated options will have flags –basename-min, –basename-max, and –basename.
  • default_min – the default min value
  • default_max – the default max value
  • initial – the default initial value
  • help_template – the help string template. $mmi will be replaced with min, max, or initial. $name will be replaced with basename.
scriptabit.configuration.copy_default_config_to_user_directory(basename, clobber=False, dst_dir=u'~/.config/scriptabit')[source]

Copies the default configuration file into the user config directory.

Parameters:
  • basename (str) – The base filename.
  • clobber (bool) – If True, the default will be written even if a user config already exists.
  • dst_dir (str) – The destination directory.
scriptabit.configuration.get_config_file(basename)[source]

Looks for a configuration file in 3 locations:

  • the current directory
  • the user config directory (~/.config/scriptabit)
  • the version installed with the package (using setuptools resource API)
Parameters:basename (str) – The base filename.
Returns:The full path to the configuration file.
Return type:str
scriptabit.configuration.get_configuration(basename=u'scriptabit.cfg', parents=None)[source]

Parses and returns the program configuration options, taken from a combination of ini-style config file, and command line arguments.

Parameters:
  • basename (str) – The base filename.
  • parents (list) – A list of ArgumentParser objects whose arguments should also be included in the configuration parsing. These ArgumentParser instances must be instantiated with the add_help argument set to False, otherwise the main ArgumentParser instance will raise an exception due to duplicate help arguments.
Returns:

The options object, and a function that can be called to print the help text.

Date Handling

Datetime functions

scriptabit.dates.parse_date_local(date, milliseconds=True)[source]

Parses dates from ISO8601 or Epoch formats to a standard datetime object in the current local timezone.

Note that this function should not be used in time calculations. It is primarily intended for displaying dates and times to the user.

Parameters:
  • date (str) – A date string in either iso8601 or Epoch format.
  • milliseconds (bool) – If True, then epoch times are treated as millisecond values, otherwise they are evaluated as seconds.
Returns:

The parsed date time in local time.

Return type:

datetime

scriptabit.dates.parse_date_utc(date, milliseconds=True)[source]

Parses dates from ISO8601 or Epoch formats to a standard datetime object.

This is particularly useful since Habitica returns dates in two formats:

- iso8601 encoded strings
- Long integer Epoch times
Parameters:
  • date (str) – A date string in either iso8601 or Epoch format.
  • milliseconds (bool) – If True, then epoch times are treated as millisecond values, otherwise they are evaluated as seconds.
Returns:

The parsed date time in UTC.

Return type:

datetime

Errors

Error classes

exception scriptabit.errors.ArgumentOutOfRangeError(value)[source]

A function argument is out of range

exception scriptabit.errors.ConfigError(value)[source]

Configuration file error

exception scriptabit.errors.InvalidHabiticaDataError(value)[source]

The specified Habitica data is invalid error

exception scriptabit.errors.NotFoundError(value)[source]

The specified Habitica item was not found error

exception scriptabit.errors.PluginError(value)[source]

Plugin error

exception scriptabit.errors.ServerUnreachableError(value)[source]

The Habitica server is unreachable

Habitica Service

class scriptabit.HabiticaService(headers, base_url)[source]

Habitica API service interface.

buy_armoire()[source]

Buy an armoire item.

Returns:The Habitica response data.
Return type:dict
cast_skill(spellId, targetId=None)[source]

Cast a skill.

Parameters:
  • spellId (SpellIDs) – The spell ID
  • targetId (UUID) – Optional UUID of the spell target. Required for targetted spells.
Returns:

The Habitica response data.

Return type:

dict

cast_skill_by_raw_spell_id(spellId, targetId=None)[source]

Cast a skill using the raw Habitica API spell ID rather than the enum.

Parameters:
  • spellId (str) – The spell ID
  • targetId (UUID) – Optional UUID of the spell target. Required for targetted spells.
Returns:

The Habitica response data.

Return type:

dict

create_checklist_item(task_id, item)[source]

Add a checklist item to the task.

Parameters:
  • task_id (str) – The task ID.
  • item (dict) – The new checklist item.
create_tag(name)[source]

Create a tag.

Parameters:name (str) – the tag name.
Returns:The new tag.
Return type:dict
create_tags(tags)[source]

Create the tags. Existing tags are ignored.

Parameters:tags (list) – The list of tag names.
Returns:The list of Habitica Tag objects corresponding to the tags argument.
Return type:list
create_task(task, task_type=<HabiticaTaskTypes.todos: u'todos'>)[source]

Creates a task.

Parameters:
  • task (dict) – The task.
  • task_type (HabiticaTaskTypes) – The type of task to create. Default is to create a new todo. Only used if the task[‘type’] is empty or not present.
Returns:

The new task as returned from the server.

Return type:

dict

create_tasks(tasks)[source]

Creates multiple tasks.

Note that unlike HabiticaService.create_task, this method does not check that the task type is valid.

Parameters:task (list) – The list of tasks.
Returns:The new tasks as returned from the server.
Return type:list
delete_checklist_item(task_id, item_id)[source]

Delete a checklist item.

Parameters:
  • task_id (str) – The task ID.
  • item_id (str) – The checklist item ID.
delete_tags(tags)[source]

Delete a list of tag objects.

Parameters:tags (list) – The list of tag objects.
delete_task(task)[source]

Delete a task.

Parameters:task (dict) – The task.
feed_pet(pet, food)[source]

Feed a pet.

Parameters:
  • pet (str) – The pet name.
  • food (str) – The food.
Returns:

The Habitica response data.

Return type:

dict

get_stats()[source]

Gets the authenticated user stats.

Returns:The stats.
Return type:dict
get_tags()[source]

Get the current user’s tags.

Returns:The tags.
Return type:list
get_task(_id=u'', alias=u'')[source]

Gets a task.

If both task ID and alias are specified, then the ID is used.

Parameters:
  • _id (str) – The task ID.
  • alias (str) – The task alias.
Returns:

The task, or None if the task is not found.

Return type:

dict

Raises:

ValueError

get_tasks(task_type=None)[source]

Gets all tasks for the current user.

Parameters:task_type (HabiticaTaskTypes) – The type of task to get. Default is all tasks apart from completed todos.
Returns:The tasks.
Return type:dict
get_user()[source]

Gets the authenticated user data.

Returns:The user data.
Return type:dict
hatch_pet(egg, potion)[source]

Hatch a pet.

Parameters:
  • egg (str) – The egg name.
  • potion (str) – The potion name.
Returns:

The Habitica response data.

Return type:

dict

is_server_up()[source]

Check that the Habitica API is reachable and up

Returns:True if the server is reachable, otherwise False.
Return type:bool
score_task(task, direction=u'up')[source]

Score a task.

Parameters:
  • task (dict) – the task to score.
  • direction (str) – ‘up’ or ‘down’
Returns:

Habitica API response data.

Return type:

dict

Raises:
  • ValueError – invalid direction.
  • ValueError – missing ID or alias.
set_exp(exp)[source]

Sets the user’s XP (experience points).

Parameters:exp (float) – The new XP value.
Returns:The new XP value, extracted from the JSON response data.
Return type:float
set_gp(gp)[source]

Sets the user’s gold (gp).

Parameters:gp (float) – The new gold value.
Returns:The new gold value, extracted from the response data.
Return type:float
set_hp(hp)[source]

Sets the user’s HP.

Parameters:hp (float) – The new HP value.
Returns:The new HP value, extracted from the JSON response data.
Return type:float
set_lvl(lvl)[source]

Sets the user’s character level. Note that XP will be reset to 0.

Parameters:lvl (int) – The new level.
Returns:The new character level, extracted from the JSON response data.
Return type:lvl
set_mp(mp)[source]

Sets the user’s MP (mana points).

Parameters:mp (float) – The new MP value.
Returns:The new MP value, extracted from the JSON response data.
Return type:float
update_task(task)[source]

Updates an existing task.

Parameters:task (dict) – The task.
Returns:The new task as returned from the server.
Return type:dict
Raises:ValueError – if neither an ID or alias are present in task.
upsert_task(task, task_type=<HabiticaTaskTypes.todos: u'todos'>)[source]

Upserts a task.

Existing tasks will be updated, otherwise a new task will be created.

Parameters:
  • task (dict) – The task.
  • task_type (HabiticaTaskTypes) – The type of task to create if a new task is required. Can be overriden by an existing task[‘type’] value.
Returns:

The new task as returned from the server.

Return type:

dict

Raises:

ValueError

Plugin Baseclass

class scriptabit.IPlugin[source]

Scriptabit plugin base class.

_config

lookupdict – Configuration object returned from argparse.

_update_count

int – Number of updates (zero-based).

_hs

scriptabit.HabiticaService – The HabiticaService instance.

activate()[source]

Called by the plugin framework when a plugin is activated.

deactivate()[source]

Called by the plugin framework when a plugin is deactivated.

dry_run

Indicates whether this is a dry run or not.

Returns:True if this is a dry run, otherwise False.
Return type:bool
get_arg_parser()[source]

Gets the argument parser containing any CLI arguments for the plugin.

Note that to avoid argument name conflicts, only long argument names should be used, and they should be prefixed with the plugin-name or unique abbreviation.

To get their ArgParser, subclasses should call this method via super and capture the returned ArgParser instance.

Returns: argparse.ArgParser: The ArgParser containing the argument definitions.

initialise(configuration, habitica_service, data_dir)[source]

Initialises the plugin.

Generally, any initialisation should be done here rather than in activate or __init__.

Parameters:
  • configuration (ArgParse.Namespace) – The application configuration.
  • habitica_service – the Habitica Service instance.
  • data_dir (str) – A writeable directory that the plugin can use for persistent data.
notify(message, **kwargs)[source]

Notify the Habitica user.

If this is a dry run, then the message is logged. Otherwise the message is logged and posted to the Habitica notification panel.

Parameters:
  • message (str) – The message.
  • panel (bool) – If True, the Habitica panel is updated.
  • notes (str) – the extra text/notes.
  • heading_level (int) – If > 0, Markdown heading syntax is prepended to the message text.
  • alias (str) – the notification alias.
static supports_dry_runs()[source]

Indicates whether the plugin correctly supports the dry-run command-line flag.

To support dry runs, the plugin must not modify any persistent data, either on Habitica or elsewhere if the dry-run flag is True.

Returns:True if dry runs are supported, otherwise False.
Return type:bool
update()[source]

This update method will be called once on every update cycle, with the frequency determined by the value returned from update_interval_minutes().

If a plugin implements a single-shot function, then update should return False.

Returns:True if further updates are required; False if the plugin is finished and the application should shut down.
Return type:bool
update_interval_minutes()[source]

Indicates the required update interval in minutes.

Returns:The required update interval in minutes.
Return type:float
update_interval_seconds()[source]

Indicates the required update interval in integer seconds.

Returns:update interval in whole seconds
Return type:int

Scriptabit

Scriptabit: Python scripting for Habitica.

scriptabit.scriptabit.start_scriptabit()[source]

Command-line entry point for scriptabit

scriptabit.scriptabit.__init_logging(logging_config_file)[source]

Initialises logging.

Parameters:logging_config_file (str) – The logging configuration file.
scriptabit.scriptabit.__get_configuration(plugin=None)[source]

Builds and parses the hierarchical configuration from environment variables, configuration files, command-line arguments, and argument defaults.

Parameters:plugin – The optional plugin. If supplied, then the plugin arguments will be added to the parsed arguments.
Returns:The argparse compatible configuration object and the help function
scriptabit.scriptabit.__get_plugin_manager()[source]

Discovers and instantiates all plugins, returning a management object.

Returns:The plugin manager with the loaded plugins.
Return type:yapsy.PluginManager
scriptabit.scriptabit.__list_plugins(plugin_manager)[source]

Lists the available plugins.

Parameters:
  • plugin_manager (yapsy.PluginManager) – the plugin manager containing
  • plugins. (the) –

Synchronisation

Synchronisation services, classes, and interfaces, including Habitica classes. The remaining classes for synchronisation with specific services must be provided through plugins.

Task

Defines an abstract task.

class scriptabit.task.CharacterAttribute[source]

Implements Task character attributes

class scriptabit.task.ChecklistItem(name, checked=False)[source]

Simple implementation of a checklist item.

__init__(name, checked=False)[source]

Initialise the checklist item.

Parameters:
  • name (str) – The item name.
  • checked (bool) – The item check-status.
class scriptabit.task.Difficulty[source]

Implements Task difficulty levels.

class scriptabit.task.SyncStatus[source]

Indicates the synchronisation status of the task.

class scriptabit.task.Task[source]

Defines a Habitica task data transfer object.

Essentially this is the common features of a task as found in many task management applications. If a task from a particular service can be mapped to this class, then moving tasks between services becomes easier.

id

str – The task ID.

name

str – The task name.

due_date

datetime – The due date in UTC

description

str – The description.

completed

bool – Completion/checked status

difficulty

Difficulty – task difficulty.

attribute

CharacterAttribute – habitica character attribute of the task

status

SyncStatus – Synchronisation status flag.

checklist

list – The task checklist, or None if the task does not have a checklist.

__init__()[source]

Initialise the task.

attribute

Task character attribute

checklist

The checklist.

Returns:
The checklist, or an empty list if there are no
checklist items.
Return type:list
completed

Task completed

copy_fields(src, status=<SyncStatus.updated: 2>)[source]

Copies fields from src.

Parameters:
  • src (Task) – the source task
  • status (SyncStatus) – the status to set
Returns:

self

Return type:

Task

description

Task description

difficulty

Task difficulty

due_date

The due date in UTC if there is one, or None.

id

Task id

last_modified

The last modified timestamp in UTC.

name

Task name

status

Task status

TaskMap

Defines persistent 1-1 task mappings.

class scriptabit.task_map.TaskMap(filename=None)[source]

Persistent 1-1 task mapping.

_TaskMap__map(a, b)

Associate two ID strings

__init__(filename=None)[source]

Initialise the TaskMap instance.

Parameters:filename (str) – The optional filename to load from.
get_all_dst_keys()[source]

Gets a list of all destination keys.

Returns:all destination keys.
Return type:list
get_all_src_keys()[source]

Gets a list of all source keys.

Returns:all source keys.
Return type:list
get_dst_id(_id)[source]

Get the mapped destination task ID for a source task.

Parameters:_id – The source task ID.
Returns:If a mapping exists, the destination task ID.
Raises:KeyError – if the input ID has no mapping.
get_src_id(_id)[source]

Get the mapped source task ID for a destination task.

Parameters:_id – The destination task.
Returns:If a mapping exists, the source task ID.
Raises:KeyError – if the input ID has no mapping.
map(src, dst)[source]

Create a mapping between a source and destination task.

Parameters:
  • src (Task) – The source task.
  • dst (Task) – The destination task.
persist(filename)[source]

Persist the TaskMap instance to a file.

Parameters:filename (str) – The destination file name.
try_get_dst_id(_id)[source]

Get the mapped destination task ID for a source task.

Parameters:_id – The source task ID
Returns:If a mapping exists, the destination task ID, otherwise False.
Return type:str
try_get_src_id(_id)[source]

Get the mapped source task ID for a destination task.

Parameters:_id – The destination task ID
Returns:If a mapping exists, the source task ID, otherwise False.
Return type:str
unmap(src_id)[source]

Delete a mapping.

Parameters:src_id – The source id to unmap.

TaskService

Defines an abstract task service.

A task service provides the following features:

  • Query for tasks (including all tasks)
  • Create a new task
  • Persist a list of tasks
class scriptabit.task_service.TaskService[source]

Defines an abstract Task Service.

_create_task(src=None)[source]

Task factory method.

Allows subclasses to create the appropriate Task type.

Parameters:src (Task) – The optional data source.
Returns:The new task
Return type:Task
create(src=None)[source]

Creates a new task.

Parameters:src (Task) – The optional data source.
Returns:The new task.
Return type:Task
get_all_tasks()[source]

Get all tasks.

Returns:The list of tasks
Return type:list
persist_tasks(tasks)[source]

Persists the tasks.

Parameters:tasks (list) – The collection of tasks to persist.

TaskSync

Provides synchronisation between two task services.

Basic algorithm

  • Build list of candidate tasks from source and destination services

  • Index the candidate tasks for lookup by ID

  • Get the existing list of source to destination task mappings

  • Check all source tasks

    • Mapping exists, destination task found:

      • update destination
    • Mapping exists, destination task not found:

      • recreate destination
      • alternatively, could delete source task
    • No mapping found:

      • new task
      • if task completed, check if last modified date is newer than last sync date
  • Check all destination tasks for which mapped source tasks can’t be found:

    • assume deleted and flag destination as ‘deleted’
  • Check for orphan mappings: both source and destination not found

    • delete mapping
  • Not implemented: persist source tasks

  • Persist destination tasks

class scriptabit.task_sync.TaskSync(src_service, dst_service, task_map, last_sync=None, sync_description=True)[source]

Provides synchronisation between two task services.

class Stats[source]

Simple sync stats

__init__()[source]

Initialise the stats

total_changed

Get the total number of changed tasks.

_TaskSync__clean_orphan_task_mappings()

Removes task mappings where neither the source or destination tasks exist.

_TaskSync__create_new_dst(src)

Creates and maps a new destination task.

Parameters:src (Task) – source task
Returns:The new destination task
Return type:Task
_TaskSync__get_dst_by_id(_id)

Looks up a cached destination task by ID

_TaskSync__get_src_by_id(_id)

Looks up a cached source task by ID

_TaskSync__get_task_data()

Gets, caches, and indexes task data from the source and destination services.

_TaskSync__handle_deleted_source_task(src_id, dst)

Handle the case where a mapped destination task exists but the source task cannot be located.

Parameters:
  • src_id (str) – the source task ID
  • dst (Task) – the destination task
_TaskSync__handle_destination_found(src, dst)

Handle the case where a pair of mapped tasks exist.

Parameters:
  • src (Task) – the source task
  • dst (Task) – the destination task
_TaskSync__handle_destination_missing(src)

Handle the case where a mapped destination task cannot be found.

Parameters:src (Task) – the source task
_TaskSync__handle_new_task(src)

Handle a new source task.

Parameters:src (Task) – the source task
__init__(src_service, dst_service, task_map, last_sync=None, sync_description=True)[source]

Initialise the TaskSync instance.

Parameters:
  • src_service (TaskService) – The TaskService for source tasks.
  • dst_service (TaskService) – The TaskService for destination tasks.
  • task_map (TaskMap) – The TaskMap.
  • last_sync (datetime) – The last known synchronisation datetime (UTC).
  • sync_description (bool) – Controls whether the task description will be synchronised.
last_sync

Gets the last synchronisation datestamp.

Returns:The last synchronisation time.
Return type:datetime
synchronise(clean_orphans=False)[source]

Synchronise the source service with the destination. The task_map will be updated.

Parameters:clean_orphans (bool) – If True, mappings for tasks that exist in neither the source or destination are deleted.
Returns:Summary statistics of the sync.
Return type:TaskSync.Stats

HabiticaTask

Implements a Habitica synchronisation task.

class scriptabit.habitica_task.HabiticaTask(task_dict=None)[source]

Defines a Habitica synchronisation task.

__init__(task_dict=None)[source]

Initialise the task.

Parameters:task_dict (dict) – The Habitica task dictionary, as returned by HabiticaService.
attribute

Task character attribute

checklist

The checklist.

Returns:
The checklist, or an empty list if there are no
checklist items.
Return type:list
completed

Task completed

description

Task description

difficulty

Task difficulty

due_date

The due date if there is one, or None.

id

Task id

is_challenge

Returns True is this is a challenge task.

last_modified

The last modified timestamp in UTC.

name

Task name

task_dict

Gets the internal task dictionary.

HabiticaTaskService

Implements the Habitica synchronisation task service.

class scriptabit.habitica_task_service.HabiticaTaskService(hs, dry_run=False, tags=None)[source]

Implements the Habitica synchronisation task service.

_HabiticaTaskService__update_task(task)

Updates a task. This is required as checklists require tedious handling.

Parameters:task (scriptabit.HabiticaTask) – The task to update.
__init__(hs, dry_run=False, tags=None)[source]

Initialises the Habitica synchronisation task service.

Parameters:
  • hs (HabiticaService) – The Habitica Service.
  • dry_run (bool) – Indicates a dry run.
  • tags (list) – The list of tags to be applied to synchronised tasks.
_create_task(src=None)[source]

Task factory method.

Parameters:src (Task) – The optional data source.
Returns:A new HabiticaTask instance.
Return type:HabiticaTask
dry_run

Returns the dry run status.

get_all_tasks()[source]

Get all tasks.

Returns:The list of tasks
Return type:list
persist_tasks(tasks)[source]

Task factory method.

Allows subclasses to create the appropriate Task type.

Returns:The new task
Return type:Task

Utility Functions

class scriptabit.UtilityFunctions(config, habitica_service)[source]

scriptabit utility functions. These are a collection of higher-level functions, implemented over the HabiticaService class.

__config

lookupdict – Configuration object returned from argparse.

__hs

scriptabit.HabiticaService – The HabiticaService instance.

buy_armoire()[source]

Purchase an item from the Enchanted Armoire

dry_run

Indicates whether this is a dry run or not.

Returns:True if this is a dry run, otherwise False.
Return type:bool
get_arg_parser()[source]

Gets the argument parser containing Utility function CLI arguments.

Returns:The ArgParser containing the argument definitions.
Return type:argparse.ArgParser
run()[source]

Runs the user-selected scriptabit utility functions

set_gold(gp, increment=False, scale=False)[source]

Sets the user gold to the specified value

Returns:The new gold points.
Return type:float
set_health(hp, increment=False, scale=False)[source]

Sets the user health to the specified value

Returns:The new health points.
Return type:float
set_level(level, increment=False, scale=False)[source]

Sets the user level to the specified value

Returns:The new gold points.
Return type:float
set_mana(mp, increment=False, scale=False)[source]

Sets the user mana to the specified value

Returns:The new mana points.
Return type:float
set_xp(xp, increment=False, scale=False)[source]

Sets the user experience points to the specified value.

Returns:The new experience points.
Return type:int
show_user_data()[source]

Shows the user data

static upsert_notification(habitica_service, text, notes=u'', heading_level=0, append_time=True, tags=None, alias=u'scriptabit_notification_panel')[source]

Creates or updates a notification (currently implemented as a scoreless habit).

Parameters:
  • habitica_service (HabiticaService) – The habitica service to use.
  • text (str) – the new text.
  • notes (str) – the extra text/notes.
  • heading_level (int) – If > 0, Markdown heading syntax is prepended to the message text.
  • append_time (bool) – If True, a time stamp is appended to text.
  • tags (list) – Optional list of tags to be applied to the notification.
  • alias (str) – the notification alias.
Returns:

The notification object returned by the Habitica API

Return type:

dict