Page tree
Skip to end of metadata
Go to start of metadata

Sample Python Scripts

The following scripts provide examples of using custom Python scripting capabilities in a typical  Agiloft installation. The  Agiloft distribution includes Python and will automatically use it to execute scripts with a .py extension. If you want to use your own version of python, you may do so by setting the KB global variable "Location of external Python directory".

You must add these functions to every Python script used in Agiloft in order for the script to terminate properly:

out.exitAction(ALset.ACCEPT)
out.save()

Samples

Click a sample below to see the script text.

 Sample Script 1 redirects the user after they submit a record.
######################################################################
# Synopsis:
#
# Redirect the user after he/she submits the ticket.
#
# There is no need to specify the Python interpreter if the script is named *.py
# because the system recognizes .py scripts as being Python based and will
# use the Python that is included in the distribution.
#
# If you use this script with your own copy of Python, please note that
# it requires ElementTree module to be installed
#
######################################################################
import sys
from ALget import ALget
from ALset import ALset
def action(inputXMLFile, outputXMLFile):
    input = ALget(inputXMLFile)
    out = ALset(outputXMLFile)
    ######################################################################
    #
    # Only log the user out if he/she is not a member of the Staff
    # group. In other words, we want all members of staff to be able
    # to log tickets on behalf of users without being logged out.
    ######################################################################
    groups = input.globalVariable('my_groups')
    groupAllowedToClose = "Staff"
    if groupAllowedToClose not in groups.split(","):
        out.redirect("http://www.example.com")
        out.exitAction(ALset.ACCEPT_REDIRECT)
    else:
        out.exitAction(ALset.ACCEPT)
    out.save()
action(sys.argv[1], sys.argv[2]) 
 Sample Script 2 sends new users a confirmation email with their login and password.
#####################################################################
# Synopsis:
# Send new users a confirmation email with their login and password
#
# There is no need to specify the Python interpreter if the script is named *.py
# because the system recognizes .py scripts as being Python based and will
# use the Python that is included in the distribution.
#
# If you use this script with your own copy of Python, please note that
# it requires ElementTree module to be installed
#
######################################################################
import sys
from ALget import ALget
from ALset import ALset
import smtplib
from email.mime.text import MIMEText
######################################################################
# Only send email to members of the Customer group.
# For security reasons, it is unsafe to send password information in
# plain text to privileged groups such as staff or admin.
######################################################################
def action(inputXMLFile, outputXMLFile):
    input = ALget(inputXMLFile)
    out = ALset(outputXMLFile)
    groups = input.valueMultipleLF("f_group")
    me = "support@CompanyName.com"
    you = input.value("email")
    if groups and groups.containsValue("Customer") and you:
        body = ("Dear " + input.value("full_name") + ",\n"
                "Thank you for registering with our support system.\n\n"
                "You have chosen the following\n"
                "login: " + input.value("_login") + "\n"
                "password: " + input.value("password") + "\n"
                "Thank you,\n"
                "CompanyName Support staff\n")
        msg = MIMEText(body)
        msg['Subject'] = "Welcome to CompanyName Support"
        msg['From'] = me
        msg['To'] = input.value("email")
        s = smtplib.SMTP('localhost')
        s.sendmail(me, [you], msg.as_string())
        s.quit()
    out.exitAction(ALset.ACCEPT)
    out.save()
action(sys.argv[1], sys.argv[2]) 
 Sample Script 3 checks if the user belongs to QA group and blocks non-QA users from closing the ticket.
############################################################################
# Synopsis:
# Check if the user belongs to QA group and block closure of the ticket if
#  he/she doesn't.
#
# There is no need to specify the Python interpreter if the script is named *.py
# because the system recognizes .py scripts as being Python based and will
# use the Python that is included in the distribution.
#
# If you use this script with your own copy of Python, please note that
# it requires ElementTree module to be installed
############################################################################
import sys
from ALget import ALget
from ALset import ALset
def action(inputXMLFile, outputXMLFile):
    input = ALget(inputXMLFile)
    out = ALset(outputXMLFile)
    groups = input.globalVariable('my_groups')
    groupAllowedToClose = "QA"
    if groupAllowedToClose not in groups.split(",") and input.value("wfstate") == "Closed" and input.value("wfstate", input.oldRecordsNamesList()[0]) != "Closed":
        # Set a field value. In this case, we set the status field
        # to its old value
        out.recordField("wfstate", input.value("wfstate", input.oldRecordsNamesList()[0]))
        print("Restore state")
    out.exitAction(ALset.ACCEPT)
    out.save()
