Exemplo n.º 1
3
class ZendeskAction(Action):
    def __init__(self, config):
        super(ZendeskAction, self).__init__(config=config)
        self.email = self.config['email']
        self.token = self.config['api_token']
        self.subdomain = self.config['subdomain']

        self.credentials = {
            'email': self.email,
            'token': self.token,
            'subdomain': self.subdomain
        }

        self.api = Zenpy(**self.credentials)

    def clean_response(self, text):
        return text.replace('\n', ' ').replace('  ', ' ').strip()

    def url_for_ticket(self, ticket):
        return 'https://{}.zendesk.com/agent/tickets/{}'.format(self.subdomain, ticket)

    def api_search(self, query, search_type):
        return self.api.search(query, type=search_type, sort_by='created_at', sort_order='desc')

    def create_ticket(self, subject, description):
        ticket = Ticket(subject=subject, description=description)

        try:
            created_ticket_audit = self.api.tickets.create(ticket)
            return {
                'ticket_id': created_ticket_audit.ticket.id,
                'ticket_url': self.url_for_ticket(created_ticket_audit.ticket.id),
                'subject': self.clean_response(subject),
                'description': self.clean_response(description)
            }
        except APIException:
            return {'error': 'Could not create ticket with provided parameters'}
        except Exception as e:
            self.logger.error(e)
            return {'error': 'Could not make API request'}

    def search_tickets(self, query, search_type='ticket', limit=10):
        try:
            query_results = self.api_search(query, search_type)
            results_clean = map(lambda t: {
                'ticket_id': t.id,
                'ticket_url': self.url_for_ticket(t.id),
                'ticket_status': t.status,
                'subject': self.clean_response(t.subject),
                'description': self.clean_response(t.description)},
                list(query_results)[:limit]
            )
            return {'search_results': results_clean}
        except APIException:
            return {'error': 'Could not execute search for query: {}'.format(query)}
        except Exception as e:
            self.logger.error(e)
            return {'error': 'There was an error executing your search'}

    def update_ticket(self, ticket_id, comment_text, public):
        try:
            ticket = self.api.tickets(id=ticket_id)
            ticket.comment = Comment(body=comment_text, public=public)
            self.api.tickets.update(ticket)
            return {
                'ticket_id': ticket_id,
                'ticket_url': self.url_for_ticket(ticket_id),
                'body': self.clean_response(comment_text),
                'public': public
            }
        except RecordNotFoundException:
            return {'error': 'Could not find ticket #{}'.format(ticket_id)}
        except Exception as e:
            self.logger.error(e)
            return {'error': 'Could not update ticket'}

    def update_ticket_status(self, ticket_id, status):
        valid_statuses = ['new', 'open', 'pending', 'solved', 'closed']
        if status in valid_statuses:
            try:
                ticket = self.api.tickets(id=ticket_id)
                ticket.status = status
                self.api.tickets.update(ticket)
                return {
                    'ticket_id': ticket_id,
                    'ticket_url': self.url_for_ticket(ticket_id),
                    'status': status
                }
            except RecordNotFoundException:
                return {'error': 'Could not find ticket #{}'.format(ticket_id)}
            except Exception as e:
                self.logger.error(e)
                return {'error': 'Could not update ticket status'}
        else:
            return {'error': 'Invalid status given for ticket'}
