def resolve_all_incidents(self, args): """ This resolves all the incidents the user was paged for. """ message = MessageClass() url = settings.VICTOROPS_RESOLVE_ALL_INCIDENTS body = { "userName": self.victor_ops_uid, "message": args['Resolution-Message'] } # PATCH request to victorops server response = requests.patch(url, headers=self.headers, data=json.dumps(body)) r_text = response.text if re.search(r'User not found', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "User not found" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() attachment.text = "Resolved all the incidents!" message.attach(attachment) return message.to_json()
def resolve_incidents(self, args): """ This resolves an incident or a list of incidents. """ message = MessageClass() url = settings.VICTOROPS_RESOLVE_INCIDENTS incident_list = args['Incident-Numbers'].split(',') body = { "userName": self.victor_ops_uid, "incidentNames": incident_list, "message": args['Resolution-Message'] } # PATCH request to victorops server response = requests.patch(url, headers=self.headers, data=json.dumps(body)) r_text = response.text if re.search(r'Already', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "The incident is already resolved" message.attach(attachment) return message.to_json() elif re.search(r'User not found', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "User not found" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() attachment.text = "Resolved!" message.attach(attachment) return message.to_json()
def ack_incidents(self, args): """ This acknowledges an incident or a list of incidents. """ message = MessageClass() url = settings.VICTOROPS_ACK_INCIDENTS # If there are multiple incidents they are split and added to an array incident_list = args['Incident-Numbers'].split(',') body = { "userName": self.victor_ops_uid, "incidentNames": incident_list, "message": args['Acknowledgement-Message'] } # PATCH request to victorops server response = requests.patch(url, headers=self.headers, data=json.dumps(body)) r_text = response.text if re.search(r'Already', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "The incident is already resolved" message.attach(attachment) return message.to_json() elif re.search(r'User not found', r_text, re.M | re.I): attachment = MessageAttachmentsClass() attachment.text = "User not found" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() attachment.text = "Acknowledged!" message.attach(attachment) return message.to_json()
def get_incident(self, args): """ Get information corresponding to the given incident_uuid """ incident_id = args['Incident-UUID'] url = (settings.VICTOROPS_INCIDENT_ALERT_URL + incident_id) # get request to victorops server response = requests.get(url, headers=self.headers) # print(response) response_json = response.json() # print(response_json) message = MessageClass() message.message_text = "Incident Details" # if the ID does not have an incident associated with it. if response.status_code == 422: attachment = MessageAttachmentsClass() attachment.text = "No incident found for the given ID!" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Incident Description" field1.value = response_json['entityDisplayName'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Incident Body" field2.value = response_json['stateMessage'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Entity ID" field3.value = response_json['entityId'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Incident Type" field4.value = response_json['messageType'] attachment.attach_field(field4) try: # val = response_json['ackAuthor'] field5 = AttachmentFieldsClass() field5.title = "Acknowledged By" field5.value = response_json['ackAuthor'] attachment.attach_field(field5) except: pass message.attach(attachment) # print(message) # message = json.dumps(message) # return message # print(type(message)) return message.to_json()
def create_invoice(self, args): """ This function is used to create an invoice given the org ID, customer ID,date, Item ID and the quantity """ org_id = args['organization'] customer_id = args['customer_id'] date = args['date'] item_id = args['item_id'] quantity = args['quantity'] # org_id = "669665442" # customer_id = "1392605000000069001" # date = "2018-07-27" # item_id = "1392605000000072001" # quantity = 1 headers = { "Authorization": "Zoho-oauthtoken" + " " + self.zohoinvoice_access_token, "X-com-zoho-invoice-organizationid": org_id, "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" } url = settings.ZOHO_INVOICE_URL payload = { "customer_id": customer_id, "date": date, "line_items": [{ "item_id": item_id, "quantity": quantity, }], } response = requests.post(url, headers=headers, data={"JSONString": json.dumps(payload)}) response_json = response.json() print(response) print(response_json) message = MessageClass() if response.status_code == 400: attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Error" field1.value = response_json['message'] attachment.attach_field(field1) message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() attachment.text = "Invoice created" message.attach(attachment) return message.to_json()
def get_complaints(self, args): print("In get_complaints") # API parameteres for getting account information auth = ("api", self.mailgun_access_token) # Consuming the API r = requests.get("https://api.mailgun.net/v3/" + self.domain_name + "/complaints", auth=("api", self.mailgun_access_token)) # NOT USED here sample_response = { "items": [{ "address": "*****@*****.**", "created_at": "Fri, 21 Oct 2011 11:02:55 GMT" }] } # Response check if r.status_code == requests.codes.ok: # Getting response in JSON print(print(json.loads(r.text))) response = json.loads(r.text) # Creating message objects to structure the message to be shown if (len(response['items']) == 0): message = MessageClass() message.message_text = "You don't have any complaints as of now !" return message.to_json() message = MessageClass() message.message_text = "Complaint details :" attachment = MessageAttachmentsClass() for i in range(0, len(response['items'])): field1 = AttachmentFieldsClass() field1.title = "Address :" field1.value = response['items'][i]["address"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Created at :" field2.value = response['items'][i]["created_at"] attachment.attach_field(field2) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def list_users(self, args): """ Returns data about all users within the company """ url = settings.PIPEDRIVE_LIST_ADD_USERS_URL + self.pipedrive_api_token response = requests.get(url, headers=self.headers) response_json = response.json() # print(response_json) message = MessageClass() message.message_text = "Users" if not bool(response_json): attachment = MessageAttachmentsClass() attachment.text = "No users!" message.attach(attachment) return message.to_json() else: userinfo = response_json['data'] for user in userinfo: attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Name" field1.value = user['name'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "ID" field2.value = user['id'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Email" field3.value = user['email'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Phone" field4.value = "-" if user['phone'] is None else user['phone'] attachment.attach_field(field4) field5 = AttachmentFieldsClass() field5.title = "Default currency" field5.value = user['default_currency'] attachment.attach_field(field5) field6 = AttachmentFieldsClass() field6.title = "Admin" field6.value = 'True' if user['is_admin'] else 'False' attachment.attach_field(field6) message.attach(attachment) return message.to_json()
def status (self,args): tweet=args['tweet'] try: self.api.update_status(tweet) except: m = MessageClass() m.message_text="Status not updated!!!" return m.to_json() m=MessageClass() m.message_text="Status Updated!!!" return m.to_json()
def favourite(self,args): id=args['id'] try: self.api.create_favorite(id) except: m = MessageClass() m.message_text="Status can't be added to favourites!!!" return m.to_json() m=MessageClass() m.message_text="Status with id=" + id + " is added to favorites!!!" return m.to_json()
def unfollow(self,args): handle=args['handle'] try: self.api.destroy_friendship(handle) except: m = MessageClass() m.message_text="can't unfollow!!!" return m.to_json() m=MessageClass() m.message_text="Person with screen_name="+handle+ " is unfollowed!!!" return m.to_json()
def follow(self,args): handle=args['handle'] try: self.api.create_friendship(handle) except: m = MessageClass("person can't be followed") m.message_text="!!!" return m.to_json() m=MessageClass() m.message_text="you followed a person with screen_name="+handle return m.to_json()
def dm(self,args): handle=args['handle'] message=args['message'] try: self.api.send_direct_message(handle,text=message) except: m = MessageClass() m.message_text="Message can't be sent!!!" return m.to_json() m=MessageClass() m.message_text="You just successfully sent a message to user "+handle return m.to_json()
def get_space_usage(self, args): print("In get_space_usage") headers = { 'Authorization': 'Bearer ' + str(self.dropbox_access_token), } # Consuming the API r = requests.post('https://api.dropboxapi.com/2/users/get_space_usage', headers=headers) # Response check if r.status_code == requests.codes.ok: # Fetching response in JSON response = r.content.decode("utf-8") response = json.loads(response) print(response) #Creating a message object from YA SDK message = MessageClass() message.message_text = "Space usage/allocation details :" attachment = MessageAttachmentsClass() used_gb = float(response['used'] / 1000000000) allocated_gb = float(response['allocation']['allocated'] / 1000000000) field1 = AttachmentFieldsClass() field1.title = "Used : " field1.value = str( Decimal(str(used_gb)).quantize(Decimal('.01'), rounding=ROUND_DOWN)) + " gb" attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Allocated : " field2.value = str( Decimal(str(allocated_gb)).quantize( Decimal('.01'), rounding=ROUND_DOWN)) + " gb" attachment.attach_field(field2) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def create_incident(self, args): """ Creates a new incident given the incident body, description and the user to be paged for the incident A flag is also returned which denotes the success or the failure of incident creation which is used to provide a webhook. """ url = settings.VICTOROPS_CREATE_LIST_INCIDENT # Check if the user to be paged exists if self.test_get_user(args['Send-To']) == 0: message = MessageClass() attachment = MessageAttachmentsClass() attachment.text = "User not found!" message.attach(attachment) return message.to_json() else: body = { "summary": args['Incident-Summary'], "details": args['Incident-Body'], "userName": self.victor_ops_uid, "targets": [{ "type": "User", "slug": args['Send-To'] }] } response = requests.post(url, headers=self.headers, data=json.dumps(body)) message = MessageClass() attachment = MessageAttachmentsClass() attachment.text = "Incident created " r_text = response.text print(r_text) # A regex check to find the incident number of the new incident incident_nos = re.findall("\d+", r_text) # print(incident_nos) # print(incident_nos[0]) entity_id, vo_uuid = self.test_list_incidents(incident_nos[0]) field2 = AttachmentFieldsClass() field2.title = "Entity ID" field2.value = entity_id # print(field2.value) attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "VO_UUID" field3.value = vo_uuid attachment.attach_field(field3) message.attach(attachment) return message.to_json()
def get_domain(self, args): """ Get a single domain """ # API parameteres for getting account information auth = ("api", self.mailgun_access_token) # Consuming the API r = requests.get("https://api.mailgun.net/v3/domains/" + str(self.domain_name), auth=auth) print(self.mailgun_access_token) # Response check if r.status_code == requests.codes.ok: # Getting response in JSON print(json.loads(r.content.decode("utf-8"))) response = json.loads(r.content.decode("utf-8")) # Creating message objects to structure the message to be shown message = MessageClass() message.message_text = "Domain details :" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Domain :" field1.value = response['domain']["name"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "State :" field2.value = response['domain']["state"] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Created at :" field3.value = response['domain']['created_at'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Type :" field4.value = response['domain']['type'] attachment.attach_field(field4) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def get_account_info(self, args): print("In get_company_info") endpoint = "https://api.dropboxapi.com/2/users/get_account" # API parameteres for getting account information headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"account_id": str(self.account_id)} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/users/get_account', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: # Getting response in JSON response = r.content.decode("utf-8") response = json.loads(response) # Creating message objects to structure the message to be shown message = MessageClass() message.message_text = "User Account Details :" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = response["name"]["display_name"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "E-mail :" field2.value = response["email"] attachment.attach_field(field2) attachment.image_url = response["profile_photo_url"] message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def send_mail(self, args): print("In send_mail") # Arguments from slack to = args['to'] text = args['text'] subject = args['subject'] # API parameteres for getting account information auth = ("api", self.mailgun_access_token) # sample payload data = { "from": "mailgun" + "@" + self.domain_name, "to": [to, "mailgun" + "@" + self.domain_name], "subject": subject, "text": text } # Consuming the API r = requests.post("https://api.mailgun.net/v3/" + self.domain_name + "/messages", auth=auth, data=data) # NOT USED here sample_response = { "message": "Queued. Thank you.", "id": "<*****@*****.**>" } # Response check if r.status_code == requests.codes.ok: # Getting response in JSON print(print(json.loads(r.text))) response = json.loads(r.text) # Creating message objects to structure the message to be shown message = MessageClass() message.message_text = response["message"] return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = json.loads(r.content.decode("utf-8")) m.message_text = d['message'] return m.to_json()
def get_space_usage(self,args): print("In get_space_usage") headers = { 'Authorization': 'Bearer ' + str(self.dropbox_access_token), } # Consuming the API r = requests.post('https://api.dropboxapi.com/2/users/get_space_usage', headers=headers) # Response check if r.status_code == requests.codes.ok: # Fetching response in JSON response = r.content.decode("utf-8") response = json.loads(response) print(response) #Creating a message object from YA SDK message = MessageClass() message.message_text = "Space usage/allocation details :" attachment = MessageAttachmentsClass() used_gb = float(response['used']/1000000000) allocated_gb = float(response['allocation']['allocated']/1000000000) field1 = AttachmentFieldsClass() field1.title = "Used : " field1.value = str(Decimal(str(used_gb)).quantize(Decimal('.01'), rounding=ROUND_DOWN)) + " gb" attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Allocated : " field2.value = str(Decimal(str(allocated_gb)).quantize(Decimal('.01'), rounding=ROUND_DOWN)) + " gb" attachment.attach_field(field2) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def get_account_info(self,args): print("In get_company_info") endpoint = "https://api.dropboxapi.com/2/users/get_account" # API parameteres for getting account information headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"account_id": str(self.account_id)} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/users/get_account', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: # Getting response in JSON response = r.content.decode("utf-8") response = json.loads(response) # Creating message objects to structure the message to be shown message = MessageClass() message.message_text = "User Account Details :" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = response["name"]["display_name"] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "E-mail :" field2.value = response["email"] attachment.attach_field(field2) attachment.image_url = response["profile_photo_url"] message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def list_incidents(self, args): """ This functions returns the list of the currently open, acknowledged and recently resolved incidents. """ url = settings.VICTOROPS_CREATE_LIST_INCIDENT response = requests.get(url, headers=self.headers) response_json = response.json() print(response_json) data = response_json["incidents"] # response_json = response_json.json() message = MessageClass() message.message_text = "All incidents : " # Check if there are incidents present if not bool(response_json): attachment = MessageAttachmentsClass() attachment.text = "No incidents" message.attach(attachment) return message.to_json() else: for details in data: attachment = MessageAttachmentsClass() field2 = AttachmentFieldsClass() field2.title = "Incident Number" field2.value = details["incidentNumber"] # print(field2.value) attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Current Phase" field3.value = details["currentPhase"] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Entity ID" field4.value = details["entityId"] attachment.attach_field(field4) field5 = AttachmentFieldsClass() field5.title = "VO_UUID" field5.value = details["lastAlertId"] attachment.attach_field(field5) message.attach(attachment) return message.to_json()
def list_users(self, args): """ Gives information about the users of the organization """ url = settings.VICTOROPS_ALL_USERS response = requests.get(url, headers=self.headers) response_json = response.json() # print(response_json) message = MessageClass() message.message_text = "Users" if not bool(response_json): attachment = MessageAttachmentsClass() attachment.text = "No users!" message.attach(attachment) return message.to_json() else: data = response_json['users'][0] for i in range(len(data)): attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Username" field1.value = data[i]['username'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Name" field2.value = str(data[i]['firstName']) + " " + str( data[i]['lastName']) attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Email" field3.value = data[i]['email'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Password Last Updated" field4.value = data[i]['passwordLastUpdated'] attachment.attach_field(field4) field5 = AttachmentFieldsClass() field5.title = "Verified" field5.value = data[i]['verified'] attachment.attach_field(field5) message.attach(attachment) return message.to_json()
def get_user(self, args): """ This function is used to get the user details given the victorops user id """ user = args['User-ID'] # VictorOps user ID url = settings.VICTOROPS_GET_USER + str(user) response = requests.get(url, headers=self.headers) response_json = response.json() message = MessageClass() message.message_text = "User Details" if bool(response_json) == False: attachment = MessageAttachmentsClass() attachment.text = "No user found!" message.attach(attachment) return message.to_json() else: attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Username" field1.value = response_json['username'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Name" field2.value = str(response_json['firstName']) + " " + str( response_json['lastName']) attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Email" field3.value = response_json['email'] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Password Last Updated" field4.value = response_json['passwordLastUpdated'] attachment.attach_field(field4) field5 = AttachmentFieldsClass() field5.title = "Verified" field5.value = response_json['verified'] attachment.attach_field(field5) message.attach(attachment) return message.to_json()
def list_all_customer_ids(self, args): ''' Picklist function to get list of customer ids ''' print("In list_all_customer_ids") # API call parameters for getting all customer ids route = "/v3/company/" + self.realmID + "/query?query=select * from Customer" bearer = getBearerTokenFromRefreshToken( self.quickbook_access_token_object.refreshToken, self.user_integration) auth_header = 'Bearer ' + bearer.accessToken headers = { 'Authorization': auth_header, 'content-type': 'application/json' } # Consuming the API r = requests.get(settings.PRODUCTION_BASE_URL + route, headers=headers) # Response check if r.status_code == requests.codes.ok: # Fetching response in JSON response = json.loads(json.dumps(xmltodict.parse(r.text))) # print(response) customer_data = response['IntuitResponse']['QueryResponse'][ 'Customer'] # Creating a message object using YA SDK functions m = MessageClass() m.message_text = "This is list all customer picklist function" ### Hardcoded ### Change It ! data = [] #customer_data[i] for i in range(0, len(customer_data)): data.append({"id": "12"}) m.data = data return m.to_json() else: m = MessageClass() d = json.loads(r.text) m.message_text = d["Fault"]["Error"][0]["Detail"] return m.to_json() #"{0}: {1}".format(r.status_code, r.text)
def account_view(self,args): """For viewing the account details""" query = "api_key="+self.API_Access_key+"&api_action=account_view&api_output=json" url = (self.API_Access_URL + "/admin/api.php?"+ query) print(self.API_Access_URL) print(url) response = requests.get(url) response_json = response.json() message = MessageClass() message.message_text = "Account Details:" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Account" field1.value = response_json['account'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Email" field2.value = response_json['email'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Subscriber Limit" field3.value = response_json['subscriber_limit'] attachment.attach_field(field3) message.attach(attachment) return message.to_json()
def deal_get(self, args): """For viewing the account details""" id = args['Id'] query = "api_key=" + self.API_Access_key + "&api_action=deal_get&api_output=json&id="+id url = (self.API_Access_URL + "/admin/api.php?" + query) print(self.API_Access_URL) print(url) response = requests.get(url) response_json = response.json() print(response_json) message = MessageClass() message.message_text = "Account Details:" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Title" field1.value = response_json['title'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Contact Email" field2.value = response_json['contact_email'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Deal Notes" field3.value = response_json['deal_notes'] attachment.attach_field(field3) message.attach(attachment) message.message_text = "The Details of Deal are:" return message.to_json()
def list_user_details(self, args): if 'id' not in args: return self.generate_simple_message( "Please provide parameter 'id' in your command") else: #Check if Id is a number if args['id'].is_digit(): user_id = int(args['id']) else: return self.generate_simple_message( "Please provide an integer value for parameter 'id' in your command" ) try: #Searching for user with id user_object = SiteUsers.objects.get(id=user_id) except SiteUsers.DoesNotExist: #return error message if user does not exist return self.generate_simple_message( "User with that id does not exist") user_details_message = MessageClass() user_details_message.message_text = "User Id - %d, Fullname - %s, Date joined - %s, Subscription - %s" % ( user_id, user_object.full_name, user_object.date_joined, user_object.subscription) user_json = serializers.serialize("json", user_object) #Adding JSON data to message for use in workflows user_details_message.data = user_json return user_details_message.to_json()
def change_user_subcription(self, args): if 'id' not in args or 'subscription' not in args: return self.generate_simple_message( "Please provide parameter 'id' and 'subscription' in your command" ) else: #Check if Id is a number if args['id'].is_digit(): user_id = int(args['id']) else: return self.generate_simple_message( "Please provide an integer value for parameter 'id' in your command" ) try: #Searching for user with id user_object = SiteUsers.objects.get(id=user_id) #changing subscription value user_object.subscription = args['subscription'] except SiteUsers.DoesNotExist: #return error message if user does not exist return self.generate_simple_message( "User with that id does not exist") user_details_message = MessageClass() user_details_message.message_text = "User subscription changed" user_json = serializers.serialize("json", user_object) #Adding JSON data to message for use in workflows user_details_message.data = user_json return user_details_message.to_json()
def all_page_ids(self,args): ''' Get all page ids for the user Basic inactive function to get dynamic inputs in all other functions. ''' sot = self.statuspage_access_token_object print(sot.user_integration_id) page_objects = PageDetail.objects.filter(user_integration_id=sot) m = MessageClass() data = [] m.message_text = "Here are your pages" #:\n" if len(page_objects) > 0 else "You don't have any pages." for page_object in page_objects: url = (settings.SP_API_BASE1 + page_object.page_id + ".json") response = requests.get(url, headers=self.headers) response_json = response.json() m.message_text += "{} - {}\n".format(response_json["name"], page_object.page_id) data.append({"name": response_json["name"],"page_id":str(page_object.page_id)}) # m = MessageClass() # data = [] # data.append({"page_id":"dfdsdfvd"}) # m.message_text = "Lol" m.data = data print(m.data) return m.to_json()
def Collectors_Available(self, args): print("In view_details") survey_id = args["SurveyId"] url = "https://api.surveymonkey.com/v3/surveys/%s/collectors"%(survey_id) message = MessageClass() result = "Collectors available are: \n" try: response = requests.get(url, headers=self.headers) response_json = response.json() data = response_json["data"] send_data = {\ "collectors":[]\ } for i in range(len(data)): obj = data[i] name = obj["name"] id = obj["id"] send_data["collectors"].append({"id":id, "name":name}) result = result + str(i+1)+": "+ name+" "+ "ID is: "+ id+"\n" message.data = send_data message.message_text = result print(send_data) # use inbuilt sdk method to_json to return message in a json format accepted by YA return message.to_json() except Exception as e: print(str(e)) traceback.print_exc()
def deal_list(self, args): """For viewing the account details""" query = "api_key=" + self.API_Access_key + "&api_action=deal_list&api_output=json" url = (self.API_Access_URL + "/admin/api.php?" + query) response = requests.get(url) response_json = response.json() message = MessageClass() attachment = MessageAttachmentsClass() for i in response_json['deals']: field1 = AttachmentFieldsClass() field1.title = "Title" field1.value = i['title'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Email" field2.value = i['contact_email'] attachment.attach_field(field2) message.attach(attachment) message.message_text = "List of deals:" return message.to_json()
def Survey_Lang_Available(self, args): # Return the available languages in which the Survey can be translated. print("In SurveyLangAvailable") survey_id = args["Survey-ID"] url = "https://api.surveymonkey.com/v3/surveys/%s/languages"%(survey_id) response = requests.get(url, headers=self.headers) response_json = response.json() print(response_json) data = response_json["data"] message = MessageClass() result = "Languages available are: \n" for i in range(len(data)): obj = data[i] lang = obj["name"] id = obj["id"] result = result + lang + " " + "ID is: "+ id+ "\n" message.message_text = result # use inbuilt sdk method to_json to return message in a json format accepted by YA return message.to_json() # def Collectors(self, args): # print("In collectors") # CollectorId = args["CollectorId"] # # url = "https://api.surveymonkey.com/v3/collectors/%s"%(CollectorId) # response = requests.get(url, headers=self.headers) # response_json = response.json() # # print(response_json) # return "Hey"
def get_organization(self, args): """ This function gets the ID and the name of the organization. This is a picklist function used by all other functions """ headers = { "Content-Type": "application/json", "Authorization": "Zoho-oauthtoken" + " " + self.zohoinvoice_access_token } url = settings.ZOHO_ORGANIZATION_URL response = requests.get(url, headers=headers) # print(response.text) # print(type(response)) response_json = response.json() # print(response_json) data = response_json['organizations'] message = MessageClass() message.message_text = "Organization list:" name_list = {'org': []} for i in data: name_list['org'].append({ "id": str(i['organization_id']), "name": str(i['name']) }) message.data = name_list print(message.data) return message.to_json()
def get_all_shared_folders(self,args): print("In get_all_shared_folders") endpoint = "https://api.dropboxapi.com/2/sharing/list_folders" headers = { 'Authorization': 'Bearer ' + str(self.dropbox_access_token), 'Content-Type': 'application/json', } data = {"limit": 100,"actions": []} # Consuming the API r = requests.post(endpoint, headers=headers, json=data) # Response check if (r.status_code == requests.codes.ok): response = r.content.decode("utf-8") response = json.loads(response) print(response) #Creating message from YA SDK message = MessageClass() message.message_text = "All shared file details :" attachment = MessageAttachmentsClass() for i in range(0,len(response['entries'])): field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = response['entries'][i]['name'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Preview URL :" field2.value = response['entries'][i]['preview_url'] attachment.attach_field(field2) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def download_file(self,args): print("In download_file") # Fetching the arguments passed from slack path = args['path'] # API call parameters for creating a customer headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"path": path} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/files/get_temporary_link', headers=headers, json=data) # Response check if (r.status_code == requests.codes.ok): # Getting the response response = r.content.decode("utf-8") response = json.loads(response) print(response) # Creating message using YA SDK message = MessageClass() message.message_text = "Temporary link to download :" attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "This link expires in 4 Hr :" field1.value = response['link'] attachment.attach_field(field1) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def get_all_file_requests(self,args): print("In get_all_file_requests") # API call parameters for creating an invoice headers = { 'Authorization': 'Bearer ' + str(self.dropbox_access_token), } # Consuming the API r = requests.post('https://api.dropboxapi.com/2/file_requests/list', headers=headers) # Response check if r.status_code == requests.codes.ok: response = r.content.decode("utf-8") response = json.loads(response) print(response) # Creating message from YA SDK message = MessageClass() attachment = MessageAttachmentsClass() if len(response) == 0: message.message_text = "No File Requests" message.attach(attachment) return message.to_json() else: message.message_text = "All file requests :" message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def get_shared_links(self,args): print("In get_shared_links") flag = False # Arguments passed from slack # For the optional argument try: path = args['path'] flag = True except: flag = False headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } endpoint = 'https://api.dropboxapi.com/2/sharing/list_shared_links' if flag == True: data = {"path": path} else: data = {} # Consuming the API r = requests.post(endpoint, headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: # Getting response in JSON response = r.content.decode("utf-8") response = json.loads(response) print(response) links = response['links'] message = MessageClass() message.message_text = "List of all shared links :" attachment = MessageAttachmentsClass() for i in range(0,len(links)): try: field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = links[i]['name'] attachment.attach_field(field1) except KeyError : 'name' # field2 = AttachmentFieldsClass() # field2.title = "Type :" # field2.value = links[i]['.tag'] # attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Preview URL :" field3.value = links[i]['url'] attachment.attach_field(field3) message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def get_all_folders(self,args): print("In get_all_folders") # API call parameters for getting all customers path = args['path'] headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } if path == '/': path = "" data = {"path": path, "recursive": True, "include_media_info": False, "include_deleted": False, "include_has_explicit_shared_members": False, "include_mounted_folders": True} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/files/list_folder', headers=headers, json=data) # Error check if r.status_code == requests.codes.ok: # Getting response in JSON format response = r.content.decode("utf-8") response = json.loads(response) print(response) message = MessageClass() message.message_text = "List files and folders :" attachment = MessageAttachmentsClass() for i in range(0, len(response['entries'])): field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = response['entries'][i]['name'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Type :" field2.value = response['entries'][i]['.tag'] attachment.attach_field(field2) attachment2 = MessageAttachmentsClass() if response['has_more'] == True: button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get more files and folders" button.command = { "service_application": str(self.user_integration.yellowant_integration_id), "function_name": 'get_more_folders', "data": {"cursor": response['cursor']} } attachment2.attach_button(button) message.attach(attachment) message.attach(attachment2) return message.to_json() message.attach(attachment) return message.to_json() else: m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def get_more_folders(self,args): print("In get_more_folders") # Fetching arguments passed from Slack cursor = args['cursor'] # API call parameters for getting customer details headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"cursor": cursor} re = requests.post('https://api.dropboxapi.com/2/files/list_folder/continue', headers=headers, json=data) if re.status_code == requests.codes.ok: res = re.content.decode("utf-8") res = json.loads(res) print("----") print(res) message = MessageClass() message.message_text = "More files and folders :" attachment = MessageAttachmentsClass() for i in range(0, len(res['entries'])): field1 = AttachmentFieldsClass() field1.title = "Name :" field1.value = res['entries'][i]['name'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Type :" field2.value = res['entries'][i]['.tag'] attachment.attach_field(field2) attachment2 = MessageAttachmentsClass() if res['has_more'] == True: button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get more files and folders" button.command = { "service_application": str(self.user_integration.yellowant_integration_id), "function_name": 'get_more_folders', "data": {"cursor": res['cursor']} } attachment2.attach_button(button) message.attach(attachment) message.attach(attachment2) return message.to_json() message.attach(attachment) return message.to_json() else: m = MessageClass() print(re.content.decode("utf-8")) d = re.content.decode("utf-8") m.message_text = "{0}: {1}".format(re.status_code, re.text) return m.to_json()
def search(self,args): print("In search") print(args) path = args['path'] query = args['search'] headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } if path == '/': path = "" data = {"path": path,"query": query,"start": 0,"max_results": 100,"mode": "filename"} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/files/search', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: print("---------------") # Getting response in JSON r = r.content.decode("utf-8") response = json.loads(r) print(response) # Creating message using YA SDK message = MessageClass() if len(response['matches']) == 0: message.message_text = "No matches !\nPlease search again." return message.to_json() message.message_text = "Matches :" attachment = MessageAttachmentsClass() for i in range(0, len(response['matches'])): field1 = AttachmentFieldsClass() field1.title = "Path:" field1.value = response['matches'][i]['metadata']['path_display'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Name :" field2.value = response['matches'][i]['metadata']['name'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Type :" field3.value = response['matches'][i]['metadata']['.tag'] attachment.attach_field(field3) message.attach(attachment) return message.to_json() else: print("Error") m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def share_folder(self, args): print("In share_folder") # Arguments from slack path = args["path"] member_policy = args['member_policy'] shared_link_policy = args['shared_link_policy'] if member_policy != 'anyone' and member_policy != "team": m = MessageClass() m.message_text = "Invalid value in member_policy argument" return m.to_json() if shared_link_policy != 'anyone' and shared_link_policy != "team": m = MessageClass() m.message_text = "Invalid value in shared_link_policy argument" return m.to_json() # API call parameters for getting all customer ids headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } data = {"path": path,"acl_update_policy": "editors","force_async": False,"member_policy": member_policy ,"shared_link_policy": shared_link_policy} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/sharing/share_folder', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: # Fetching response in JSON r = r.content.decode("utf-8") response = json.loads(r) print(response) # Creating a message object using YA SDK functions m = MessageClass() m.message_text = "Details for the shared folder : " attachment = MessageAttachmentsClass() field1 = AttachmentFieldsClass() field1.title = "Shared link : " field1.value = response['preview_url'] attachment.attach_field(field1) field2 = AttachmentFieldsClass() field2.title = "Visibility :" field2.value = response['policy']['shared_link_policy']['.tag'] attachment.attach_field(field2) field3 = AttachmentFieldsClass() field3.title = "Name :" field3.value = response['name'] attachment.attach_field(field3) m.attach(attachment) return m.to_json() else: print("Error") m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()
def create_folder(self, args): print("In create_folder") print(args) path = args['path'] autorename = args['autorename'] if autorename != 'true' and autorename != 'false': m = MessageClass() m.message_text = "Invalid value in autorename argument" return m.to_json() headers = { 'Authorization': 'Bearer ' + self.dropbox_access_token, 'Content-Type': 'application/json', } if autorename == 'true': autorename = True else: autorename = False data = {"path": path,"autorename": autorename} # Consuming the API r = requests.post('https://api.dropboxapi.com/2/files/create_folder_v2', headers=headers, json=data) # Response check if r.status_code == requests.codes.ok: print("---------------") # Getting response in JSON r = r.content.decode("utf-8") response = json.loads(r) print(response) #Creating message using YA SDK message = MessageClass() attachment = MessageAttachmentsClass() attachment2 = MessageAttachmentsClass() message.message_text = "New folder successfully created" button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get folder details" button.command = { "service_application": str(self.user_integration.yellowant_integration_id), "function_name": 'get_all_folders', "data" :{"path": response['metadata']['path_display'], "recursive": True, "include_media_info": False, "include_deleted": False, "include_has_explicit_shared_members": False, "include_mounted_folders": True} } attachment2.attach_button(button) message.attach(attachment) message.attach(attachment2) return message.to_json() else: print("Error") m = MessageClass() print(r.content.decode("utf-8")) d = r.content.decode("utf-8") m.message_text = "{0}: {1}".format(r.status_code, r.text) return m.to_json()