#1614: Using Context Variables in Event-Based Action Scripts

Отредактирована: сегодня

Question

How can context variables be used to create scripts for event-based actions?

Answer

Using event context variables in scripts

In Swarmica, a Python script can be used as an action for an Event-based action.

For more information about writing scripts, see Writing custom automation plugins with Python.

Depending on the scenario, the script receives data about a specific event and additional context, if required.

Event-based actions support five event types:

ArticleEvent — article events
CustomFieldEvent — custom-field events
KCSEvent — KCS events
TicketEvent — ticket events
UserEvent — user events

The parameters passed for each event are described in Description of objects and parameters for triggers.

When a trigger fires, the data has the following structure:

{'data': {'event_id': <ID>, 'event': <TicketEvent: TicketEvent object (<ID>)>[, <ADDITIONAL_CONTEXT>]}}

Processing event data

To use event data, process the event object passed in the data. You can assign this object to a separate variable:

event = data.get('event', None)

or:

event = <EVENT_NAME>.objects.filter(id=data['event_id']).first()

Here, EVENT_NAME is the corresponding event class.

For example, suppose the script should run for a TicketEvent. The code is:

event = TicketEvent.objects.filter(id=data['event_id']).first()

You can then use the event variable to process the parameters passed by the corresponding event. The parameter structure is:

event.parameter[.parameter[.<...>]]

If a parameter is an object with its own parameters, the variable structure becomes more complex.

For example, a TicketEvent is an entity containing the following parameters:

ParameterDescriptionValue
responsiblePasses the event assigneeuser object
datePasses the event date
old_valuePasses the previous event values
new_valuePasses the new event values
ticketPasses the ticket where the event occurredticket object
ticket_commentPasses comments from the ticket where the event occurredticketcomment object

Suppose we need to perform an action on the ticket itself. The parameters include a ticket object, so the required object is accessed as follows:

event.ticket

For convenience, you can assign the object to a separate variable:

ticket = event.ticket

For example, to write the ticket ID and creation date to the log:

ticket = event.ticket
logger.info(f"Ticket #{ticket.id} was created at {ticket.created_at}")

or:

logger.info(f"Ticket #{event.ticket.id} was created at {event.ticket.created_at}")

Processing additional context

For more information about context, see What is the event-based or scheduled automation context?.

You can add additional context for an event-based action under Settings → Event-based actions → Action, in the Add data to context field. Enter the data in JSON format.

When the event fires, the additional context is passed together with the event data. For example, the additional context can be:

{
  "id": "1234"
}

The data passed to the script will then look like this:

{'data': {'event_id': <ID>, 'event': <TicketEvent: TicketEvent object (<ID>)>, 'id':'1234'}}

To work with additional context in the script, assign its value to a separate variable:

id = data.get('id', None)

Example

Suppose that when a ticket priority is increased to Critical, the ticket must be moved to a separate group.

Set the following event conditions:

Event type = Ticket priority changed
Ticket: Priority = Urgent

This scenario uses a TicketEvent. To pass the group where the ticket should be placed to the script, use additional context.

Add the UID of the new group to the additional context:

{
  "new_group_uid": "ABCMWvoee35feOeA"
}

The script will be:

# Import the modules required to run the script and work with the objects
from runtime.runners import BaseRunner
from core.models import TicketEvent, Group, Ticket

# Logging
import logging
logger = logging.getLogger(__name__)

class Runner(BaseRunner):
    def run(self, *args, **kwargs):
        logger.info(kwargs)

        # Put the event data passed to the script into data
        data = kwargs.get('data', {})

        # Get the TicketEvent object using data['event_id']
        event = TicketEvent.objects.filter(id=data['event_id']).first()

        # Log an error if the event was not passed
        if not event:
            logger.error(f"No event with {data['event_id']} found, exiting")
            return

        # Get the ticket object from the event
        ticket = event.ticket

        # Make sure that the ticket was passed with the event
        if ticket:
            ticket_id = event.ticket.id
            group_uid = data.get('new_group_uid', None)
            new_group = Group.objects.get(uid=group_uid)

            logger.info(
                f"Ticket #{ticket_id} should be assigned to group with UID {group_uid}"
            )

            # Check the current group and assign the required group if needed
            if ticket.group.uid != group_uid:
                ticket.group = new_group
                ticket.save()
                logger.info("Ticket group changed")
            else:
                logger.info("Ticket is already in the correct group")
        else:
            logger.warning(
                f"Ticket is not found in event {data['event_id']}, exiting"
            )
            return