class ZendeskConnection:
    def __init__(self):
        self._creds = {
            'email': os.environ.get('ZENDESK_USER', None),
            'token': os.environ.get('ZENDESK_TOKEN', None),
            'subdomain': "pagarme"
        }
        self._zenpy_client = Zenpy(**self._creds)
        self._sl = SlackConnection.SlackConnection()
        self._mc = MongoConnection.MongoConnection()


    def _generate_comment(self, ticket):
        ticket_comments = ""
        for comment in self._zenpy_client.tickets.comments(ticket_id=ticket.id):
            ticket_comments += " " + str(comment)

        return self._remove_special_characters(ticket_comments)


    def _remove_special_characters(self, phrase):
        phrase = phrase.lower()
        return unidecode(phrase)

    def _word_in_text(self, word, text):
        if re.search(r'\b' + word + r'\b', text):
            return True
        return False


    def _tag_ticket(self, ticket):
        try:
            TAGS = tags.TAGS
            new_tags = []
            subject = self._remove_special_characters(ticket.subject)
            ticket_comments = self._generate_comment(ticket)
            description = self._remove_special_characters(ticket.description)
            content = subject + " " + ticket_comments + " " + description + " "
            for tag in TAGS:
                for word in TAGS[tag]:
                    if (self._word_in_text(word, content)) and (tag not in new_tags):
                        new_tags.append(tag)
            ticket.tags.extend(new_tags)
            self._zenpy_client.tickets.update(ticket)
        except Exception as e:
            print(e.args)


    def _get_supporters(self):
        supporter_list = []

        for supporter in self._zenpy_client.search(type='user', group_id=21164867):
            for email in self._mc.get_active_supporters():
                if supporter.email in email['email']:
                    try:
                        supporter_list.append(supporter)
                    except Exception as e:
                        print(e.args)
        return supporter_list


    def _get_not_assigned_tickets(self):
        not_assigned_tickets = list()

        for tickets in self._zenpy_client.search(type='ticket', group_id=21164867,
                                                 assignee_id=None, status=['new', 'open', 'pending']):
            not_assigned_tickets.append(tickets)

        return not_assigned_tickets

    def _get_assignees_tickets(self, assignees, statuses):
        assigned_tickets = list()

        for ticket in self._zenpy_client.search(
            type='ticket', group_id=21164867, assignee_id=assignees,
            status=statuses
        ):
            assigned_tickets.append(ticket)

        return assigned_tickets

    def _get_pending_interaction_tickets(self, tickets, inactiveHours):
        pending = list()

        for ticket in tickets:
            comments = list(self._zenpy_client.tickets.comments(ticket.id))
            latest_comment = comments[len(comments)-1]

            now = datetime.now()
            latest_comment_date = datetime.strptime(str(latest_comment.created), "%Y-%m-%d %H:%M:%S+00:00")

            diff_in_hours = utilities.get_dates_diff_in_hours(now, latest_comment_date)

            if diff_in_hours >= inactiveHours:
                pending.append(ticket)

        return pending

    def _typing_tickets(self):
        not_assigned_tickets_with_type = list()
        fl = open("ticket_log.txt", "r+")
        read_file_string = fl.read()

        for ticket in self._get_not_assigned_tickets():
            if ticket.type in ['problem', 'incident', 'question', 'task']:
                not_assigned_tickets_with_type.append(ticket)
            else:
                if str(ticket.id) not in read_file_string:
                    self._sl.send_message(ticket)
                    fl.write("  " + str(ticket.id))

        fl.close()
        return not_assigned_tickets_with_type


    def _get_yesterday_tickets(self):
        yesterday = datetime.now() - timedelta(days=2)
        yesterday_tickets = self._zenpy_client.search(type='ticket', created_after=yesterday.date(), group_id=21164867)
        support_tickets = [];
        for ticket in yesterday_tickets:
            support_tickets.append(ticket)

        return support_tickets


    def _get_ticket_count_supporter(self):
        sups = self._get_supporters()
        ticket_count = []

        for sup in sups:
            tickets = self._zenpy_client.search(type='ticket', group_id=21164867,
                                                status=['open', 'pending'], assignee_id=sup.id)
            count = len(tickets)

            ticket_count.append({'nome': sup.name, 'count': count, 'id': sup.id})

        print('Active supporters: \n' + str(ticket_count))

        return ticket_count


    def tag_yesterday_tickets(self):
        yesterday_tickets = self._get_yesterday_tickets()
        tagged_tickets = [];
        for ticket in yesterday_tickets:
            self._tag_ticket(ticket)
            tagged_tickets.append(ticket.id)
        print('Tagged tickets: ' + ''.join( str(tagged_tickets) ) )


    def assign_tickets(self):
        sups = self._get_ticket_count_supporter()
        # Send ticket type message through slack
        tickets = self._typing_tickets()
        if sups:
            if len(tickets) > 0:
                for ticket in tickets:
                    #  Get lowest ticket count supporter
                    lowest_ticket_count_sup = None
                    for count in sups:
                        if not lowest_ticket_count_sup:
                            lowest_ticket_count_sup = count
                        elif count['count'] < lowest_ticket_count_sup['count']:
                            lowest_ticket_count_sup = count

                    sup = self._mc.get_supporter_by_zendesk_id(lowest_ticket_count_sup['id'])
                    try:
                        # Assign the ticket
                        ticket.assignee_id = sup['zendesk_id']
                        slack_id = sup['slack_id']
                        name = sup['name']
                        print(slack_id + " | " + name)
                        self._zenpy_client.tickets.update(ticket)

                        # Notify the supporter on slack
                        self._sl.notify_supporter(slack_id, name, ticket)

                        # Increase the ticket count for the agent who got it
                        for agent in sups:
                            if agent['id'] == lowest_ticket_count_sup['id']:
                                agent['count'] += 1

                    except Exception as e:
                        print(e.args)
            elif len(tickets) <= 0:
                print("No tickets to assign.")
        elif not sups:
            print("No active agents to assign tickets.")

    def notify_pending_interaction_tickets(self):
        supporters = list(self._mc.find_supporters())

        supportersIds = map(lambda supporter: supporter["zendesk_id"], supporters)
        supportersTickets = self._get_assignees_tickets(supportersIds, ["open", "pending", "hold"])

        minInactiveHours = 24
        pendingInteractionTickets = self._get_pending_interaction_tickets(supportersTickets, minInactiveHours)

        if len(pendingInteractionTickets) == 0:
            print("No pending tickets to notify")
            return

        for supporter in supporters:
            supporterTickets = [ticket for ticket in pendingInteractionTickets if str(ticket.assignee_id) == supporter["zendesk_id"]]

            self._sl.notify_pending_interaction_tickets(supporter, supporterTickets, minInactiveHours)
