Exemple #1
0
 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()
Exemple #2
0
 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()
Exemple #3
0
 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()
Exemple #4
0
    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()
Exemple #5
0
    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()
Exemple #6
0
    def list_items(self, args):
        """
            This function returns all the items of an organization
        """
        org_id = args['organization']
        headers = {
            "Authorization":
            "Zoho-oauthtoken" + " " + self.zohoinvoice_access_token,
            "X-com-zoho-invoice-organizationid": org_id,
            "Content-Type": "application/json"
        }
        url = settings.ZOHO_ITEMS_URL
        response = requests.get(url, headers=headers)
        print(response)
        print(response.text)
        message = MessageClass()
        message.message_text = "Items"
        response_json = response.json()
        data = response_json['items']
        i = 0
        print(data[0]['description'])
        a = data[0]['description']
        if len(a) == 0:
            print("its none")
        else:
            print("no")

        for item in data:
            attachment = MessageAttachmentsClass()
            attachment.text = "Item" + " " + str(i + 1)

            field1 = AttachmentFieldsClass()
            field1.title = "Item Name"
            field1.value = item['name']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Item ID"
            field2.value = item['item_id']
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Item Type"
            field3.value = item['product_type']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Rate"
            field4.value = item['rate']
            attachment.attach_field(field4)

            des = item['description']
            field5 = AttachmentFieldsClass()
            field5.title = "Description"
            field5.value = "-" if len(des) == 0 else des
            attachment.attach_field(field5)
            i = i + 1
            message.attach(attachment)
        return message.to_json()
Exemple #7
0
    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()
Exemple #8
0
    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()
Exemple #9
0
    def list_activities(self, args):
        """
            Returns all activities assigned to a particular user
        """
        url = settings.PIPEDRIVE_GET_ALL_ACTIVITY + self.pipedrive_api_token
        response = requests.get(url, headers=self.headers)
        response_json = response.json()
        # print(response_json)
        activity_info = response_json['data']

        message = MessageClass()
        message.message_text = "Activities"

        for i in range(len(activity_info)):
            attachment = MessageAttachmentsClass()
            attachment.text = "Activity" + " " + str(i + 1)

            field1 = AttachmentFieldsClass()
            field1.title = "Activity Subject"
            field1.value = activity_info[i]['subject']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Activity Type"
            field2.value = activity_info[i]['type']
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Due Date"
            field3.value = activity_info[i]['due_date']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Contact Person"
            field4.value = "-" if activity_info[i][
                'person_name'] is None else activity_info[i]['person_name']
            attachment.attach_field(field4)

            field5 = AttachmentFieldsClass()
            field5.title = "Company"
            field5.value = "-" if activity_info[i][
                'org_name'] is None else activity_info[i]['org_name']
            attachment.attach_field(field5)

            field6 = AttachmentFieldsClass()
            field6.title = "Handled by"
            field6.value = activity_info[i]['owner_name']
            attachment.attach_field(field6)

            message.attach(attachment)
        return message.to_json()
Exemple #10
0
    def list_all_deals(self, args):
        """
            Returns all deals
        """
        url = settings.PIPEDRIVE_GET_ALL_DEAL + self.pipedrive_api_token
        response = requests.get(url, headers=self.headers)
        response_json = response.json()
        # print(response_json)
        deal_info = response_json['data']

        message = MessageClass()
        message.message_text = "Deals"

        for i in range(len(deal_info)):
            attachment = MessageAttachmentsClass()
            attachment.text = "Deal" + " " + str(i + 1)

            field1 = AttachmentFieldsClass()
            field1.title = "Title"
            field1.value = deal_info[i]['title']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Value"
            field2.value = str(deal_info[i]['currency']) + " " + str(
                deal_info[i]['value'])
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Name"
            field3.value = deal_info[i]['person_id']['name']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Company"
            field4.value = deal_info[i]['org_id']['name']
            attachment.attach_field(field4)

            field5 = AttachmentFieldsClass()
            field5.title = "Handled by"
            field5.value = deal_info[i]['user_id']['name']
            attachment.attach_field(field5)

            field6 = AttachmentFieldsClass()
            field6.title = "Status"
            field6.value = deal_info[i]['status']
            attachment.attach_field(field6)

            message.attach(attachment)
        return message.to_json()
Exemple #11
0
    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()
Exemple #12
0
    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()
