Exemplo n.º 1
0
    def setup_request_v3(self, survey=None, payload=None):
        ''' This method sets up the request and handles the setup of the request for the survey.'''

        assert survey != None, 'Hey There! The survey parameter cannot be None. You need to pass in a survey ID as a string into the survey parameter.'
        assert isinstance(survey, str) == True, 'Hey There! The survey parameter must be of type string.'
        assert len(survey) == 18, 'Hey there! It looks like your survey ID is a the incorrect length. It needs to be 18 characters long. Please try again.'
        assert survey[:3] == 'SV_', 'Hey there! It looks like your survey ID is incorrect. You can find the survey ID on the Qualtrics site under your account settings. Please try again.'

        headers, url = self.header_setup(content_type=True, xm=False, path=f'surveys/{survey}/export-responses/')
        request = r.request("POST", url, data=json.dumps(payload), headers=headers)
        response = request.json()
        try:
            if response['meta']['httpStatus'] == '500 - Internal Server Error':
                raise Qualtrics500Error('500 - Internal Server Error')
            elif response['meta']['httpStatus'] == '503 - Temporary Internal Server Error':
                raise Qualtrics503Error('503 - Temporary Internal Server Error')
            elif response['meta']['httpStatus'] == '504 - Gateway Timeout':
                raise Qualtrics504Error('504 - Gateway Timeout')
            elif response['meta']['httpStatus'] == '400 - Bad Request':
                raise Qualtrics400Error('Qualtrics Error\n(Http Error: 400 - Bad Request): There was something invalid about the request.')
            elif response['meta']['httpStatus'] == '401 - Unauthorized':
                raise Qualtrics401Error('Qualtrics Error\n(Http Error: 401 - Unauthorized): The Qualtrics API user could not be authenticated or does not have authorization to access the requested resource.')
            elif response['meta']['httpStatus'] == '403 - Forbidden':
                raise Qualtrics403Error('Qualtrics Error\n(Http Error: 403 - Forbidden): The Qualtrics API user was authenticated and made a valid request, but is not authorized to access this requested resource.')
        except (Qualtrics500Error, Qualtrics503Error, Qualtrics504Error, Qualtrics400Error, Qualtrics401Error, Qualtrics403Error) as e:
            return print(e)
        else: 
            progress_id = response['result']['progressId']
            return progress_id, url, headers
Exemplo n.º 2
0
 def send_request_v3(self, survey=None, payload=None):
     '''This method sends the request, and sets up the download request.'''
     is_file = None
     progress_id, url, headers = self.setup_request_v3(survey=survey, payload=payload)
     progress_status = "in progress"
     while progress_status != "complete" and progress_status != "failed" and is_file is None:
         check_url = url + progress_id
         check_request = r.request("GET", check_url, headers=headers)
         check_response = check_request.json()
         try:
             is_file = check_response["result"]["fileId"]
         except KeyError:
             pass
         progress_status = check_response["result"]["status"]
     try:
         if check_response['meta']['httpStatus'] == '500 - Internal Server Error':
             raise Qualtrics500Error('500 - Internal Server Error')
         elif check_response['meta']['httpStatus'] == '503 - Temporary Internal Server Error':
             raise Qualtrics503Error('503 - Temporary Internal Server Error')
         elif check_response['meta']['httpStatus'] == '504 - Gateway Timeout':
             raise Qualtrics504Error('504 - Gateway Timeout')
         elif check_response['meta']['httpStatus'] == '400 - Bad Request':
             raise Qualtrics400Error('Qualtrics Error\n(Http Error: 400 - Bad Request): There was something invalid about the request.')
         elif check_response['meta']['httpStatus'] == '401 - Unauthorized':
             raise Qualtrics401Error('Qualtrics Error\n(Http Error: 401 - Unauthorized): The Qualtrics API user could not be authenticated or does not have authorization to access the requested resource.')
         elif check_response['meta']['httpStatus'] == '403 - Forbidden':
             raise Qualtrics403Error('Qualtrics Error\n(Http Error: 403 - Forbidden): The Qualtrics API user was authenticated and made a valid request, but is not authorized to access this requested resource.')
     except (Qualtrics500Error, Qualtrics503Error, Qualtrics504Error, Qualtrics400Error, Qualtrics401Error, Qualtrics403Error) as e:
         return print(e)
     else: 
         download_url = url + is_file + '/file'
         download_request = r.get(download_url, headers=headers, stream=True)
         return download_request