Exemplo n.º 3
0
 def __init__(self, *args, **kwargs):
     creds = {
         "email": settings.ZENDESK_EMAIL,
         "token": settings.ZENDESK_TOKEN,
         "subdomain": settings.ZENDESK_SUBDOMAIN,
     }
     self.client = Zenpy(**creds)
Exemplo n.º 4
0
 def __init__(self, user, token, NoOfdays):
     self.creds = {'email': user, 'token': token, 'subdomain': 'qubole'}
     self.client = Zenpy(**self.creds)
     self.startTime = datetime.datetime.now() - datetime.timedelta(
         days=NoOfdays)
     self.result_generator = self.client.tickets.incremental(
         start_time=self.startTime)
Exemplo n.º 5
0
def close_ticket(prescription):
    if not isinstance(prescription, MedicalPrescription):
        return False

    mticket = ZendeskTicket.objects.filter(prescription=prescription).first()
    zenpy_client = Zenpy(**settings.ZENDESK)

    if not mticket:
        return False

    ticket = zenpy_client.tickets(id=mticket.external_id)

    ticket.status = 'solved'

    if prescription.status in domain_models.MedicalPrescription.STATUS_CHOICES:
        new_cf = []
        for cf in ticket.custom_fields:
            if cf.get('id', None) == 114103846891:
                new_cf.append({
                    'id': 114103846891,
                    'value': prescription.status.lower()
                })
            new_cf.append(cf)

        ticket.custom_fields = new_cf

    ticket_audit = zenpy_client.tickets.update(ticket)

    if ticket_audit:
        return True
    return False
Exemplo n.º 6
0
def index():
  try: # We use try method to keep running if there is no API available.
    # Default
    zenpy_client = Zenpy(**creds)
    ticket_generator = zenpy_client.tickets()
    return render_template('index.html', tickets=ticket_generator)
  except:
    print("Sorry, API isn't currently available")