action(sys.argv[1], sys.argv[2])
 Sample Script 4 illustrates some common tasks you would perform in a typical script.
######################################################################
# Synopsis:
# This script performs some common tasks typical of a script.
# You could run this script against the input file example:
# filename.py input.xml output.xml
#
# There is no need to specify the Python interpreter if the script is named *.py
# because the system recognizes .py scripts as being Python based and will
# use the Python that is included in the distribution.
#
# If you use this script with your own copy of Python, please note that
# it requires ElementTree module to be installed
#
######################################################################
import sys
# these are interface modules to interact with input and output xml files
from ALget import ALget
from ALset import ALset
def action(inputXMLFile, outputXMLFile):
    # Load the XML files into internal structures. This is a required step before interacting with input using API calls.
    input = ALget(inputXMLFile)
    out = ALset(outputXMLFile)
    # we will use this to accumulate messages to the user
    message = ""
    # Let's retrieve the user's name to provide a personalized message.
    # That would be the Full Name from the Contacts table entry for the user editing the ticket.
    full_name = input.globalVariable('my_full_name')
    # Let's check if user is a creator of the record and prohibit editing if not, with an appropriate message.
    # The same could be done with permissions, but access control through scripts can be more sophisticated.
    # For example, you could use input.globalVariable('my_start_work') and input.globalVariable('my_stop_work')
    # (if there are such fields in Contacts table) to allow modifications only within the user's working hours.
    print("Editor name:" + input.globalVariable('my_full_name'))
    print("Creator name:" + input.value('created_by'))
    if input.globalVariable('my_login') != input.value('login'):
        # We compare the login of the user who edits the record (via the global variable) with
        # the login of the record's creator. Note that this example would be for the Support Cases table,
		# in which the Creator Login variable is simply "login"). If they're not the same, we add a message to
		#  the message variable we defined earlier, to describe the reason for denial.  
        message += "Sorry, " + full_name + ", you are not the creator of this record, you cannot modify it."
		# Then we set the exit code to reject the changes.
        out.exitAction(ALset.BLOCK)
    else:
        # Now let's try to detect some changes in the record.
        # For example, let's make deleteable flag non-editable without blocking other changes.
		# The second parameter of value() is optional.  Passing this argument in will refer to the version just before
		# the user's edit.  If the current (edited) version doesn't equal that version, the user must've changed it.
        if input.value('deleteable') != input.value('deleteable', input.oldRecordsNamesList()[0]):
            # We will notify user that the change is not allowed.
            message += "Sorry, " + full_name + ", you cannot modify the deleteable flag, your change will be ignored."
            # Let's return the old value back.
            out.recordField('deleteable', input.value('deleteable', input.oldRecordsNamesList()[0]))
		# Now some more complex techniques - linked records access.
    	# Let's find out, for example, the name and phone number of the record owner
    	# if a Support Case is "open" ("owned by" is a Linked Field relationship with the contacts table)
    	if "Open" == input.value('wfstate'):
        	# Retreive phone and name from first (index=0) record linked to owned_by field.
        	owner_phone = input.linkedValue("end_user_name", 0, "direct_phone")
        	owner_name = input.linkedValue("end_user_name", 0, "full_name")
        	message += "You can contact " + owner_name + ", owner of this support case by phone at " + owner_phone + "."
    	# Now check if this case is assigned to a team as opposed to a user
		# NOTE: this example is outdated because the assigned_team field in support cases only links to the Teams table,
		# but the methods used here are interesting regardless.
    	linkedRecordNames = input.linkedRecordsNamesList("assigned_team")
    	if input.tableNameForRecord(linkedRecordNames[0]) == "teams":
    	    message += "This issue assigned to " + input.linkedValue("assigned_team", 0, "_name") + " team."
    	# Accept changes to ticket
    	out.exitAction(ALset.ACCEPT)
    # Store the full message we've been accumulating in the variable "message" using the message() method, so the user can read it all.
    out.message(message)
    # And don't forget to save the output file.
    out.save()
# Retrieve input and output XML files from sys.argv and pass them into our function!
action(sys.argv[1], sys.argv[2]) 				



CONTENTS