Exemplo n.º 3
0
 def extract_page(surveys=surveys, url=url):
     ''' This method is a nested method that extracts a single page of surveys. '''
     try:
         request = r.get(url, headers=headers)
         response = request.json()
         if response['meta'][
                 'httpStatus'] == '500 - Internal Server Error':
             raise Qualtrics500Error('500 - Internal Server Error')
         elif response['meta'][
                 'httpStatus'] == '503 - Temporary Internal Server Error':
             raise Qualtrics503Error(
                 '503 - Temporary Internal Server Error')
         elif response['meta']['httpStatus'] == '504 - Gateway Timeout':
             raise Qualtrics504Error('504 - Gateway Timeout')
         elif response['meta']['httpStatus'] == '400 - Bad Request':
             raise Qualtrics400Error(
                 'Qualtrics Error\n(Http Error: 400 - Bad Request): There was something invalid about the request.'
             )
         elif response['meta']['httpStatus'] == '401 - Unauthorized':
             raise Qualtrics401Error(
                 'Qualtrics Error\n(Http Error: 401 - Unauthorized): The Qualtrics API user could not be authenticated or does not have authorization to access the requested resource.'
             )
         elif response['meta']['httpStatus'] == '403 - Forbidden':
             raise Qualtrics403Error(
                 'Qualtrics Error\n(Http Error: 403 - Forbidden): The Qualtrics API user was authenticated and made a valid request, but is not authorized to access this requested resource.'
             )
     except (Qualtrics500Error, Qualtrics503Error):
         t.sleep(0.25)
         extract_page(surveys=surveys, url=url)
     except Qualtrics504Error:
         t.sleep(5)
         extract_page(surveys=surveys, url=url)
     except (Qualtrics400Error, Qualtrics401Error,
             Qualtrics403Error) as e:
         print(e)
     except:
         t.sleep(10)
         extract_page(surveys=surveys, url=url)
     else:
         keys = [
             'id', 'name', 'ownerId', 'lastModified', 'creationDate',
             'isActive'
         ]
         lists = Parser().json_parser(response=response,
                                      keys=keys,
                                      arr=False)
         single_page = pd.DataFrame(lists).transpose()
         single_page.columns = keys
         surveys = pd.concat([surveys,
                              single_page]).reset_index(drop=True)
         next_page = response['result']['nextPage']
         return surveys, next_page
Exemplo n.º 4
0
    def get_survey_response(self, survey=None, response=None, verbose=False): 
        ''' This method retrieves a single response from a given survey. '''

        assert survey != None, 'Hey There! The survey parameter cannot be None. You need to pass in a survey ID as a string into the survey parameter.'
        assert response != None, 'Hey There! The response parameter cannot be None. You need to pass in a response ID as a string into the response parameter.'
        assert isinstance(survey, str) == True, 'Hey There! The survey parameter must be of type string.'
        assert isinstance(response, str) == True, 'Hey There! The response parameter must be of type string.'
        assert len(survey) == 18, 'Hey there! It looks like your survey ID is a the incorrect length. It needs to be 18 characters long. Please try again.'
        assert len(response) == 17, 'Hey there! It looks like your response ID is a the incorrect length. It needs to be 17 characters long. Please try again.'
        assert survey[:3] == 'SV_', 'Hey there! It looks like your survey ID is incorrect. You can find the survey ID on the Qualtrics site under your account settings. Please try again.'
        assert response[:2] == 'R_', 'Hey there! It looks like your response ID is incorrect. You can find the response ID on the Qualtrics site under your account settings. Please try again.'

        headers, url = self.header_setup(content_type=True, xm=False, path=f'/surveys/{survey}/responses/{response}')
        request = r.request("GET", url, headers=headers)
        response = request.json()
        try:
            if response['meta']['httpStatus'] == '500 - Internal Server Error':
                raise Qualtrics500Error('500 - Internal Server Error')
            elif response['meta']['httpStatus'] == '503 - Temporary Internal Server Error':
                raise Qualtrics503Error('503 - Temporary Internal Server Error')
            elif response['meta']['httpStatus'] == '504 - Gateway Timeout':
                raise Qualtrics504Error('504 - Gateway Timeout')
            elif response['meta']['httpStatus'] == '400 - Bad Request':
                raise Qualtrics400Error('Qualtrics Error\n(Http Error: 400 - Bad Request): There was something invalid about the request.')
            elif response['meta']['httpStatus'] == '401 - Unauthorized':
                raise Qualtrics401Error('Qualtrics Error\n(Http Error: 401 - Unauthorized): The Qualtrics API user could not be authenticated or does not have authorization to access the requested resource.')
            elif response['meta']['httpStatus'] == '403 - Forbidden':
                raise Qualtrics403Error('Qualtrics Error\n(Http Error: 403 - Forbidden): The Qualtrics API user was authenticated and made a valid request, but is not authorized to access this requested resource.')
        except (Qualtrics503Error, Qualtrics504Error) as e:
            # Recursive call to handle Internal Server Errors
            return self.get_survey_response(self, survey=survey, response=response, verbose=verbose)
        except (Qualtrics500Error, Qualtrics400Error, Qualtrics401Error, Qualtrics403Error) as e:
            # Handle Authorization/Bad Request Errors
            return print(e)
        else:
            if verbose == True:
              return response['meta']['httpStatus'], response['result']
            else: 
              return response['result']
        return