Exemplo n.º 7
0
def delete_all_tickets():
    zenpy_client = Zenpy(**settings.ZENDESK)

    for ticket in zenpy_client.search(status="new"):
        zenpy_client.tickets.delete(ticket)

    for ticket in zenpy_client.search(status="open"):
        zenpy_client.tickets.delete(ticket)
Exemplo n.º 8
0
def get_description(ticket_id):
    global zenpy_client
    try:
        zenpy_client = Zenpy(**credentials)
        ticket = zenpy_client.tickets(id=ticket_id)
        return ticket.description
    except Exception as e:
        logger.exception("get_description {}".format(e))
        raise
Exemplo n.º 9
0
 def __init__(self):
     self._creds = {
         'email': os.environ.get('ZENDESK_USER', None),
         'token': os.environ.get('ZENDESK_TOKEN', None),
         'subdomain': "pagarme"
     }
     self._zenpy_client = Zenpy(**self._creds)
     self._sl = SlackConnection.SlackConnection()
     self._mc = MongoConnection.MongoConnection()
Exemplo n.º 10
0
def get_unclosed_tickets(email: str, token: str,
                         subdomain: str) -> Iterable[Ticket]:
    zenpy = Zenpy(subdomain, email, token)
    ticket: ZendeskTicket
    for ticket in zenpy.tickets():
        requester: ZendeskUser = ticket.requester
        waiting_on = None
        staled_at = None
        yield Ticket(ticket.id, ticket.subject, requester.email,
                     requester.email, ticket.status, waiting_on, staled_at,
                     ticket.created_at)
Exemplo n.º 11
0
def update_ticket(ticket_id, message):
    global zenpy_client
    comment = "```\n{}\n```".format(message)
    try:
        zenpy_client = Zenpy(**credentials)
        ticket = zenpy_client.tickets(id=ticket_id)
        ticket.comment = Comment(body=comment, public=False)
        zenpy_client.tickets.update(ticket)
    except Exception as e:
        logger.exception("update_ticket {}".format(e))
        raise
Exemplo n.º 12
0
    def validate_zendesk_credentials(subdomain: str, user_name: str,
                                     api_token: str):
        from zenpy import Zenpy
        from zenpy.lib.exception import APIException

        try:
            zendesk_client = Zenpy(subdomain=subdomain,
                                   email=user_name,
                                   token=api_token)
            list(zendesk_client.search(assignee='test'))
        except APIException as e:
            raise ActionFailure(e)
Exemplo n.º 13
0
    def __init__(self, config):
        super(ZendeskAction, self).__init__(config=config)
        self.email = self.config['email']
        self.token = self.config['api_token']
        self.subdomain = self.config['subdomain']

        self.credentials = {
            'email': self.email,
            'token': self.token,
            'subdomain': self.subdomain
        }

        self.api = Zenpy(**self.credentials)
Exemplo n.º 14
0
 def check_zendesk_ticket(foia):
     """Check if an open zendesk ticket exists for this FOIA"""
     client = Zenpy(
         email=settings.ZENDESK_EMAIL,
         subdomain=settings.ZENDESK_SUBDOMAIN,
         token=settings.ZENDESK_TOKEN,
     )
     response = client.search(
         "{}-{}".format(foia.slug, foia.pk),
         type="ticket",
         via="api",
         subject="FOIAOnline",
         status="open",
     )
     return len(list(response)) > 0
Exemplo n.º 15
0
def close_adf_ticket(ticket):
    if not isinstance(ticket, ZendeskASFTicket):
        return False

    zenpy_client = Zenpy(**settings.ZENDESK)

    ticket = zenpy_client.tickets(id=ticket.external_id)

    ticket.status = 'solved'

    ticket_audit = zenpy_client.tickets.update(ticket)

    if ticket_audit:
        return True
    return False
