Custom Actions

For versions >= 17.03 the pattern for writing custom actions has changed from handling single resources to handling the entire set of matched resources. While the mechanism for registering actions remains the same several changes should be noted:

1. Add bulk_action: True and accepts_complement: True to the keyword arguments.

  1. The function arguments now are: - bot: Bot object - settings: dictionary of settings for the action - matches: list of resource objects that matched all filters - non_matches: list of resource objects that did not match all filters

Note that the legacy action receives an event object which wraps the resource object. This is no longer the case for bulk actions which receive lists of resource objects.

Actions

Receiving the entire matched/non_matched results from a bot’s filters gives the developer the maximum flexibility for performing the actions in what best suites the specific need of the developer. For example, sending requests to an third party API may require chunking requests into smaller batches.:

from DivvyUtils.misc import chunks

@registry.action(
    uid='divvy.action.start_resource_example',
    bulk_action=True,
    accepts_complement=True,
    ...
)
def start_resource_example(bot, settings, matches, non_matches):
    for chunk in chunks(matches, 50):
        ids_for_api_request = [str(resource.resource_id) for resource in chunk]
        do_api_request(ids_for_api_request)

Interative Actions (Deprecated)

The method used prior to 17.03 which is called per resources.

Here’s an example of how DivvyCloud’s plugin registers the predefined “Log Message” action, which logs a line of text to the console:

# Instantiate an object for interfacing with the bot filter and action registries
from DivvyBotFactory.registry import BotFactoryRegistryWrapper
registry = BotFactoryRegistryWrapper()

# Define the action
@registry.action(
    uid='divvy.action.log_message',
    name='Log Message',
    description='Log an info message, intended to aid developers in testing.',
    author='DivvyCloud Inc.',
    supported_resources=[],
    settings_config=[
        StringField(  # Configuration field to appear in the bot creation form
            name='message_text',
            display_name='Message To Log',
            description='Message text to log when this action is evaluated.',
            preselected_values='Action evaluated'
        )
    ]
)
def log_message(event, bot, settings):
    logger.info('{0}: {1}'.format(
        event.resource.resource_id,  # Unique ID belonging to the resource being acted upon
        settings.get('message_text', 'Unspecified message')
    ))

# Register and unregister this action along with the containing plugin
def load():
    registry.load()
def unload():
    registry.unload()