Exemplo n.º 5
0
    def create_contact_in_XM(self, **kwargs):
        '''This function gives you the ability to create a contact in your XM Directory. This method does re-list not each
        element that you just created. It returns the XMDirectory "Contact ID" associated with the newly created XM directory
        contact.
        
        :param dynamic_payload: A dictionary containing the correct key-value pairs.
        :type dynamic_payload: dict
        :param first_name: The contacts first name.
        :type first_name: str
        :param last_name: The contacts last name.
        :type last_name: str
        :param email: the contacts email.
        :type email: str
        :param phone: the contacts phone number.
        :type phone: str
        :param language: the native language of the contact. (Default: English)
        :type language: str
        :param metadata: any relevant contact metadata.
        :type metadata: dict
        :return: The newly created contact id (CID) in XMDirectory.
        :type return: str
        '''
        
        dynamic_payload={}
        verbose = False
        for key in list(kwargs.keys()):
            assert key in ['first_name', 'last_name', 'email', 'unsubscribed', 'language', 'external_ref', 'metadata', 'phone', 'verbose', 'dynamic_payload'], "Hey there! You can only pass in parameters with names in the list, ['first_name', 'last_name', 'email', 'unsubscribed', 'language', 'external_ref', 'metadata']"
            if key == 'first_name':
                dynamic_payload.update({'firstName': kwargs[str(key)]})
            elif key == 'last_name':
                dynamic_payload.update({'lastName': kwargs[str(key)]})
            elif key == 'email':
                dynamic_payload.update({'email': kwargs[str(key)]})
            elif key == 'phone':
                dynamic_payload.update({'phone': kwargs[str(key)]})
            elif key == 'language':
                dynamic_payload.update({'language': kwargs[str(key)]})
            elif key == 'external_ref':
                dynamic_payload.update({'extRef': kwargs[str(key)]})
            elif key == 'unsubscribed':
                dynamic_payload.update({'unsubscribed': kwargs[str(key)]})
            elif key == 'phone':
                dynamic_payload.update({'phone': kwargs[str(key)]})
            elif key == 'metadata':
                assert isinstance(kwargs['metadata'], dict), 'Hey there, your metadata parameter needs to be of type "dict"!'
                dynamic_payload.update({'embeddedData': kwargs[str(key)]})
            elif key == 'dynamic_payload':
              dynamic_payload = dict(kwargs[str(key)])
            elif key == 'verbose':
              verbose = True

        headers, base_url = self.header_setup(content_type=True, xm=True)
        url = f"{base_url}/contacts"
        request = r.post(url, json=dynamic_payload, headers=headers)
        response = request.json()
        try:
            if response['meta']['httpStatus'] == '500 - Internal Server Error':
                raise Qualtrics500Error('500 - Internal Server Error')
            elif response['meta']['httpStatus'] == '503 - Temporary Internal Server Error':
                raise Qualtrics503Error('503 - Temporary Internal Server Error')
            elif response['meta']['httpStatus'] == '504 - Gateway Timeout':
                raise Qualtrics504Error('504 - Gateway Timeout')
            elif response['meta']['httpStatus'] == '400 - Bad Request':
                raise Qualtrics400Error('Qualtrics Error\n(Http Error: 400 - Bad Request): There was something invalid about the request.')
            elif response['meta']['httpStatus'] == '401 - Unauthorized':
                raise Qualtrics401Error('Qualtrics Error\n(Http Error: 401 - Unauthorized): The Qualtrics API user could not be authenticated or does not have authorization to access the requested resource.')
            elif response['meta']['httpStatus'] == '403 - Forbidden':
                raise Qualtrics403Error('Qualtrics Error\n(Http Error: 403 - Forbidden): The Qualtrics API user was authenticated and made a valid request, but is not authorized to access this requested resource.')
        except (Qualtrics500Error, Qualtrics503Error, Qualtrics504Error) as e:
            # Recursive call to handle Internal Server Errors
            return self.create_contact_in_XM(dynamic_payload=dynamic_payload)
        except (Qualtrics400Error, Qualtrics401Error, Qualtrics403Error) as e:
            # Handle Authorization/Bad Request Errors
            return print(e)
        else:
            if verbose == True:
              return response['meta']['httpStatus'], response['result']['id']
            else: 
                return response['result']['id']