Exemplo n.º 16
0
def main():
    parsed_args = singer.utils.parse_args(REQUIRED_CONFIG_KEYS)
    creds = {"subdomain": parsed_args.config['subdomain']}

    try:
        oauth_args = singer.utils.parse_args(OAUTH_CONFIG_KEYS)
        creds.update({
            "oauth_token": oauth_args.config['access_token'],
        })
    except:
        LOGGER.debug("Cannot find oauth configuration.")

    try:
        api_args = singer.utils.parse_args(API_CONFIG_KEYS)
        creds.update({
            "email": api_args.config['email'],
            "token": api_args.config['api_token']
        })
    except:
        LOGGER.debug("Cannot find api token configuration.")

    client = Zenpy(**creds)

    if parsed_args.discover:
        do_discover(client)
    elif parsed_args.catalog:
        state = parsed_args.state
        do_sync(client, parsed_args.catalog, state,
                parsed_args.config['start_date'])
Exemplo n.º 17
0
def create_support_request(user, email, message, attachments=()):
    client = Zenpy(
        subdomain=settings.ZENDESK_SUBDOMAIN,
        email=settings.ZENDESK_EMAIL,
        token=settings.ZENDESK_TOKEN,
    )
    ticket_audit = client.tickets.create(
        Ticket(
            subject='Data Workspace Support Request',
            description=message,
            requester=User(email=email, name=user.get_full_name()),
            custom_fields=[
                CustomField(
                    id=zendesk_service_field_id, value=zendesk_service_field_value
                )
            ],
        )
    )
    if attachments:
        uploads = [client.attachments.upload(x) for x in attachments]
        ticket_audit.ticket.comment = Comment(
            body='Additional attachments', uploads=[x.token for x in uploads]
        )
        client.tickets.update(ticket_audit.ticket)
    return ticket_audit.ticket.id
Exemplo n.º 18
0
def create_ticket(title, description, impact, history, name, email):
    global ticket_number

    zendesk_client = Zenpy(**creds)

    # Create a new ticket
    ticket_audit = zendesk_client.tickets.create(
        Ticket(
            subject=title,
            requester=User(name=name, email=email),
            comment=Comment(
                html_body=
                '<h3>Request Details</h3><pre><code>Title: {}<br>Request: {}<br>'
                'Impact: {}<br>History: {}</code></pre><h3>Submitter Details</h3><pre><code>'
                'Name: {}<br>Email: {}</code></pre>'.format(
                    title, description, impact, history, name, email)),
            type="problem",
            priority="normal",
            requester_id="366101959011",
            submitter_id="366101959011",
            ticket_form_id="360000072631",
            group_id="360000964291",
            collaborator_ids=["443254580", "656182144"],
            follower_ids=["443254580", "656182144"],
            custom_fields=[
                CustomField(id=360005680151,
                            value='request_to_update_existing_process')
            ]))

    ticket_number = ticket_audit.ticket.id
Exemplo n.º 19
0
def main():
    parsed_args = singer.utils.parse_args(REQUIRED_CONFIG_KEYS)

    # OAuth has precedence
    creds = oauth_auth(parsed_args) or api_token_auth(parsed_args)
    session = get_session(parsed_args.config)

    # Pass some config options into the client
    rate_limit_settings = {}
    for key in ('proactive_ratelimit', 'proactive_ratelimit_request_interval',
                'ratelimit_budget'):
        if key in parsed_args.config:
            rate_limit_settings[key] = parsed_args.config.pop(key)
    LOGGER.info('zenpy rate limit settings = %r', rate_limit_settings)
    client = Zenpy(session=session, **rate_limit_settings, **creds)

    if not client:
        LOGGER.error("""No suitable authentication keys provided.""")

    if parsed_args.discover:
        do_discover(client)
    elif parsed_args.catalog:
        state = parsed_args.state
        start_date = parsed_args.config['start_date']
        lookback_minutes = parsed_args.config.get('lookback_minutes')
        do_sync(client, parsed_args.catalog, state, start_date,
                lookback_minutes)
Exemplo n.º 20
0
def _get_client():
    global zenpy_client
    # Zenpy will let the connection timeout after 5s and will retry 3 times
    if not zenpy_client:
        zenpy_client = Zenpy(timeout=5, **ZENPY_CREDENTIALS)

    return zenpy_client
