# 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](https://support.swarmica.com/article/en/1157-writing-custom-automation-plugins-with-python.html).

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**](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#articleevent) — article events  
[**CustomFieldEvent**](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#customfieldevent) — custom-field events  
[**KCSEvent**](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#kcsevent) — KCS events  
[**TicketEvent**](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#ticketevent) — ticket events  
[**UserEvent**](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#userevent) — user events

The parameters passed for each event are described in [Description of objects and parameters for triggers](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html).

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

~~~python
{'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:

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

or:

~~~python
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:

~~~python
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:

~~~python
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:

| Parameter | Description | Value |
| --- | --- | --- |
| responsible | Passes the event assignee | [user](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#user) object |
| date | Passes the event date | |
| old_value | Passes the previous event values | |
| new_value | Passes the new event values | |
| ticket | Passes the ticket where the event occurred | [ticket](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#ticket) object |
| ticket_comment | Passes comments from the ticket where the event occurred | [ticketcomment](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#ticketcomment) 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:

~~~python
event.ticket
~~~

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

~~~python
ticket = event.ticket
~~~

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

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

or:

~~~python
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?](https://support.swarmica.com/article/en/1351-what-is-the-event-based-or-scheduled-automation-context.html).

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:

~~~json
{
  "id": "1234"
}
~~~

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

~~~txt
{'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:

~~~python
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:

~~~txt
Event type = Ticket priority changed
Ticket: Priority = Urgent
~~~

This scenario uses a [**TicketEvent**](https://support.swarmica.com/article/en/1605-description-of-objects-and-parameters-for-triggers.html#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:

~~~json
{
  "new_group_uid": "ABCMWvoee35feOeA"
}
~~~

The script will be:

~~~python
# 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
~~~