Exemplo n.º 6
0
    def share_user_surveys(self,
                           survey=None,
                           recipient_id=None,
                           permissions={}):
        '''This method provides functionality to share a survey within a given brand/organization.

        :param survey: the name of the list to be created.
        :param recipient_id: the group/user qualtrics id
        :param permissions: an object of permission properties.
        :return: A message on HTTP-200 Success
        '''

        assert survey != None, 'Hey there! The survey parameter cannot be None.'
        assert isinstance(
            survey, str
        ) == True, 'Hey there! The survey parameter must be of type string.'
        assert recipient_id != None, 'Hey there! The recipient parameter cannot be None.'
        assert isinstance(
            recipient_id, str
        ) == True, 'Hey there! The recipient parameter must be of type string.'
        assert permissions != None, 'Hey there! The permissions parameter cannot be None.'
        assert isinstance(
            permissions, dict
        ) == True, 'Hey there! The permissions parameter must be of type dict.'

        headers, url = self.header_setup(
            content_type=False,
            xm=False,
            path=f'surveys/{survey}/permissions/collaborations')
        data = {'recipientId': recipient_id, 'permissions': permissions}
        try:
            request = r.post(url, json=data, headers=headers)
            response = request.json()
            if response['meta']['httpStatus'] == '500 - Internal Server Error':
                raise Qualtrics500Error('500 - Internal Server Error')
            elif response['meta'][
                    'httpStatus'] == '503 - Temporary Internal Server Error':
                raise Qualtrics503Error(
                    '503 - Temporary Internal Server Error')
            elif response['meta']['httpStatus'] == '504 - Gateway Timeout':
                raise Qualtrics504Error('504 - Gateway Timeout')
            elif response['meta']['httpStatus'] == '400 - Bad Request':
                raise Qualtrics400Error(
                    'Qualtrics Error\n(Http Error: 400 - Bad Request): There was something invalid about the request.'
                )
            elif response['meta']['httpStatus'] == '401 - Unauthorized':
                raise Qualtrics401Error(
                    'Qualtrics Error\n(Http Error: 401 - Unauthorized): The Qualtrics API user could not be authenticated or does not have authorization to access the requested resource.'
                )
            elif response['meta']['httpStatus'] == '403 - Forbidden':
                raise Qualtrics403Error(
                    'Qualtrics Error\n(Http Error: 403 - Forbidden): The Qualtrics API user was authenticated and made a valid request, but is not authorized to access this requested resource.'
                )
        except (Qualtrics500Error, Qualtrics503Error, Qualtrics504Error) as e:
            # Recursive call to handle Internal Server Errors
            return self.share_user_surveys(survey=survey,
                                           recipient_id=recipient_id,
                                           permissions=permissions)
        except (Qualtrics400Error, Qualtrics401Error, Qualtrics403Error) as e:
            # Handle Authorization/Bad Request Errors
            return print(e)
        else:
            return f'The survey "{survey}" was shared with the user/group "{recipient_id}"'