Exemplo n.º 21
0
 def __init__(self, **kwargs):
     """Initialize Zendesk API client."""
     creds = {
         "email": settings.ZENDESK_USER_EMAIL,
         "token": settings.ZENDESK_API_TOKEN,
         "subdomain": settings.ZENDESK_SUBDOMAIN,
     }
     self.client = Zenpy(**creds)
Exemplo n.º 22
0
def send_to_zendesk(request_email, subject, message, user=None):
    ticket = create_zendesk_ticket(request_email, subject, message, user)
    zenpy = Zenpy(
        email=settings.ZENDESK_EMAIL,
        token=settings.ZENDESK_TOKEN,
        subdomain='freesound'
    )
    zenpy.tickets.create(ticket)
Exemplo n.º 23
0
def get_tickets(client: Zenpy) -> List:
    """
    Gets all tickets from the Zendesk API for the workspace.
    N.B.: will be inefficient at large size, should paginate requests
    in future.
    :param client: the Zenpy client connection object
    :return: a list of all tickets for the client workspace
    """
    return list(client.tickets())
 def __init__(self):
     self._creds = {
         'email': os.environ.get('ZENDESK_USER', None),
         'token': os.environ.get('ZENDESK_TOKEN', None),
         'subdomain': "pagarme"
     }
     self._zenpy_client = Zenpy(**self._creds)
     self._sl = SlackConnection.SlackConnection()
     self._mc = MongoConnection.MongoConnection()
Exemplo n.º 25
0
def send_to_zendesk(request_email, subject, message, user=None):
    ticket = create_zendesk_ticket(request_email, subject, message, user)
    zenpy = Zenpy(email=settings.ZENDESK_EMAIL,
                  token=settings.ZENDESK_TOKEN,
                  subdomain='freesound')
    try:
        zenpy.tickets.create(ticket)
    except (ZendeskAPIException, HTTPError, ZenpyException) as e:
        web_logger.info('Error creating Zendesk ticket: {}'.format(str(e)))
Exemplo n.º 26
0
def update_zendesk_ticket(ticket_id, comment=None, status=None):
    client = Zenpy(
        subdomain=settings.ZENDESK_SUBDOMAIN,
        email=settings.ZENDESK_EMAIL,
        token=settings.ZENDESK_TOKEN,
    )

    ticket = client.tickets(id=ticket_id)

    if comment:
        ticket.comment = Comment(body=comment, public=False)

    if status:
        ticket.status = status

    client.tickets.update(ticket)

    return ticket
Exemplo n.º 27
0
	def __init__(self, connector):
		self.connector = connector
		self.settings = frappe.get_doc("Zendesk Settings", None)
		if not self.settings.last_user_sync:
			frappe.db.set_value("Zendesk Settings", None, "last_user_sync", now_datetime())

		if not self.settings.last_org_sync:
			frappe.db.set_value("Zendesk Settings", None, "last_org_sync", now_datetime())

		self.name_field = 'id'

		try:
			self.zenpy_client = Zenpy(**{
				'email' : self.settings.email,
				'token' : self.settings.get_password(fieldname='api_token',raise_exception=False),
				'subdomain': self.settings.subdomain
			})
		except Exception as e:
			frappe.log_error(e, 'Zendesk Connection Error')

		try:
			found = False
			if self.settings.org_type_id:
				for field in self.zenpy_client.organization_fields():
					if field.id == self.settings.org_type_id:
						found = True

				if found == False:
					for field in self.zenpy_client.organization_fields():
						if field.key == 'is_supplier' and field.type == 'checkbox':
							frappe.db.set_value("Zendesk Settings", "Zendesk Settings", "org_type_id", field.id)
							found = True

				if found == False:
					self.create_custom_field()
			else:
				for field in self.zenpy_client.organization_fields():
					if field.key == 'is_supplier' and field.type == 'checkbox':
						frappe.db.set_value("Zendesk Settings", "Zendesk Settings", "org_type_id", field.id)
						found = True
				if found == False:
					self.create_custom_field()
		except Exception as e:
			frappe.log_error(e, 'Zendesk Setup Error')