Exemple #13
0
 def add_user(self, args):
     """
         Adds a new user to the organization
     """
     message = MessageClass()
     url = settings.VICTOROPS_ADD_USER
     body = {
         "firstName": args['First-Name'],
         "lastName": args['Last-Name'],
         "username": args['UserName'],
         "email": args['Email'],
         "admin": True,
         "expirationHours": int(args['Expiration-Hours'])
     }
     # POST request to victorops server
     response = requests.post(url,
                              headers=self.headers,
                              data=json.dumps(body))
     # print(r)
     r_text = response.text
     if re.search(r'The email address', r_text, re.M | re.I):
         attachment = MessageAttachmentsClass()
         attachment.text = "The email is already registered"
         message.attach(attachment)
         return message.to_json()
     elif re.search(r'is unavailable', r_text, re.M | re.I):
         attachment = MessageAttachmentsClass()
         attachment.text = "Username " + str(
             args['UserName']) + " is not available"
         message.attach(attachment)
         return message.to_json()
     else:
         attachment = MessageAttachmentsClass()
         attachment.text = "User added"
         message.attach(attachment)
         return message.to_json()
Exemple #14
0
    def list_users(self, args):
        """
            This function returns all the users in the organization
        """
        org_id = args['organization']
        headers = {
            "Content-Type": "application/json",
            "Authorization":
            "Zoho-oauthtoken" + " " + self.zohoinvoice_access_token,
            "X-com-zoho-invoice-organizationid": org_id
        }
        url = settings.ZOHO_USER_URL
        response = requests.get(url, headers=headers)
        print(response)
        print(response.text)
        i = 0
        message = MessageClass()
        message.message_text = "Users"
        response_json = response.json()
        data = response_json['users']

        for user in data:
            attachment = MessageAttachmentsClass()
            attachment.image_url = user["photo_url"]
            attachment.text = "User" + " " + str(i + 1)

            field1 = AttachmentFieldsClass()
            field1.title = "Name"
            field1.value = user['name']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Email"
            field2.value = user['email']
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "User ID"
            field3.value = user['user_id']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Role ID"
            field4.value = user['role_id']
            attachment.attach_field(field4)
            i = i + 1
            message.attach(attachment)
        return message.to_json()
Exemple #15
0
    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()
Exemple #16
0
    def get_logs(self, args):
        """To get the logs of the function"""
        region = args['Region']
        function_name = args['FunctionName']
        message = MessageClass()
        attachment = MessageAttachmentsClass()
        logstream = self.log_stream(args, function_name)

        # If Logstream is 0 then the Logs dosen't exist
        if logstream ==0:
            message.message_text = "There are no logs for that Function or the Log" \
                                   " group name and the Function Name are mismatched"
            return message.to_json()

        aws_lambda = boto3.client(service_name='logs', 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)
        log_group_name = "/aws/lambda/"+function_name

        # The following while loop is to find the i till which last log exists, for usage in get_log_events
        i = 0
        strin=""
        while strin != "START":
            response = aws_lambda.get_log_events(
                logGroupName=log_group_name,
                logStreamName=logstream,
                limit=i+1
            )
            string=str(response['events'][0]['message'])
            i = i+1
            strin = string[:5]

        #
        response = aws_lambda.get_log_events(
            logGroupName=log_group_name,
            logStreamName=logstream,
            limit=i
        )
        events = [event['message'] for event in response['events']]
        for event in events:
            attachment.text = event
            message.attach(attachment)

        message.message_text = "The Event logs are:"
        return message.to_json()
Exemple #17
0
    def add_user(self, args):
        """
            This function is used to add an user to the organization
        """
        org_id = args['organization']
        name = args['name']
        email = args['email']
        role = args['user_role']

        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_USER_URL
        payload = {"name": name, "email": email, "user_role": role}

        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 = "Your invitation has been sent."
            message.attach(attachment)
            return message.to_json()
Exemple #18
0
    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()
