Custom Script to Link Requests
Hello,
I have a script that I found on this site that I have modified to duplicate a request. It will create a new request from the parent request and copy all the relevant data I want over while adding a note to the parent request with the id and link etc for the child request. All of that works great but I am trying to figure out if I can add some commands in to link the created child request with the parent request at the same time. I looked in the API documentation and there is some things for linking a request I'm just not sure how to add it to my script. Here is the script I currently have that works to duplicate.
- #This Python Script is used to Trigger the Creation of a Child Request in ServiceDesk Plus, based on the value that is selected in a specific field in the Parent Request.The Ticket ID of the New Request is captured and added as a Note in the Parent Request.The Parent Ticket Id is appended to the Subject of the New Request.This is achieved using Request Custom Triggers.
- #Works on python version 3.4.1 and above.
- #Use Case: We have Considered a Service Request for 'New Hire' in this script.The Answer that is returned for the Resource Question "Need a VPN Account" is used to trigger the creation of a New Child Request.For this, a specific Template called "Request a VPN account creation" is used.
- #Below are the list of Packages used in this Script.We have used a Python Library called 'Requests' which is not bundled by default with Python installation.
- #More information on this Package and the instructions on installing it on the Application Server are available in the following link.
- # http://docs.python-requests.org/en/latest/user/install/#install
- import requests
- import sys
- import json
- import datetime
- from pprint import pprint
- #Create a Session Object that will be used to pass different parameters across the HTTP requests.
- #All the parameters like the ServerName , protocol , portnumber and Technician API key that are used in the Script are Input here.Please update this based on your Environment.
- with requests.Session() as s:
- url = "<server:port>" #Update this link with the protocol and servername:portnumber values of the ServiceDesk Plus application.
- TechnicianKey='<technician key>' #Replace 2F258F6D-4689-40F5-8EF7-3501CC21CEA8 with a Technician's API key.
- OperationName='ADD_REQUEST'#This value is the name of the Operation that is performed in this API call.
- #Reading the argument passed to the script.The Request details are stored as a JSON Object in a file and its path is provided to the Script as input.
- filename = str(sys.argv[1])
- #Reading the Request JSON object from the json file which is provided as input to the script as $COMPLETE_JSON_FILE
- with open(filename) as data_file:
- data = json.load(data_file)
- requestObj = data['request']
- #Below is a Sample of the Request Details in Json Format.
- '''{"request":{"WORKORDERID":"47","REQUESTER":"Guest","CREATEDBY":"Bala","CREATEDTIME":"1450300531128","DUEBYTIME":"1450330200128","RESPONSEDUEBYTIME":"-1","FR_DUETIME":"-1","RESPONDEDTIME":"0","RESOLVEDTIME":"0","COMPLETEDTIME":"0","SHORTDESCRIPTION":"","TIMESPENTONREQ":"0hrs 0min","SUBJECT":"Upgrade ServicedeskPlus","REQUESTTEMPLATE":"Default Request","MODE":"","SLA":"Medium SLA","ASSET":"bala.soho.local, bala230.soho.local, isspec2.soho.local, Bala-macbook-pro","NotifyForNoteAddition":"requester2@sohocorp.com","DEPARTMENT":"","IS_CATALOG_TEMPLATE":"false","SITE":"","ISVIPUSER":"No","SERVICE":"","CATEGORY":"Hardware","SUBCATEGORY":"Desktop","ITEM":"","TECHNICIAN":"Bala","TECHNICIAN_LOGINNAME":"-","STATUS":"Open","PRIORITY":"Medium","LEVEL":"L5","IMPACT":"","URGENCY":"","IMPACTDETAILS":"-","REQUESTTYPE":"","CLOSURECODE":"","CLOSURECOMMENTS":"","YETTOREPLYCOUNT":"","GROUP":"","DESCRIPTION":"Please upgrade 'servicedesk plus on the test server.","Seating Location":"","Client_Code": "","LOGIN_NAME":"administrator","LOGGEDIN_USER_NAME":"Bala"},"diff":{"DUEBYTIME":{"OLD":"1450326600128","NEW":"1450330200128"},"SLA":{"OLD":"High SLA","NEW":"Medium SLA"},"PRIORITY":{"OLD":"High","NEW":"Medium"}}}'''
- #Assigning value got from the Request JSON Object to variables which can be used in constructing the JSON for creating the New Request
- workorderid = requestObj['WORKORDERID']
- requester = requestObj['REQUESTER']
- requesttemplate = requestObj['REQUESTTEMPLATE']
- ##createdby = requestObj['CREATEDBY']
- subject = requestObj['SUBJECT']
- description = requestObj['DESCRIPTION']
- technician = requestObj['LOGGEDIN_USER_NAME']
- ##priority = requestObj['PRIORITY']
- ##site = requestObj['SITE']
- category = requestObj['CATEGORY']
- subcategory = requestObj['SUBCATEGORY']
- #item = requestObj['ITEM']
- #impact = requestObj['IMPACT']
- #urgency = requestObj['URGENCY']
- #The Additional Fields in the Request are processed here.
- conFName=requestObj['Consumer FName']
- conLName=requestObj['Consumer LName']
- conL4SSN=requestObj['SSN last 4']
- conPhone=requestObj['Consumer Phone']
- memberID=requestObj['Member ID']
- #emailIDs=requestObj['email_ids_to_notify']
- capTicket=requestObj['CAP Ticket']
- carrier=requestObj['Carrier']
- coverageYear=requestObj['Coverage Year']
- #This block is used to get the value of a Specific Question from the Resource Section in the Service Request.
- ##resourceObj=requestObj['resource']
- ##resourceSection=resourceObj['Resource required for new employee']
- ##resourceQn=resourceSection['Need a VPN Account']
- ##resourceAns=resourceQn[0]
- ##createrequest = False
- #The code below can be used to remove the White Spaces in the Asset list that is got from the Request Json Object.The reconstructed asset_list can be used to set the Asset Field in the New Request.
- #The list got as "bala.soho.local, bala230.soho.local" is converted as "bala.soho.local,bala230.soho.local" , after removing the white spaces.
- #assets = requestObj['ASSET']
- #asset_list = ''.join(assets.split())
- #The below Code shows how the data got from a Date/Time field in the Parent Request can be processed and used in the Child Request.The Default date fields will be returned, in the Request Json in Long date format.The Date format to set/update a Date field in the Request is '17 Dec 2015, 02:45:31'.
- '''
- DUEBYTIME = requestObj['DUEBYTIME']
- duebydate = datetime.datetime.fromtimestamp(int(DUEBYTIME) / 1e3).strftime('%d %b %Y, %H:%M:%S')'''
- ##if resourceAns == "Yes": #Checking if the value for Need a VPN Account is set as Yes.
- createrequest = True
- #Below is the sample JSON format for submitting request data through the ADD_REQUEST API
- '''{'operation': {'details': {'requesttemplate': 'Default Request', 'subject': 'Upgrade ServicedeskPlus - Parent Ticket ID: 47', 'technician': 'Bala', 'requester': 'Guest', 'site': '', 'description': "Please upgrade 'servicedesk plus on the test server.", 'asset': 'bala.soho.local,bala230.soho.local', 'priority': 'Medium'}}}'''
- #Creating the json object for the Request Create operation and storing it in the variable 'jsonData'
- operationJson={}
- operationJson["operation"]={}
- detailsJson={}
- detailsJson["details"]={}
- jsonObj={}
- jsonObj["requester"]=requester
- jsonObj["Parent Ticket ID"]=workorderid
- jsonObj["subject"]=subject
- jsonObj["description"]="Steps taken to assist:"
- jsonObj["requesttemplate"]="Default Request"
- jsonObj["Category"]=category
- jsonObj["Subcategory"]=subcategory
- jsonObj["technician"]=technician
- jsonObj["Consumer FName"]=conFName
- jsonObj["Consumer LName"]=conLName
- jsonObj["SSN last 4"]=conL4SSN
- jsonObj["Consumer Phone"]=conPhone
- jsonObj["Member ID"]=memberID
- #jsonObj["email_ids_to_notify"]=emailIDs
- jsonObj["CAP Ticket"]=capTicket
- jsonObj["Carrier"]=carrier
- jsonObj["Coverage Year"]=coverageYear
- ##jsonObj["priority"]=priority
- ##jsonObj["site"]=site
- detailsJson["details"]=jsonObj
- operationJson["operation"]=detailsJson
- jsonData=json.dumps(operationJson)
- if createrequest == True:
- #Constructing the url for the API call and submitting that to the ServiceDesk Plus server
- apprUrl = url + "/sdpapi/request/"
- data = {'INPUT_DATA' : jsonData ,'TECHNICIAN_KEY': TechnicianKey,'format':'json','OPERATION_NAME':OperationName}
- r = s.post(apprUrl,data)
-
- if(r.status_code == 200): #Checking if the API Request was Submitted successfully.The Status Code 200 is returned if the POST operation had succeeded
-
-
- #Reading the Json Response got by submitting the API request to the ServiceDesk application.Given below is a sample response got from the Application.
- '''{"operation": {"result": {"status": "Success","message": "Request details added successfully."},"Details": {"WORKORDERID": "217","REQUESTER": "Shawn Adams","CREATEDBY": "Gopinath","CREATEDTIME": "1470141311306","DUEBYTIME": "1470198600306"}}}'''
- responseobj=r.json()
- status=responseobj['operation']['result']['status']
- message=responseobj['operation']['result']['message']
-
- # If the Status is 'Success' in the Response,this indicates that the request was created successfully.We proceed by adding a Note in the Parent Request.
- if status == 'Success':
-
- #The Id of the newly created request is read here from the Details Json Object
- id=responseobj['operation']['Details']['WORKORDERID']
- #Creating the json object for Adding a Note in the Parent Request.A Sample of the json object to Add Notes is given below.
- '''{"message":"Request Added Successfully","result":"success","operation":[{"INPUT_DATA": [{"notes": {"notestext":"Ticket has been created in JIRA and information populated in SDP"}}],"OPERATIONNAME":"ADD_NOTE"}],}'''
- addnotejson={}
- addnotejson["operation"] = []
- addnotejson["result"]="success"
- operationjson={"INPUT_DATA":[]}
- operationjson["OPERATIONNAME"]="ADD_NOTE"
- notesArray={}
- noteObject={}
- noteJson={}
- noteObject["notestext"]="Child Request Created with ID: "+id+"</br> Request Link: <ticket system url>"+id #This is the actual Note Text, which can be customized based on the Requirement.Update this link with the protocol and servername:portnumber values of the ServiceDesk Plus application.
- noteJson["notes"]=noteObject
- notesArray["notes"]=noteObject
- addnotejson["message"] = "A Child Request has been Created and Note with the Request id has been added." #This message will be displayed in the Parent Request's History
- operationjson['INPUT_DATA'].append(notesArray)
- addnotejson['operation'].append(operationjson)
- print(addnotejson)##"New Request Created Successfully: "+id)
-
-
- #If the Status is not Success,this indicates that the Request was not created successfully and we will show the Failure Message in the History Tab of the Parent Request.This will provide the necessary information about why the request Creation had Failed.
- else:
-
- print(status)
- print(message)
-
- #If the API request was not submitted successfully, we will print the Error Message given below along with the Error Json Response got from the Server.This will help in troubleshooting the reason why the http request failed.
- else :
- print("Problem submitting session request")
- print(r.json())
- else:
- print("No Requests created through Custom Triggers")
Can anyone help me figure out the best way to be able to add linking commands to link the parent and child request to this script?
Thanks for your help in advance.
New to ADSelfService Plus?