Exemplo n.º 28
0
def zenpyz(oauth_token):
    creds = {"subdomain": subdomain, "oauth_token": oauth_token}

    # Import the Zenpy Class
    from zenpy import Zenpy

    zenpy_client = Zenpy(**creds)

    for comment in zenpy_client.tickets.comments(ticket_id=98):
        print comment.body
Exemplo n.º 29
0
def etl():
    s3 = boto3.client(
        's3',
        aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
        aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
        region_name=os.getenv("AWS_DEFAULT_REGION"),
    )
    zenpy = Zenpy(
        email=os.getenv("ZENDESK_EMAIL"),
        token=os.getenv("ZENDESK_TOKEN"),
        subdomain=os.getenv("OUR_SUBDOMAIN"),
    )
    dsn_string = os.getenv("REDSHIFT_CONN_STRING")

    # Process nonform tickets
    conn = psycopg2.connect(dsn_string)
    conn.set_session(autocommit=True)
    nonform_query = "SELECT MAX(created_at) FROM zendesk.tickets WHERE LENGTH(ticket_form)=0"
    start_date, end_date = find_dates(conn, query=nonform_query)

    filename = time.strftime("%d_%m_%Y") + '_zendesk_tickets.json'
    extract_tickets(zenpy, start_date, end_date, filename)
    stage_and_load_tickets(conn, s3, filename)

    delete_duplicates(conn)
    conn.close()

    # Process form tickets
    form_dsn = "host='hostname' dbname='public' user='******' password='******' port='5439'"
    conn = psycopg2.connect(dsn_string)
    conn.set_session(autocommit=True)
    form_query = "SELECT MAX(created_at) FROM zendesk.tickets WHERE LENGTH(ticket_form)>0"
    start_date, end_date = find_dates(conn, query=form_query)

    ticket_forms = [
        'Pre sale product enquiry',
        'Pre sale delivery enquiry',
        'Pre sale invoice enquiry',
        'Pre sale service enquiry',
        'Pre despatch order enquiry',
        'Post despatch delivery enquiry',
        'Post despatch returns enquiry',
        'Post despatch item damaged',
        'Technical enquiry',
        'Post despatch general enquiry',
    ]

    for form in tqdm(ticket_forms, leave=True):
        filename = time.strftime("%d_%m_%Y") + '_zendesk_tickets_' + str(
            form) + '.json'
        extract_tickets(zenpy, start_date, end_date, filename, form=form)
        stage_and_load_tickets(conn, s3, filename)

    delete_duplicates(conn)
    conn.close()
Exemplo n.º 30
0
def zdviewtest(view_title):
    zd_client = Zenpy(**creds)
    view = next(iter(zd_client.views.search(query=view_title) or []), None)
    print(view.title)
    for ticket in zd_client.views.tickets(view):
        metrics = zd_client.tickets.metrics(ticket.id)
        dd, hh, mm = days_hours_minutes(
            parse(metrics.status_updated_at) - parse(metrics.created_at))
        print(u"{0};{1};{2};{3};{4};{5};{6};{7}".format(
            ticket.id, ticket.subject, ticket.status, metrics.created_at,
            metrics.status_updated_at, dd, hh, mm))