Exemple #19
0
    def list_pipelines(self, args):
        """
            Returns data about all pipelines
        """
        url = settings.PIPEDRIVE_GET_ADD_PIPELINE + self.pipedrive_api_token
        response = requests.get(url, headers=self.headers)
        response_json = response.json()
        # print(response_json)
        pipeline_info = response_json['data']
        # print(deal_info)
        message = MessageClass()
        message.message_text = "Pipelines"
        for i in range(len(pipeline_info)):
            attachment = MessageAttachmentsClass()
            attachment.text = "Pipeline" + " " + str(i + 1)

            field1 = AttachmentFieldsClass()
            field1.title = "Name"
            field1.value = pipeline_info[i]['name']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Url title"
            field2.value = pipeline_info[i]['url_title']
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Add Time"
            field3.value = pipeline_info[i]['add_time']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Order"
            field4.value = pipeline_info[i]['order_nr']
            attachment.attach_field(field4)

            message.attach(attachment)
        return message.to_json()
Exemple #20
0
    def add_user(self, args):
        """
            Adds a new user to the company, returns the ID upon success.
        """
        message = MessageClass()
        url = settings.PIPEDRIVE_LIST_ADD_USERS_URL + self.pipedrive_api_token
        body = {
            "name": args['Name'],
            "email": args['Email'],
            "active_flag": "1"
        }
        # POST request to pipedrive server
        response = requests.post(url,
                                 headers=self.headers,
                                 data=json.dumps(body))
        if response.status_code == 400:
            attachment = MessageAttachmentsClass()
            attachment.text = "Provided email not valid"
            message.attach(attachment)
            return message.to_json()
        else:
            response_json = response.json()
            # print(response_json)
            userinfo = response_json['data']
            # print(userinfo)
            message.message_text = "User Added!"
            attachment = MessageAttachmentsClass()

            field1 = AttachmentFieldsClass()
            field1.title = "Name"
            field1.value = userinfo['name']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "ID"
            field2.value = userinfo['id']
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Email"
            field3.value = userinfo['email']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Phone"
            field4.value = "-" if userinfo['phone'] is None else userinfo[
                'phone']
            attachment.attach_field(field4)

            field5 = AttachmentFieldsClass()
            field5.title = "Default currency"
            field5.value = userinfo['default_currency']
            attachment.attach_field(field5)

            field6 = AttachmentFieldsClass()
            field6.title = "Admin"
            field6.value = 'True' if userinfo['is_admin'] else 'False'
            attachment.attach_field(field6)

            phone = "-" if userinfo['phone'] is None else userinfo['phone']

            message.data = {
                "name": userinfo['name'],
                "ID": userinfo['id'],
                "Email": userinfo['email'],
                "Phone": phone,
                "Default currency": userinfo['default_currency']
            }

            message.attach(attachment)
            return message.to_json()
Exemple #21
0
    def search_users(self, args):
        """
           Finds users by their name.The input must be at least 2 characters long.
        """
        message = MessageClass()

        if (len(args['Search-Term'])) < 2:
            attachment = MessageAttachmentsClass()
            attachment.text = "The search term must be at least 2 characters long"
            message.attach(attachment)
            return message.to_json()

        url = settings.PIPEDRIVE_SEARCH_USERS_URL % args[
            'Search-Term'] + self.pipedrive_api_token
        # print(url)

        body = {"term": args['Search-Term']}
        response = requests.get(url,
                                headers=self.headers,
                                data=json.dumps(body))
        response_json = response.json()
        # print(response_json)

        message.message_text = "Users"
        userinfo = response_json['data']
        if userinfo is None:
            attachment = MessageAttachmentsClass()
            attachment.text = "No users found!"
            message.attach(attachment)
            return message.to_json()
        else:
            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()
Exemple #22
0
    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)
Exemple #23
0
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)
Exemple #24
0
    def add_activity(self, args):
        """
            Adds a new activity.
        """
        url = settings.PIPEDRIVE_ADD_ACTIVITY + self.pipedrive_api_token
        body = {
            "subject": args['Subject'],
            "done": "0",
            "type": args['Type'],
            "due_date": args['Due-Date'],
            "deal_id": args['Deal'],
            "person_id": args['Contact-Person']
        }
        response = requests.post(url,
                                 headers=self.headers,
                                 data=json.dumps(body))
        # print(response)
        # print(response_json)
        message = MessageClass()
        if response.status_code == 400:
            attachment = MessageAttachmentsClass()
            attachment.text = "Unrecognized date value for due date."
            message.attach(attachment)
            return message.to_json()
        else:
            response_json = response.json()
            activity_info = response_json['data']
            message.message_text = "Activity added"

            attachment = MessageAttachmentsClass()

            field1 = AttachmentFieldsClass()
            field1.title = "Activity Subject"
            field1.value = activity_info['subject']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Activity Type"
            field2.value = activity_info['type']
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Due Date"
            field3.value = activity_info['due_date']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Contact Person"
            field4.value = activity_info['person_name']
            attachment.attach_field(field4)

            field5 = AttachmentFieldsClass()
            field5.title = "Company"
            field5.value = activity_info['org_name']
            attachment.attach_field(field5)

            field6 = AttachmentFieldsClass()
            field6.title = "Handled by"
            field6.value = activity_info['owner_name']
            attachment.attach_field(field6)

            message.data = {
                "Activity Subject": activity_info['subject'],
                "Activity Type": activity_info['type'],
                "Due Date": activity_info['due_date'],
                "Contact Person": activity_info['person_name'],
                "Company": activity_info['org_name'],
                "Handled by": activity_info['owner_name']
            }

            message.attach(attachment)
            return message.to_json()
