def webhook_delivered(request, webhook_id): print("In webhook_delivered") """ Webhook function to notify user about update in component """ urllib.parse.unquote(request.body.decode("utf-8")) params_dict = urllib.parse.parse_qsl(request.body) params = dict(params_dict) #Extracting necessary data recipient = params[b'recipient'].decode('utf-8') # Fetching yellowant object try: yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Mail delivered to " + str(recipient) attachment = MessageAttachmentsClass() attachment.title = "Mail Stats upto last 1 month" button_get_components = MessageButtonsClass() button_get_components.name = "1" button_get_components.value = "1" button_get_components.text = "Get all stats" button_get_components.command = { "service_application": service_application, "function_name": 'get_stats', "data": {} } attachment.attach_button(button_get_components) webhook_message.data = {"recipient_email_id": recipient} webhook_message.attach(attachment) #print(integration_id) # Creating yellowant object yellowant_user_integration_object = YellowAnt( access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="notify_delivered", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def update_incident(request,webhook_id): print("In update_incident") """ Webhook function to notify user about update in incident """ # Extracting necessary data data = (request.body.decode('utf-8')) response_json = json.loads(data) page_id = response_json['page']['id'] unsubscribe = response_json['meta']['unsubscribe'] incident_id = response_json['incident']['id'] name = response_json['incident']['name'] try: # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Updates in incident with Id : " + str(incident_id) + "\nName : " + str(name) attachment = MessageAttachmentsClass() attachment.title = "Incident operations" button_get_incidents = MessageButtonsClass() button_get_incidents.name = "1" button_get_incidents.value = "1" button_get_incidents.text = "Get all incidents" button_get_incidents.command = { "service_application": service_application, "function_name": 'all_incidents', "data": { 'page_id': page_id } } attachment.attach_button(button_get_incidents) webhook_message.data = {"page_id": page_id} webhook_message.attach(attachment) #print(integration_id) # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="incident_updates_webhook", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def next_page(self, args): """This returns the list of functions in the next page""" message = MessageClass() region = args['Region'] next_marker = args['NextMarker'] aws_lambda = boto3.client(service_name='lambda', region_name=region, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=self.aws_access_key, aws_secret_access_key=self.aws_secret_token, aws_session_token=None, config=None) # Gets the next ten functions in lambda response = aws_lambda.list_functions(Marker=next_marker, MaxItems=10) functions = [Function['FunctionName'] for Function in response['Functions']] for Function in functions: attachment = MessageAttachmentsClass() attachment.title = Function # Button to get the logs of the function button = MessageButtonsClass() button.text = "Get Logs" button.value = "Get Logs" button.name = "Get Logs" button.command = {"service_application": self.yellowant_integration_id, "function_name": "get-logs", "data": {"FunctionName": Function, "Region": region}} attachment.attach_button(button) # Button to invoke the function button1 = MessageButtonsClass() button1.text = "Invoke" button1.value = "Invoke" button1.name = "Invoke" button1.command = {"service_application": self.yellowant_integration_id, "function_name": "invoke-async", "data": {"Function-Name": Function, "Region": region}, "inputs": ["input"]} attachment.attach_button(button1) message.attach(attachment) try: # Button to get the functions in next page, Checks actually if next page exists or not attachment = MessageAttachmentsClass() button2 = MessageButtonsClass() button2.text = "Next Page" button2.value = "Next Page" button2.name = "Next Page" button2.command = {"service_application": self.yellowant_integration_id, "function_name": "next-page", "data": {"NextMarker": response['NextMarker'], "Region": region}} attachment.attach_button(button2) message.attach(attachment) message.message_text = "The Functions present are:" except: message.message_text = "This is the Last page and The Functions present are: " return message.to_json()
def run(self): """Method which runs when the thread is started""" global GROUP_NAME, VM_NAME, USERNAME, PASSWORD message = MessageClass() credentials, subscription_id = get_credentials(self.user_integration) compute_client = ComputeManagementClient(credentials, subscription_id) network_client = NetworkManagementClient(credentials, subscription_id) GROUP_NAME = self.args.get("Resource-Group") VM_NAME = self.args.get("VM-Name") NIC_NAME = self.args.get("nic_name") IP_CONFIG_NAME = self.args.get("ipconfig_name") USERNAME = self.args.get("username") PASSWORD = self.args.get("password") VNET_NAME = self.args.get("vnet_name") SUBNET_NAME = self.args.get("subnet_name") LOCATION = self.args.get("location") try: # Create a NIC nic = create_nic(network_client, VNET_NAME, SUBNET_NAME, IP_CONFIG_NAME, NIC_NAME) ############# # VM Sample # ############# # Create Linux VM print('\nCreating Linux Virtual Machine') vm_parameters = create_vm_parameters(nic.id, VM_REFERENCE['linux'], VM_NAME, USERNAME, PASSWORD, LOCATION) async_vm_creation = compute_client.virtual_machines.create_or_update( GROUP_NAME, VM_NAME, vm_parameters) # async_vm_creation.wait() message.message_text = "You are Virtual Machine is being created" except CloudError: print('A VM operation failed:', traceback.format_exc(), sep='\n') message.message_text = "There was an error.Please try again" else: webhook_message = MessageClass() webhook_message.message_text = "VM created successfully" attachment = MessageAttachmentsClass() attachment.title = VM_NAME webhook_message.attach(attachment) yellowant_user_integration_object = YellowAnt( access_token=self.user_integration.yellowant_integration_token) yellowant_user_integration_object.create_webhook_message( requester_application=self.user_integration. yellowant_integration_id, webhook_name="start_vm_webhook", **webhook_message.get_dict()) print('All example operations completed successfully!')
def incident_resolved(request, webhook_id): # data = request.body data_string = data.decode('utf-8') data_json = json.loads(data_string) name = data_json['display_name'] entity_id = data_json['entity_id'] incident_number = data_json['incident_number'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Incident Resolved\n The entity ID : " + str(entity_id) \ + "\nThe Incident Number : " + str(incident_number) attachment = MessageAttachmentsClass() attachment.title = "Incident Operations" button_get_incidents = MessageButtonsClass() button_get_incidents.name = "1" button_get_incidents.value = "1" button_get_incidents.text = "Get all incidents" button_get_incidents.command = { "service_application": service_application, "function_name": 'list_incidents', "data": { 'data': "test", } } attachment.attach_button(button_get_incidents) webhook_message.attach(attachment) # print(integration_id) webhook_message.data = { "Display Name": name, "Entity ID": entity_id, "Incident Number": incident_number, } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_incident_resolved", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def search(self, args): input = args['input'] sp = spotipy.Spotify(auth=self.access_token) # artist_name = 'Ed Sheeran'.join(sys.argv[1:]) results = sp.search(q=input, limit=20) message = MessageClass() for i, t in enumerate(results['tracks']['items']): print(' ', i, t['name']) attachment = MessageAttachmentsClass() attachment.title = t['name'] message.attach(attachment) message.message_text = "The Search Results are" return message.to_json()
def settings(self, args): """ To get the number of functions in the Lambda """ region = args['Region'] message = MessageClass() aws_lambda = boto3.client(service_name='lambda', region_name=region, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=self.aws_access_key, aws_secret_access_key=self.aws_secret_token, aws_session_token=None, config=None) response = aws_lambda.get_account_settings() attachment = MessageAttachmentsClass() attachment.title = response['AccountUsage']['FunctionCount'] message.attach(attachment) message.message_text = "The Function Count is:" return message.to_json()
def campaign_status(self, args): """For viewing the account details""" message = MessageClass() id = args['Id'] status = args['status'] query = "api_key=" + self.API_Access_key + "&api_action=campaign_status&api_output=json&id="+id+"&status="+status url = (self.API_Access_URL + "/admin/api.php?" + query) response = requests.get(url) response_json = response.json() print(response_json) attachment = MessageAttachmentsClass() attachment.title = response_json['result_message'] message.attach(attachment) message.message_text = "" return message.to_json()
def deal_delete(self, args): """For viewing the account details""" id = args['Id'] query = "api_key=" + self.API_Access_key + "&api_action=deal_delete&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() attachment = MessageAttachmentsClass() attachment.title = response_json['result_message'] message.attach(attachment) message.message_text = "" return message.to_json()
def get_attendance(args, user_integration): auth_token_object = UserIntegration.objects.get( yellowant_integration_id=user_integration.yellowant_integration_id) auth_token = auth_token_object.auth_token m = MessageClass() url = 'https://people.zoho.com/people/api/attendance/getUserReport?' sDate = args.get('start_date') eDate = args.get('end_date') employee_id = args.get('employee_id') data = { 'authtoken': auth_token, 'sdate': sDate, 'edate': eDate, 'empId': employee_id, 'dateFormat': 'yyyy-MM-dd' } response = requests.post(url, data=data) response = response.json() print(type(response)) attachment = MessageAttachmentsClass() for k, v in response.items(): attachment = MessageAttachmentsClass() attachment.title = k for k1, v1 in v.items(): field = AttachmentFieldsClass() field.title = k1 field.value = v1 attachment.attach_field(field) m.attach(attachment) field = AttachmentFieldsClass() print(response) print(sDate) print(eDate) print(employee_id) m.message_text = "Just test" return m
def home(self,args): try: l=self.api.home_timeline(count=30) except: m = MessageClass() m.message_text="can't get the feed!!!" return m.to_json() m=MessageClass() for status in l: st=MessageAttachmentsClass() st.title=status.author.screen_name+" "+str(status.id) tweet=AttachmentFieldsClass() tweet.value=status.text st.attach_field(tweet) m.attach(st) return m.to_json()
def View_Surveys(self, args): # Display the Surveys associated with the users account. print("In view surveys") user_id = self.user_integration.yellowant_intergration_id url = (settings.SM_API_BASE + settings.VIEW_SURVEY) response = requests.get(url, headers=self.headers) response_json = response.json() print(response_json) data = response_json["data"] send_data = {"surveys": []} message = MessageClass() message.message_text = "Surveys" for i in range(len(data)): attachment = MessageAttachmentsClass() send_data['surveys'].append({ 'id': data[i]["id"], 'title': data[i]["title"] }) obj = data[i] title = obj["title"] id = obj["id"] button1 = MessageButtonsClass() attachment.title = title field1 = AttachmentFieldsClass() field1.title = "ID" field1.value = id attachment.attach_field(field1) button1.text = "Know more" button1.value = id button1.name = id button1.command = { "service_application": user_id, "function_name": "ViewSurveyDetails", "data":{\ "SurveyId":id\ } } attachment.attach_button(button1) message.attach(attachment) message.data = send_data print(message) # use inbuilt sdk method to_json to return message in a json format accepted by YA return message.to_json()
def new_releases(self, args): # input = args['input'] sp = spotipy.Spotify(auth=self.access_token) # artist_name = 'Ed Sheeran'.join(sys.argv[1:]) results = sp.search(q=input, limit=20) message = MessageClass() response = sp.new_releases() albums = response['albums'] for i, item in enumerate(albums['items']): print(albums['offset'] + i, item['name']) attachment = MessageAttachmentsClass() attachment.title = item['name'] # if albums['next']: # response = sp.next(albums) message.attach(attachment) message.message_text = "The New Releases are:" return message.to_json()
def list_buckets(self, args): """ To list the buckets in the AWS S3, no input arguments required """ message = MessageClass() sss = boto3.client(service_name='s3', api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=self.aws_access_key, aws_secret_access_key=self.aws_secret_token, aws_session_token=None, config=None) response = sss.list_buckets() buckets = [bucket['Name'] for bucket in response['Buckets']] for bucket in buckets: attachment = MessageAttachmentsClass() attachment.title = bucket message.attach(attachment) message.message_text = "The Buckets present are:" return message.to_json()
def Survey_Category(self, args): url = (settings.SM_API_BASE + settings.SURVEY_CATEGORY) response = requests.get(url, headers=self.headers) response_json = response.json() result = "Survey Categories are: \n" message = MessageClass() data = response_json["data"] for i in range(len(data)): obj = data[i] id = obj["id"] name = obj["name"] attachment = MessageAttachmentsClass() attachment.title = id attachment.text = name message.attach(attachment) message.message_text = "Categories are" # use inbuilt sdk method to_json to return message in a json format accepted by YA return message.to_json()
def search(self,args): query=args['query'] try: p=self.api.search_users(query) except: m = MessageClass() m.message_text="cannot find people!!!" return m.to_json() m=MessageClass() for status in p: st=MessageAttachmentsClass() st.title=status.name scname=AttachmentFieldsClass() scname.value=status.screen_name st.attach_field(scname) u=AttachmentFieldsClass() u.value=status.profile_image_url st.attach_field(u) m.attach(st) return m.to_json()
def get_message_byfolder(self, args): """This function returns the messages of a particular folder. The name of the folder is provided as input by the user. If the folder is Empty it returns 'Empty Folder' """ print("In get_message_byfolder") folder_name = args["Folder-Name"] folder_name = folder_name.strip() folder_name = folder_name.replace(" ", "") get_foldermessages_url = graph_endpoint.format( '/me/mailfolders/{}/messages'.format(folder_name)) query_parameters = { '$top': '10', '$select': 'receivedDateTime,subject,from', '$orderby': 'receivedDateTime DESC' } r = make_api_call('GET', get_foldermessages_url, self.access_token, parameters=query_parameters) print(r.json()) value = r.json()["value"] message = MessageClass() if len(value) == 0: message.message_text = "Empty Folder" return message.to_json() if r.status_code == requests.codes.ok: for i in range(0, len(value)): obj = value[i] id = obj["id"] bodyPreview = self.list_messages(args, id=id) attachment = MessageAttachmentsClass() attachment.title = "Subject" attachment.text = str(obj["subject"]) field1 = AttachmentFieldsClass() field1.title = "Received Date Time" field1.value = str(obj["receivedDateTime"]) attachment.attach_field(field1) if bodyPreview != None: field2 = AttachmentFieldsClass() field2.title = "Body Preview" field2.value = str(bodyPreview) attachment.attach_field(field2) from_obj = obj["from"] for j in range(0, len(from_obj)): emailAddress = from_obj["emailAddress"] field3 = AttachmentFieldsClass() field3.title = "From" field3.value = emailAddress["name"] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Email Id" field4.value = emailAddress["address"] attachment.attach_field(field4) message.attach(attachment) message.message_text = "messages are" print("returning mailfolder") if i == (len(value) - 1): return message.to_json() else: continue else: print(r.text) return "{0}: {1}".format(r.status_code, r.text)
def add_new_customer(request, webhook_id): """ Webhook function to notify user about newly created customer """ print("In add_new_customer") print(webhook_id) # Extracting necessary data code = request.GET.get("code", False) if code == request.codes.ok: data = (request.body.decode('utf-8')) response_json = json.loads(data) print(response_json) try: yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id #QuickbookUserToken.objects.get(realmId=response_json['eventNotifications'][0]['realmId']).user_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() id = str(response_json['eventNotifications'][0]['dataChangeEvent'] ['entities'][0]['id']) webhook_message.message_text = "New customer added\n" + "ID :" + str( response_json['eventNotifications'][0]['dataChangeEvent'] ['entities'][0]['id']) attachment = MessageAttachmentsClass() attachment.title = "Get all customer details" button_get_incidents = MessageButtonsClass() button_get_incidents.name = "1" button_get_incidents.value = "1" button_get_incidents.text = "Get customer details" button_get_incidents.command = { "service_application": service_application, "function_name": 'get_customer_details', "data": { "customer_id": id } } attachment.attach_button(button_get_incidents) webhook_message.data = {"customer_id": id} webhook_message.attach(attachment) #print(integration_id) # Creating yellowant object yellowant_user_integration_object = YellowAnt( access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_customer", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403) else: return HttpResponse(status=400)
def webhook(request, hash_str=""): print("Inside webhook") data = request.body if len(data) == 0: validationToken = request.GET['validationtoken'] try: print("In try") return HttpResponse(validationToken, status=200) except: validationToken = None print("Error occured") return HttpResponse(status=400) else: try: message = MessageClass() attachment = MessageAttachmentsClass() response_json = json.loads(data) value_obj = response_json["value"] value = value_obj[0] SubscriptionId = value["SubscriptionId"] ResourceData = value["ResourceData"] message_id = ResourceData["Id"] ya_user = YellowUserToken.objects.get( subscription_id=SubscriptionId) """Make a request to get the message details using message_id""" get_message_details = graph_endpoint.format( "/me/messages/{}".format(message_id)) webhook_request = make_api_call('GET', get_message_details, ya_user.outlook_access_token) response_json = webhook_request.json() subject = response_json["subject"] from_user = response_json["from"] email_address = from_user["emailAddress"] attachment.title = "Subject" attachment.text = str(subject) message.attach(attachment) forward_button = MessageButtonsClass() forward_button.text = "Forward" forward_button.value = "forward" forward_button.name = "forward" forward_button.command = { "service_application": ya_user.yellowant_integration_id, "function_name": "forward_message", "data": { "Message-Id": str(message_id) }, "inputs": ["toRecipients", "Message"] } attachment.attach_button(forward_button) reply_button = MessageButtonsClass() reply_button.text = "Reply" reply_button.value = "Reply" reply_button.name = "Reply" reply_button.command = { "service_application": ya_user.yellowant_integration_id, "function_name": "reply", "data": { "Message-Id": str(message_id) }, "inputs": ["Message"] } attachment.attach_button(reply_button) message.message_text = "Ola! You got a new E-mail from-" + email_address[ "name"] + "( " + email_address["address"] + " )" yauser_integration_object = YellowAnt( access_token=ya_user.yellowant_token) print("Reached here") yauser_integration_object.create_webhook_message( requester_application=ya_user.yellowant_integration_id, webhook_name="inbox_webhook", **message.get_dict()) return True except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def list_function(self, args): """ Gives the list of the functions in the Lambda""" message = MessageClass() attachment = MessageAttachmentsClass() region = args['Region'] # Page is an optional argument try: page = int(args["Page"]) except: page = 1 # If page no. is greater than 1 get the marker of the specified field and use it to get the functions in that page if page > 1: aws_lambda = boto3.client(service_name='lambda', region_name=region, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=self.aws_access_key, aws_secret_access_key=self.aws_secret_token, aws_session_token=None, config=None) #Snippet added to check the Page No. entered is valid or not check = aws_lambda.get_account_settings() max_page = int(int(check['AccountUsage']['FunctionCount'])/10)+1 # If page no. entered is greter than max pages of the Lambda then return this if page > max_page: message.message_text = "The Page no. entered is more than the pages present" return message.to_json() next_marker = self.marker(args, page) response = aws_lambda.list_functions(Marker=next_marker, MaxItems=10) functions = [Function['FunctionName'] for Function in response['Functions']] # Attaching functions and thier respective Buttons for Function in functions: attachment = MessageAttachmentsClass() attachment.title = Function message.attach(attachment) # Button to get the logs of the function button = MessageButtonsClass() button.text = "Get Logs" button.value = "Get Logs" button.name = "Get Logs" button.command = {"service_application": self.yellowant_integration_id, "function_name": "get-logs", "data": {"FunctionName": Function, "Region": region}} attachment.attach_button(button) # Button to invoke the function button1 = MessageButtonsClass() button1.text = "Invoke" button1.value = "Invoke" button1.name = "Invoke" button1.command = {"service_application": self.yellowant_integration_id, "function_name": "invoke-async", "data": {"FunctionName": Function, "Region": region}, "inputs": ["input"]} attachment.attach_button(button1) try: # Button to get the functions in next page, Checks actually if next page exists or not attachment = MessageAttachmentsClass() button2 = MessageButtonsClass() button2.text = "Next Page" button2.value = "Next Page" button2.name = "Next Page" button2.command = {"service_application": self.yellowant_integration_id, "function_name": "next-page", "data": {"NextMarker": response['NextMarker'], "Region": region}} attachment.attach_button(button2) message.message_text = ("The Functions in Page %d are:" % page) except: message.message_text = "This is the last page" # If page is 1 or not specified than return the functions in the 1st page else: aws_lambda = boto3.client(service_name='lambda', region_name=region, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=self.aws_access_key, aws_secret_access_key=self.aws_secret_token, aws_session_token=None, config=None) # Display first 10 functions response = aws_lambda.list_functions(MaxItems=10) functions = [Function['FunctionName'] for Function in response['Functions']] for Function in functions: attachment = MessageAttachmentsClass() attachment.title = Function message.attach(attachment) # Button to get the logs of the function button = MessageButtonsClass() button.text = "Get Logs" button.value = "Get Logs" button.name = "Get Logs" button.command = {"service_application": self.yellowant_integration_id, "function_name": "get-logs", "data": {"FunctionName": Function, "Region": region}} attachment.attach_button(button) # Button to invoke the function button1 = MessageButtonsClass() button1.text = "Invoke" button1.value = "Invoke" button1.name = "Invoke" button1.command = {"service_application": self.yellowant_integration_id, "function_name": "invoke-async", "data": {"Function-Name": Function, "Region": region}, "inputs": ["input"]} attachment.attach_button(button1) try: # Button to get the functions in next page, Checks actually if next page exists or not attachment = MessageAttachmentsClass() button2 = MessageButtonsClass() button2.text = "Next Page" button2.value = "Next Page" button2.name = "Next Page" button2.command = {"service_application": self.yellowant_integration_id, "function_name": "next-page", "data": {"NextMarker": response['NextMarker'], "Region": region}} attachment.attach_button(button2) message.message_text = ("The Functions in Page %d are:" % page) except: message.message_text = "This is the last page" return message.to_json()
def incident_triggered(request, webhook_id): """ Webhook function to notify user about newly created incident """ # Extracting necessary data data = request.body data_string = data.decode('utf-8') data_json = json.loads(data_string) name = data_json['display_name'] entity_id = data_json['entity_id'] incident_number = data_json['incident_number'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Incident Triggered\n The entity ID : " + str(entity_id)\ + "\nThe Incident Number : " + str(incident_number) +\ "\n Incident message : " + str(name) attachment = MessageAttachmentsClass() attachment.title = "Incident Operations" # button_get_incidents = MessageButtonsClass() # button_get_incidents.name = "1" # button_get_incidents.value = "1" # button_get_incidents.text = "Get all incidents" # button_get_incidents.command = { # "service_application": service_application, # "function_name": 'list_incidents', # "data": { # 'data': "test", # } # } # # attachment.attach_button(button_get_incidents) button_ack_incidents = MessageButtonsClass() button_ack_incidents.name = "2" button_ack_incidents.value = "2" button_ack_incidents.text = "Acknowledge the current incident" button_ack_incidents.command = { "service_application": service_application, "function_name": 'ack_incidents', "data": { "Incident-Numbers": incident_number, }, "inputs": ["Acknowledgement-Message"] } attachment.attach_button(button_ack_incidents) webhook_message.attach(attachment) # print(integration_id) webhook_message.data = { "Display Name": name, "Entity ID": entity_id, "Incident Number": incident_number, } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_incident", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def webhook_unsubscribed(request, webhook_id): print("In webhook_unsubscribed") """ Webhook function to notify user about update in unsbscribes """ urllib.parse.unquote(request.body.decode("utf-8")) params_dict = urllib.parse.parse_qsl(request.body) params = dict(params_dict) ## Extracting necessary data device_type = params[b'device-type'].decode("utf-8") name = params[b'client-name'].decode("utf-8") domain = params[b'domain'].decode("utf-8") city = params[b'city'].decode('utf-8') country = params[b'country'].decode('utf-8') recipient = params[b'recipient'].decode('utf-8') try: # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "Unsubscribe details" attachment_message = MessageAttachmentsClass() field2 = AttachmentFieldsClass() field2.title = "Email Id :" field2.value = recipient attachment_message.attach_field(field2) field1 = AttachmentFieldsClass() field1.title = "Browser :" field1.value = name attachment_message.attach_field(field1) field3 = AttachmentFieldsClass() field3.title = "Domain" field3.value = domain attachment_message.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Device type" field4.value = device_type attachment_message.attach_field(field4) field5 = AttachmentFieldsClass() field5.title = "City" field5.value = city attachment_message.attach_field(field5) field6 = AttachmentFieldsClass() field6.title = "Country" field6.value = country attachment_message.attach_field(field6) webhook_message.attach(attachment_message) attachment = MessageAttachmentsClass() attachment.title = "Unsubscribe operations" button_get_incidents = MessageButtonsClass() button_get_incidents.name = "1" button_get_incidents.value = "1" button_get_incidents.text = "Get unsubscribe details" button_get_incidents.command = { "service_application": service_application, "function_name": 'get_unsubscribes', "data": {} } attachment.attach_button(button_get_incidents) webhook_message.data = { "recipient_email_id": recipient, "domain": domain, "device_type": device_type, "city": city, "country": country, "name": name, } webhook_message.attach(attachment) #print(integration_id) # Creating yellowant object yellowant_user_integration_object = YellowAnt( access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="notify_unsubscribe", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def add_new_user(request, webhook_id): """ Webhook function to notify user about newly added user """ # Extracting necessary data data = request.body data_string = data.decode('utf-8') data_json = json.loads(data_string) ID = data_json["current"][0]['id'] name = data_json["current"][0]['name'] Default_currency = data_json["current"][0]['default_currency'] Email = data_json["current"][0]['email'] phone = "-" if data_json["current"][0]['phone'] is None else data_json[ "current"][0]['phone'] # Fetching yellowant object yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) access_token = yellow_obj.yellowant_token integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "New user added."+"\n" + "The username : "******"\nThe Email ID:" + str(Email) attachment = MessageAttachmentsClass() attachment.title = "Get user details" button_get_users = MessageButtonsClass() button_get_users.name = "1" button_get_users.value = "1" button_get_users.text = "Get all users" button_get_users.command = { "service_application": service_application, "function_name": 'list_users', "data": { 'data': "test", } } attachment.attach_button(button_get_users) webhook_message.attach(attachment) # print(integration_id) # userinfo = response['data'] # phone = "-" if userinfo['phone'] is None else userinfo['phone'] webhook_message.data = { "name": name, "ID": ID, "Email": Email, "Phone": phone, "Default currency": Default_currency } # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="new_user", **webhook_message.get_dict()) return HttpResponse("OK", status=200)
def get_my_messages(self, args): """Returns the messages of the inbox folder""" print("In get_my_messages") get_messages_url = graph_endpoint.format( '/me/mailfolders/inbox/messages') # Use OData query parameters to control the results # - Only first 10 results returned # - Only return the ReceivedDateTime, Subject, and From fields # - Sort the results by the ReceivedDateTime field in descending order query_parameters = { '$top': '10', '$select': 'receivedDateTime,subject,from', '$orderby': 'receivedDateTime DESC' } r = make_api_call('GET', get_messages_url, self.access_token, parameters=query_parameters) if r.status_code == requests.codes.ok: r_json = r.json() obj1 = r_json["value"] print(r_json) message = MessageClass() for i in range(0, len(obj1)): obj = obj1[i] id = obj["id"] bodyPreview = self.list_messages(args, id=id) attachment = MessageAttachmentsClass() attachment.title = "Subject" attachment.text = str(obj["subject"]) field1 = AttachmentFieldsClass() field1.title = "Received Date Time" field1.value = str(obj["receivedDateTime"]) attachment.attach_field(field1) if bodyPreview != None: field2 = AttachmentFieldsClass() field2.title = "Body Preview" field2.value = str(bodyPreview) attachment.attach_field(field2) from_obj = obj["from"] for j in range(0, len(from_obj)): emailAddress = from_obj["emailAddress"] field3 = AttachmentFieldsClass() field3.title = "From" field3.value = emailAddress["name"] attachment.attach_field(field3) field4 = AttachmentFieldsClass() field4.title = "Email Id" field4.value = emailAddress["address"] attachment.attach_field(field4) button1 = MessageButtonsClass() button1.text = "Forward" button1.value = "forward" button1.name = "forward" button1.command = { "service_application": self.user_integration.yellowant_integration_id, "function_name": "forward_message", "data": { "Message-Id": str(obj["id"]) }, "inputs": ["toRecipients", "Message"] } attachment.attach_button(button1) button2 = MessageButtonsClass() button2.text = "Reply" button2.value = "Reply" button2.name = "Reply" button2.command = { "service_application": self.user_integration.yellowant_integration_id, "function_name": "reply", "data": { "Message-Id": str(obj["id"]) }, "inputs": ["Message"] } attachment.attach_button(button2) message.attach(attachment) message.message_text = "Inbox messages are" return message.to_json() else: print(r.text) return "{0}: {1}".format(r.status_code, r.text)
def webhook(request, hash_str=""): '''Respond to the webhook verification (GET request) by echoing back the challenge parameter.''' print("Inside webhook") if request.method == "GET": print("Inside webhook validation") challenge = request.GET.get('challenge', None) if challenge != None: return HttpResponse(challenge, status=200) else: return HttpResponse(status=400) else: print("In notifications") webhook_id = hash_str data = (request.body.decode('utf-8')) response_json = json.loads(data) print(response_json) data = {"users": [], "accounts": []} try: yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "File/Folder updated !" attachment = MessageAttachmentsClass() attachment.title = "Updated file/folder details :" for i in range(0, len(response_json['list_folder']['accounts'])): field1 = AttachmentFieldsClass() field1.title = "Id : " field1.value = response_json['list_folder']['accounts'][i] data["accounts"].append( response_json['list_folder']['accounts'][i]) attachment.attach_field(field1) attachment2 = MessageAttachmentsClass() attachment2.title = "User update details :" for i in range(0, len(response_json['delta']['users'])): field2 = AttachmentFieldsClass() field2.title = "Id : " field2.value = response_json['delta']['users'][i] data["users"].append(response_json['delta']['users'][i]) attachment2.attach_field(field2) button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get all files and folders " button.command = { "service_application": service_application, "function_name": 'get_all_folders', "data": { "path": "", "recursive": True, "include_media_info": False, "include_deleted": False, "include_has_explicit_shared_members": False, "include_mounted_folders": True } } attachment.attach_button(button) webhook_message.attach(attachment) webhook_message.attach(attachment2) #print(integration_id) print("-----------") print(data) print("------------") webhook_message.data = data # Creating yellowant object yellowant_user_integration_object = YellowAnt( access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="files_folders_update", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def webhook(request, hash_str=""): '''Respond to the webhook verification (GET request) by echoing back the challenge parameter.''' print("Inside webhook") if request.method == "GET": print("Inside webhook validation") challenge = request.GET.get('challenge',None) if challenge != None: return HttpResponse(challenge,status=200) else: return HttpResponse(status=400) else: print("In notifications") webhook_id = hash_str data = (request.body.decode('utf-8')) response_json = json.loads(data) print(response_json) data = { "users": [], "accounts": [] } try: yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id) print(yellow_obj) access_token = yellow_obj.yellowant_token print(access_token) integration_id = yellow_obj.yellowant_integration_id service_application = str(integration_id) print(service_application) # Creating message object for webhook message webhook_message = MessageClass() webhook_message.message_text = "File/Folder updated !" attachment = MessageAttachmentsClass() attachment.title = "Updated file/folder details :" for i in range(0,len(response_json['list_folder']['accounts'])): field1 = AttachmentFieldsClass() field1.title = "Id : " field1.value = response_json['list_folder']['accounts'][i] data["accounts"].append(response_json['list_folder']['accounts'][i]) attachment.attach_field(field1) attachment2 = MessageAttachmentsClass() attachment2.title = "User update details :" for i in range(0, len(response_json['delta']['users'])): field2 = AttachmentFieldsClass() field2.title = "Id : " field2.value = response_json['delta']['users'][i] data["users"].append(response_json['delta']['users'][i]) attachment2.attach_field(field2) button = MessageButtonsClass() button.name = "1" button.value = "1" button.text = "Get all files and folders " button.command = { "service_application": service_application, "function_name": 'get_all_folders', "data" : {"path": "", "recursive": True, "include_media_info": False, "include_deleted": False, "include_has_explicit_shared_members": False, "include_mounted_folders": True} } attachment.attach_button(button) webhook_message.attach(attachment) webhook_message.attach(attachment2) #print(integration_id) print("-----------") print(data) print("------------") webhook_message.data = data # Creating yellowant object yellowant_user_integration_object = YellowAnt(access_token=access_token) # Sending webhook message to user send_message = yellowant_user_integration_object.create_webhook_message( requester_application=integration_id, webhook_name="files_folders_update", **webhook_message.get_dict()) return HttpResponse("OK", status=200) except YellowUserToken.DoesNotExist: return HttpResponse("Not Authorized", status=403)
def list_users_today(self, args): #Check if 'sort' param is present, else assign default as 'asc' if 'sort' in args: if args['sort'] in ['asc', 'dsc']: order = args['sort'] else: #If invalid, fallback to default value order = 'asc' else: #setting default order 'asc' order = 'asc' if 'subscription' in args: subscription = args['subscription'] else: subscription = None #Instantiate a Message Object message = MessageClass() message.message_text = "" #Create list to store the results users_list = [] d_24 = datetime.datetime.now() - datetime.timedelta(days=1) if subscription is None: users_today = SiteUsers.objects.filter(date_joined__gte=d_24) else: users_today = SiteUsers.objects.filter(date_joined__gte=d_24, subscription=subscription) #Creating User attachments with information of users with a button to fetch user details using the "list_user_details" command for user in users_today: user_attachment = MessageAttachmentsClass() user_attachment.title = user.full_name #Showing user data in a "Field" date_field = AttachmentFieldsClass() date_field.title = "Date Joined" date_field.value = user.date_joined date_field.short = 1 #Utilize two columns user_attachment.attach_field(date_field) #Adding a button which calls the "list_user_details" command get_user_details_button = MessageButtonsClass() get_user_details_button.value = "1" #Give some random value get_user_details_button.name = "1" #Give some random value get_user_details_button.text = "Get user details" #Encoding command in button get_user_details_button.command = { "function_name": "list_user_details", "service_application": self.service_application, "data": { "id": user.id } } user_attachment.attach_button(get_user_details_button) #Adding a button which provides with a dialog to change the subscription for the user using "change_user_subcription" function change_user_sub_button = MessageButtonsClass() change_user_sub_button.value = "1" #Give some random value change_user_sub_button.name = "1" #Give some random value change_user_sub_button.text = "Change subscription" #Encoding command in button change_user_sub_button.command = { "function_name": "change_user_subcription", "service_application": self.service_application, "data": { "id": user.id }, "inputs": ['subscription'] } user_attachment.attach_button(change_user_sub_button) #Add attachment to message message.attach(user_attachment) #Adding users data to be used in workflows message.data = {"users": serializers.serialize("json", users_today)} return message.to_json()