Exemplo n.º 31
0
    def create_zendesk_ticket(self):

        zenpy_client = Zenpy(
            subdomain=settings.ZENDESK_SUBDOMAIN,
            email=settings.ZENDESK_EMAIL,
            token=settings.ZENDESK_TOKEN,
        )

        attachments = [
            value for field, value in self.cleaned_data.items()
            if field.startswith('attachment') and value
        ]

        if attachments:
            uploads = []
            for attachment in attachments:
                upload_instance = zenpy_client.attachments.upload(
                    attachment.temporary_file_path())
                uploads.append(upload_instance.token)
        else:
            uploads = None

        service = SERVICE_FIELD_MAPPING[self.cleaned_data['platform']]

        custom_fields = [
            CustomField(id=30041969, value=service),  # service
            CustomField(id=360000180437,
                        value=self.cleaned_data['department']),  # directorate
            CustomField(id=45522485,
                        value=self.cleaned_data['email']),  # email
            CustomField(id=360000188178,
                        value=self.cleaned_data['telephone']),  # Phone number
            CustomField(
                id=360000182638,
                value=self.cleaned_data['request_type']),  # Content request
            CustomField(id=360000180477,
                        value=self.cleaned_data['publication_date_explanation']
                        ),  # reason
            CustomField(id=360000180457,
                        value=str(
                            self.cleaned_data['publication_date']))  # due date
        ]

        ticket = zenpy_client.tickets.create(
            Ticket(subject=self.cleaned_data['title_of_request'],
                   custom_fields=custom_fields,
                   tags=['content_delivery', self.cleaned_data['platform']],
                   comment=Comment(html_body=self.formatted_text(),
                                   uploads=uploads),
                   requester=User(name=self.cleaned_data['name'],
                                  email=self.cleaned_data['email']))).ticket

        return ticket.id
Exemplo n.º 32
0
def import_tickets(tickets):
    creds = {
        'email': os.environ['DATABOT_ZD_EMAIL'],
        'token': os.environ['DATABOT_ZD_TOKEN'],
        'subdomain': os.environ['DATABOT_ZD_SUBDOMAIN']
    }
    zenpy_client = Zenpy(**creds)

    # Create a new ticket
    for ticket in tickets:
        print ticket
        ticket = Ticket(**ticket)
        zenpy_client.ticket_import.create(ticket)
Exemplo n.º 33
0
    def run(self):
        zenpy = Zenpy.__new__(Zenpy)
        zenpy.__init__(zenpy, ' ', ' ')

        node_list = []
        cache_node = container()
        cache_sections = self.generate_cache_sections(zenpy)
        for cache_section in cache_sections:
            node = paragraph()
            self.state.nested_parse(StringList(cache_section.split('\n')), 0, node)
            node_list.append(node)
        node_list.append(cache_node)
        return node_list
Exemplo n.º 34
0
def get_client(config):
    """Given a `config`, create a Zenpy API client."""
    zenpy_args = dict([
        (zenpy_key, getattr(config, config_key, None))
        for zenpy_key, config_key in [(
            'email', 'email'), ('password',
                                'password'), ('subdomain', 'subdomain')]
    ])

    try:
        zenpy_client = Zenpy(**zenpy_args)
    except zenpy.lib.exception.ZenpyException as exc:
        if getattr(config, 'unpickle_tickets', None):
            zenpy_args['password'] = zenpy_args['password'] or 'dummy_pass'
            zenpy_args['subdomain'] = zenpy_args['subdomain'] \
                or 'dummy_subdomain'
            zenpy_args['email'] = zenpy_args['email'] or 'dummy_email'
            zenpy_client = Zenpy(**zenpy_args)
        else:
            raise ZTVConfigException(str(exc))

    return handle_pickling(config, zenpy_client)
Exemplo n.º 35
0
    def __init__(self, config):
        super(ZendeskAction, self).__init__(config=config)
        self.email = self.config['email']
        self.token = self.config['api_token']
        self.subdomain = self.config['subdomain']

        self.credentials = {
            'email': self.email,
            'token': self.token,
            'subdomain': self.subdomain
        }

        self.api = Zenpy(**self.credentials)
Exemplo n.º 36
0
    def run(self):
        zenpy = Zenpy.__new__(Zenpy)
        zenpy.__init__(zenpy, ' ', ' ')

        node_list = []
        doc_sections = self.generate_sections(zenpy)

        output = '.. py:class:: Zenpy%s\n\n' % inspect.signature(zenpy.__class__)
        output += '  %s' % zenpy.__doc__

        node = container()
        self.state.nested_parse(StringList(output.split('\n')), 0, node)
        node_list.append(node)

        for doc_section in doc_sections:
            node = paragraph()
            self.state.nested_parse(StringList(doc_section.split('\n')), 0, node)
            node_list.append(node)
        return node_list