Exemple #25
0
    def add_pipeline(self, args):
        """
            Adds a new pipeline
        """
        url = settings.PIPEDRIVE_GET_ADD_PIPELINE + self.pipedrive_api_token
        body = {
            "name": args['Name'],
            "deal_probability": args['Deal-Probability'],
            "active": "1"
        }
        response = requests.post(url,
                                 headers=self.headers,
                                 data=json.dumps(body))
        # print(response.text)
        message = MessageClass()

        if response.status_code == 400:
            attachment = MessageAttachmentsClass()
            attachment.text = "Cannot add the pipeline."
            message.attach(attachment)
            return message.to_json()
        else:
            response_json = response.json()
            pipeline_info = response_json['data']
            message.message_text = "Pipeline created"

            attachment = MessageAttachmentsClass()

            field1 = AttachmentFieldsClass()
            field1.title = "Name"
            field1.value = pipeline_info['name']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Url title"
            field2.value = pipeline_info['url_title']
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Add Time"
            field3.value = pipeline_info['add_time']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Order"
            field4.value = pipeline_info['order_nr']
            attachment.attach_field(field4)

            field5 = AttachmentFieldsClass()
            field5.title = "Deal Probability"
            field5.value = pipeline_info['deal_probability']
            attachment.attach_field(field5)

            message.data = {
                "Name": pipeline_info['name'],
                "Url title": pipeline_info['url_title'],
                "Add Time": pipeline_info['add_time'],
                "Order": pipeline_info['order_nr']
            }

            message.attach(attachment)
            return message.to_json()
Exemple #26
0
    def add_deal(self, args):
        """
            Adds a new deal.
        """
        url = settings.PIPEDRIVE_ADD_DEAL + self.pipedrive_api_token
        body = {
            "title": args['title'],
            "value": args['value'],
            "currency": args['currency'],
            "person_id": args['Contact-person-name'],
            "org_id": args['Organization-Name'],
            "status": "",
        }
        response = requests.post(url,
                                 headers=self.headers,
                                 data=json.dumps(body))
        # print(response)
        message = MessageClass()

        if response.status_code == 400:
            attachment = MessageAttachmentsClass()
            attachment.text = "No stages found in the default pipeline. Cannot add a deal."
            message.attach(attachment)
            return message.to_json()
        else:
            response_json = response.json()
            dealinfo = response_json['data']
            message.message_text = "Deal created"

            attachment = MessageAttachmentsClass()

            field1 = AttachmentFieldsClass()
            field1.title = "Title"
            field1.value = dealinfo['title']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Value"
            field2.value = str(dealinfo['currency']) + " " + str(
                dealinfo['value'])
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Name"
            field3.value = dealinfo['person_id']['name']
            attachment.attach_field(field3)

            field4 = AttachmentFieldsClass()
            field4.title = "Company"
            field4.value = dealinfo['org_id']['name']
            attachment.attach_field(field4)

            field5 = AttachmentFieldsClass()
            field5.title = "Handled by"
            field5.value = dealinfo['user_id']['name']
            attachment.attach_field(field5)

            message.data = {
                "Title": dealinfo['title'],
                "Value": dealinfo['value'],
                "Currency": dealinfo['currency'],
                "Name": dealinfo['person_id']['name'],
                "Company": dealinfo['org_id']['name'],
                "Handled by": dealinfo['user_id']['name']
            }

            message.attach(attachment)
            return message.to_json()
Exemple #27
0
    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)