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
def run(self, subject, ticket_id): assert subject or ticket_id, 'subject or ticket id is required' if not subject: subject = '' try: # search for the tickets that match the subject line and with the status 'new' tics = self.client.search(ticket_id, subject=subject, type='ticket') print('total tickets found: ', tics.count) # process the list of ticket(s) for tic in tics: # Update the status to pending tic.status = 'pending' # comment on the ticket tic.comment = Comment(body='I am Working on it') self.client.tickets.update(tic) except RecordNotFoundException as e: print('Ticket not found. Exception is {}'.format(e)) except APIException as e: print( 'Api Exception occured while updating Ticket with subject {}'. format(subject)) except Exception as e: print( 'General Exception {} occured while updating Ticket with subject {}' .format(e, subject))
def setUp(self): self.test_element = Comment() self.test_object = Ticket(comments=ProxyList([self.test_element])) self.attribute_name = 'comments' self.proxy_list = getattr(self.test_object, self.attribute_name) self.test_object._clean_dirty() self.proxy_list._clean_dirty()
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
def run(self, subject, ticket_id): assert subject or ticket_id, 'subject or ticket id is required' if not subject: subject = '' try: # search for the tickets with subject match tics = self.client.search(ticket_id, subject=subject, type='ticket') for tic in tics: # update the ticket with status closed tic.status = 'closed' # comment on the ticket tic.comment = Comment(body='Closing the ticket') job_status = self.client.tickets.update(tic) print('Closed Ticket Status: ', job_status) except RecordNotFoundException as e: print('Ticket not found with subject {}'.format(subject)) except APIException as e: print( 'Api Exception occured while updating Ticket with subject {}'. format(subject)) except Exception as e: print( 'General Exception {} occured while updating Ticket with subject {}' .format(e, subject))
def setUp(self): self.test_object = Ticket(comments=ProxyDict( dict(comment=Comment(), list=[1, 3, 4], dict={ 1: 2, 3: 4 }))) self.attribute_name = 'comments' self.proxy_dict = getattr(self.test_object, self.attribute_name) self.proxy_dict._clean_dirty() self.test_object._clean_dirty()
def create_comment(self, ticket_id, desc, privacy, files=[]): """ # | Function to create comment for the given ticket id # | # | Arguments: # | <ticket_id>: Ticket id # | <desc>: description, Comment description # | # | Returns: Comment object """ user_id = self._get_zendesk_user_id() if not user_id: # | If user is False, then there is no email for the user # | in that case throw error raise ZendeskError(403, "No email address found for the user") author_id = user_id #If no attachments are present if not files: #Passing the contents for comment creation #We set the comment privacy via the public option(Privacy options are Public reply/Internal Note) data = { "author_id": author_id, "body": desc, "public": privacy, } else: #Enter this loop if there are attachments #Fetching the token list by passing the list of files token_list = self.create_attachment(files) #Passing the contents for comment creation #We set the comment privacy via the public option(Privacy options are Public reply/Internal Note) #We also pass the token list via uploads option data = { "author_id": author_id, "body": desc, "public": privacy, "uploads": token_list } try: comment = Comment(**data) ticket = Ticket(id=ticket_id) ticket.comment = comment created_comment = self._zenpy.tickets.update(ticket) return created_comment except Exception as e: LOG.error(str(e)) raise ZendeskError(str(e))
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
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
def create_ticket(zc, ticket_content, user_map, status_map): # Check if any users were not imported from the provided user data and create basic accound if not if ticket_content['submitter_id'] not in user_map: user_map = create_basic_user(zc, id=ticket_content['submitter_id'], usr_dict=user_map) if ticket_content['requester_id'] not in user_map: user_map = create_basic_user(zc, id=ticket_content['requester_id'], usr_dict=user_map) # Format list like strings in the data to proper python lists tags = ticket_content['tags'] \ .replace("(", "") \ .replace(")", "") \ .replace("[", "") \ .replace("]", "") \ .replace("'", "") tags = tags.split(",") tags.append("RJC") # Create ticket object tik = Ticket( id=int(ticket_content['id']), created_at=ticket_content['created_at'], subject=ticket_content['subject'], status=status_map[ticket_content['status']], submitter_id=user_map[ticket_content['submitter_id']], requester_id=user_map[ticket_content['requester_id']], updated_at=ticket_content["updated_at"], due_at=ticket_content['due_at'], tags=tags, custom_fields={ 1500004511962: ticket_content['dept'], 1500004439621: ticket_content['product information'], 1500004511982: int(ticket_content['emp id']), 1500004439641: ticket_content['start date'], 1500004439661: ticket_content['subscription'], 1500004439681: ticket_content['business name'], 1500004512022: ticket_content['about'] } ) # Provided a generic assignee id if the data is not provided if ticket_content['assignee_id'] not in user_map: tik.assignee_id = "1507432183881" # look up the foreign assignee_id in the user map else: tik.assignee_id = user_map[ticket_content['assignee_id']] # Store the provided description as a comment object tik.comment = Comment(body=ticket_content['description'], public=False) # Create the ticket zc.tickets.create(tik) return user_map
def commentTicket(self): """ :return: """ try: self._comment.body = self._dictValues['comment'] if self._comment.uploads is not None: self._updateObject.comment = Comment( body=self._comment.body, public=self._comment.public, uploads=[self.uploadFile(self._comment.uploads).token]) else: self._updateObject.comment = Comment( body=self._comment.body, public=self._comment.public) except Exception as er: if self._log is not None: self._log.error("{} - {}".format(self.__class__.__name__, er)) else: print("{} - {}".format(self.__class__.__name__, er)) return False
def lambda_handler(event, context): ticket = zenpy_client.tickets(id=event['Input']['Ticket_Id']) og_lang = event['Input']['Original_Langugage'] tolang = os.environ['target_language'] new_lang = event['Input']['TranslatedText'] ticket.comment = Comment( body=event['Input']['TranslatedText'], html_body= '<h4>Translated by Amazon Translate from {} to {}</h4><p>{}</p>'. format(og_lang, tolang, new_lang), public=False) zenpy_client.tickets.update(ticket)
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 _add_zd_comment(self, tickets: list, message: callable, public=False): """ Add a private note with the JIRA issue key to each ticket """ for ticket in tickets: ticket.comment = Comment(body=message(ticket), public=public) if tickets: jobs = [] # Bulk API accepts only 100 items at a time while len(tickets) > 100: batch = tickets[:100] tickets = tickets[100:] jobs.append(self.zd_client.tickets.update(batch)) jobs.append(self.zd_client.tickets.update(tickets)) self._track_jobs_status(jobs)
def create_zendesk_ticket( contact_email, user, goal, justification_text, approval_url, dataset_name, dataset_url, information_asset_owner, # nb this can be null information_asset_manager, # so can this ): client = Zenpy( subdomain=settings.ZENDESK_SUBDOMAIN, email=settings.ZENDESK_EMAIL, token=settings.ZENDESK_TOKEN, ) ticket_description = build_ticket_description_text( dataset_name, dataset_url, contact_email, user, justification_text, goal ) private_comment = build_private_comment_text( information_asset_owner, information_asset_manager, approval_url ) username = get_username(user) subject = f'Access Request for {dataset_name}' ticket_audit = client.tickets.create( Ticket( subject=subject, description=ticket_description, requester=User(email=contact_email, name=username), custom_fields=[ CustomField( id=zendesk_service_field_id, value=zendesk_service_field_value ) ], ) ) ticket_audit.ticket.comment = Comment(body=private_comment, public=False) client.tickets.update(ticket_audit.ticket) return ticket_audit.ticket.id
def create_zendesk_ticket(self): client = Zenpy( email=settings.ZENDESK_EMAIL, subdomain=settings.ZENDESK_SUBDOMAIN, token=settings.ZENDESK_TOKEN, ) description = self.text tags = ["flag", self.category.replace(" ", "_")] for obj_name in ["foia", "agency", "jurisdiction"]: obj = getattr(self, obj_name) if obj: description += "\n{}{}".format( settings.MUCKROCK_URL, obj.get_absolute_url() ) tags.append("{}_flag".format(obj_name)) if self.user: entitlements = list( self.user.organizations.values_list( "entitlement__slug", flat=True ).distinct() ) if "free" in entitlements and len(entitlements) > 1: entitlements.remove("free") tags.extend(entitlements) request = { "subject": self.get_category_display() or "Generic Flag", "comment": Comment(body=description), "type": "task", "priority": "normal", "status": "new", "tags": tags, } if self.user: requester = {"name": self.user.profile.full_name or self.user.username} if self.user.email: requester["email"] = self.user.email else: requester = {"name": "Anonymous User"} request["requester"] = ZenUser(**requester) request = client.requests.create(Request(**request)) return request.id
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
def create_zendesk_ticket(request, access_request, catalogue_item=None): client = Zenpy( subdomain=settings.ZENDESK_SUBDOMAIN, email=settings.ZENDESK_EMAIL, token=settings.ZENDESK_TOKEN, ) access_request_url = request.build_absolute_uri( reverse("admin:request_access_accessrequest_change", args=(access_request.id, ))) authorize_url = request.build_absolute_uri( reverse("admin:auth_user_change", args=[access_request.requester.id])) ticket_description = build_ticket_description_text(access_request, access_request_url, catalogue_item) private_comment = (build_private_comment_text( catalogue_item, authorize_url) if catalogue_item else None) username = get_username(access_request.requester) subject = f"Access Request for {catalogue_item if catalogue_item else username}" ticket_audit = client.tickets.create( Ticket( subject=subject, description=ticket_description, requester=User(email=access_request.requester.email, name=username), custom_fields=[ CustomField(id=zendesk_service_field_id, value=zendesk_service_field_value) ], )) ticket_audit.ticket.comment = Comment(body=private_comment, public=False) client.tickets.update(ticket_audit.ticket) return ticket_audit.ticket.id
def zenpy_update_ticket(output, text_detected_body, images_detected_body): credentials = { 'email': os.environ['ZENDESK_EMAIL'], 'token': os.environ['ZENDESK_TOKEN'], 'subdomain': os.environ['ZENDESK_SUBDOMAIN'] } zenpy_client = Zenpy(**credentials) ticket = zenpy_client.tickets(id=output['attachment_data']['ticket_id']) ticket.comment = Comment( body=text_detected_body, html_body= '<h4>Attachment processed by Amazon Textract & Amazon Rekognition</h4><p>{}<p><p>{}</p>' .format(images_detected_body, text_detected_body), public=False) zenpy_client.tickets.update(ticket) return
def process_ticket(ticket): my_ticket = ticket.to_dict() id = ticket.to_dict()['id'] if id not in processed_tickets: description = my_ticket['description'] # Sentences and embeddings sents = [ x for x in flatten([ x.split("\n\n") for x in nltk.sent_tokenize(my_ticket['description'])[:-1] ]) if x.strip() != '' and x not in invalid_sentences ] last_sentence = min([ i for (x, i) in zip(sents, range(len(sents))) if x.strip().lower().replace(",", "") in footer_text ] + [len(sents)]) sents = sents[0:last_sentence] infersent.build_vocab(sents, tokenize=True) embeddings = infersent.encode(sents, tokenize=True, verbose=False) ticket.comment = Comment(body=description, public=False)
def create_zendesk_ticket(subdomain: str, user_name: str, api_token: str, subject: str, description: str = None, comment: str = None, tags: list = None): from zenpy import Zenpy from zenpy.lib.exception import APIException from zenpy.lib.api_objects import Comment from zenpy.lib.api_objects import Ticket try: zendesk_client = Zenpy(subdomain=subdomain, email=user_name, token=api_token) comment = Comment(html_body=comment) zendesk_client.tickets.create( Ticket(subject=subject, description=description, tags=tags, comment=comment)) except APIException as e: raise ActionFailure(e)
def run(self, params={}): client = self.connection.client assignee_id = params.get("assignee_id") or None collaborator_ids = params.get("collaborator_ids") or None description = params.get("description") or None due_at = params.get("due_at") or None external_id = params.get("external_id") or None group_id = params.get("group_id") or None priority = (params.get("priority")) or None if priority: priority = priority.lower() problem_id = params.get("problem_id") or None recipient = params.get("recipient") or None requester_id = params.get("requester_id") or None status = (params.get("status")) or None if status: status = status.lower() subject = params.get("subject") or None tags = params.get("tags") or None t_type = (params.get("type")) or None if t_type: t_type = t_type.lower() ticket = Ticket( assignee_id=assignee_id, collaborator_ids=collaborator_ids, description=description, due_at=due_at, external_id=external_id, group_id=group_id, priority=priority, problem_id=problem_id, recipient=recipient, requester_id=requester_id, status=status, subject=subject, tags=tags, type=t_type, ) if params.get("attachment"): if params.get("attachment")["content"]: upload_instance = client.attachments.upload( params.get("attachment")["content"], target_name=params.get("attachment")["filename"], ) # content_type=None, content_url=None, file_name=None ticket.comment = Comment(body=params.get("description"), uploads=[upload_instance.token]) returned_ticket = client.tickets.create(ticket).ticket ticket_obj = { "assignee_id": returned_ticket.assignee_id, "brand_id": returned_ticket.brand_id, "collaborator_ids": returned_ticket.collaborator_ids, "created_at": returned_ticket.created_at, "description": returned_ticket.description, "due_at": returned_ticket.due_at, "external_id": returned_ticket.external_id, "forum_topic_id": returned_ticket.forum_topic_id, "group_id": returned_ticket.group_id, "has_incidents": returned_ticket.has_incidents, "id": returned_ticket.id, "organization_id": returned_ticket.organization_id, "priority": returned_ticket.priority, "problem_id": returned_ticket.problem_id, "raw_subject": returned_ticket.raw_subject, "recipient": returned_ticket.recipient, "requester_id": returned_ticket.requester_id, "sharing_agreement_ids": returned_ticket.sharing_agreement_ids, "status": returned_ticket.status, "subject": returned_ticket.subject, "submitter_id": returned_ticket.submitter_id, "tags": returned_ticket.tags, "type": returned_ticket.type, "updated_at": returned_ticket.updated_at, "url": returned_ticket.url, } return ticket_obj
def run(self, params={}): client = self.connection.client assignee_id = params.get('assignee_id') or None collaborator_ids = params.get('collaborator_ids') or None description = params.get('description') or None due_at = params.get('due_at') or None external_id = params.get('external_id') or None group_id = params.get('group_id') or None priority = (params.get('priority')) or None if priority: priority = priority.lower() problem_id = params.get('problem_id') or None recipient = params.get('recipient') or None requester_id = params.get('requester_id') or None status = (params.get('status')) or None if status: status = status.lower() subject = params.get('subject') or None tags = params.get('tags') or None t_type = (params.get('type')) or None if t_type: t_type = t_type.lower() ticket = Ticket(assignee_id=assignee_id, collaborator_ids=collaborator_ids, description=description, due_at=due_at, external_id=external_id, group_id=group_id, priority=priority, problem_id=problem_id, recipient=recipient, requester_id=requester_id, status=status, subject=subject, tags=tags, type=t_type) if params.get('attachment'): if params.get('attachment')['content']: upload_instance = client.attachments.upload( params.get('attachment')['content'], target_name=params.get('attachment')['filename'] ) # content_type=None, content_url=None, file_name=None ticket.comment = Comment(body=params.get('description'), uploads=[upload_instance.token]) returned_ticket = client.tickets.create(ticket).ticket ticket_obj = { 'assignee_id': returned_ticket.assignee_id, 'brand_id': returned_ticket.brand_id, 'collaborator_ids': returned_ticket.collaborator_ids, 'created_at': returned_ticket.created_at, 'description': returned_ticket.description, 'due_at': returned_ticket.due_at, 'external_id': returned_ticket.external_id, 'forum_topic_id': returned_ticket.forum_topic_id, 'group_id': returned_ticket.group_id, 'has_incidents': returned_ticket.has_incidents, 'id': returned_ticket.id, 'organization_id': returned_ticket.organization_id, 'priority': returned_ticket.priority, 'problem_id': returned_ticket.problem_id, 'raw_subject': returned_ticket.raw_subject, 'recipient': returned_ticket.recipient, 'requester_id': returned_ticket.requester_id, 'sharing_agreement_ids': returned_ticket.sharing_agreement_ids, 'status': returned_ticket.status, 'subject': returned_ticket.subject, 'submitter_id': returned_ticket.submitter_id, 'tags': returned_ticket.tags, 'type': returned_ticket.type, 'updated_at': returned_ticket.updated_at, 'url': returned_ticket.url } return ticket_obj
def create_zendesk_ticket(instance): try: zenpy_client = Zenpy(**settings.ZENDESK) if type(instance) in [str, int]: instance = domain_models.MedicalPrescription.objects.filter( id=int(instance)).first() desc = "" if instance.period_info: desc = "Última menstruação: {}".format(instance.period_info) desc = """{} Informações Adicionais: {}""".format(desc, instance.additional_info or "Nenhuma") try: if instance.preferred_laboratory: desc = """{} Laboratório preferido: {}""".format( desc, instance.preferred_laboratory.description or "Nenhuma") except Exception: print(instance.preferred_laboratory) try: if instance.preferred_date_to_schedule: desc = """{} Data preferida: {}""".format( desc, instance.preferred_date_to_schedule.strftime( "%Y-%m-%d %H:%M:%S") or "Nenhuma") except Exception: print(instance.preferred_date_to_schedule) selfie = '' if instance.patient.selfie_uploadcare: selfie = instance.patient.selfie_uploadcare.url elif instance.patient.selfie: selfie = instance.patient.selfie.url ticket = zenpy_client.tickets.create( Ticket(subject='Prescrição para: {}'.format( instance.patient.full_name), requester=User(name=instance.patient.full_name, external_id=instance.patient.user.id, email=instance.patient.user.email, remote_photo_url=selfie, user_fields=UserField( gender=instance.patient.gender, phone=str(instance.patient.phone))), type='task', priority='normal', custom_fields=[ CustomField(id=114103586991, value='patient_requested'), CustomField(id=114103769352, value=instance.patient.phone), CustomField(id=114103769652, value=instance.patient.gender) ], description=desc)) # a = MedicalPrescription.objects.all().last() # from general_utils.utils import create_zendesk_ticket # create_zendesk_ticket(a) et = ticket.ticket tdata = et.to_dict() del (tdata['via']) print(tdata) try: print('###') zticket = ZendeskTicket.objects.create(external_id=et.id, prescription=instance, content=tdata) except Exception: print('***') zticket = ZendeskTicket.objects.filter( prescription=instance).first() zticket.external_id = et.id zticket.content = tdata zticket.save() print(zticket) et.external_id = zticket.id et.tags.extend([u'prescrição', u'saracare']) # # from general_utils.utils import create_zendesk_ticket # p = MedicalPrescription.objects.all().last() # create_zendesk_ticket(p) ppieces = [] for ppiece in instance.pieces.all(): if ppiece.picture: ppieces.append(("Precrição", ppiece.picture.file)) for name, file in [ ("RG frente", instance.picture_id_front_uploadcare.file if instance.picture_id_front_uploadcare else None), ("RG verso", instance.picture_id_back_uploadcare.file if instance.picture_id_back_uploadcare else None), ("Plano frente", instance.picture_insurance_card_front_uploadcare.file if instance.picture_insurance_card_front_uploadcare else None), ("Plano verso", instance.picture_insurance_card_back_uploadcare.file if instance.picture_insurance_card_back_uploadcare else None) ] + ppieces: if file: upload_instance = zenpy_client.attachments.upload(file) et.comment = Comment(body=name, uploads=[upload_instance.token]) zenpy_client.tickets.update(et) zenpy_client.tickets.update(et) except Exception as e: print("Creation Error: {}".format(e))
def create_adf_zendesk_tickets(instances): try: print('init adf creation') zenpy_client = Zenpy(**settings.ZENDESK) scs = ScheduledExam.objects.filter(id__in=instances) if not scs: print("No adf tickets to create") return onesc = scs.first() mp = onesc.prescription desc = """Data de abertura: {} Laboratório:{} Exames: {} """ lab_name = onesc.laboratory.description if onesc.laboratory else '' print(desc) ticket = zenpy_client.tickets.create( Ticket( subject='Abertura de ficha para: {} no laboratório: {}'.format( mp.patient.full_name, lab_name), requester=User(name=mp.patient.full_name, external_id=mp.patient.user.id, email=mp.patient.user.email), type='task', status='open', priority='normal', due_at=onesc.scheduled_time, custom_fields=[ CustomField(id=114103586991, value='patient_requested'), CustomField(id=114103769352, value=mp.patient.phone), CustomField(id=114103769652, value=mp.patient.gender), CustomField(id=360002412071, value=onesc.scheduled_time.date()) ], description=desc.format( onesc.scheduled_time.strftime('%d/%m/%Y %H:%M'), onesc.laboratory.description, ', '.join([i.exam.name for i in scs])))) et = ticket.ticket tdata = et.to_dict() del (tdata['via']) print(tdata) try: zticket = ZendeskASFTicket.objects.create(external_id=et.id, content=tdata) except Exception as e: print('*** {} ***'.format(e)) print("Ticket for exams: {} already created".format( scs.values('id'))) zticket = ZendeskASFTicket.objects.filter( external_id=et.id).first() print(zticket) et.external_id = zticket.id et.tags.extend([u'saracare', u'aberturadeficha']) ppieces = [] for name, file in [ ("RG frente", mp.picture_id_front_uploadcare.file if mp.picture_id_front_uploadcare else None), ("RG verso", mp.picture_id_back_uploadcare.file if mp.picture_id_back_uploadcare else None), ("Plano frente", mp.picture_insurance_card_front_uploadcare.file if mp.picture_insurance_card_front_uploadcare else None), ("Plano verso", mp.picture_insurance_card_back_uploadcare.file if mp.picture_insurance_card_back_uploadcare else None) ] + ppieces: if file: upload_instance = zenpy_client.attachments.upload(file) et.comment = Comment(body=name, uploads=[upload_instance.token]) zenpy_client.tickets.update(et) zenpy_client.tickets.update(et) scs.update(zendesk_adf_ticket=zticket) except Exception as e: print("Creation Error: {}".format(e))
def update_ticket(self, source, update_field): ticket = self.find_target_ticket_for_original_id(source.id) if not ticket: print('Target ticket not found for %s' % source.id) return 0 elif ticket.status == 'deleted' or ticket.status == 'closed': print('Skipping %s ticket: %s' % (ticket.status, ticket.id)) return 0 print('Ticket %s - %s' % (ticket.id, ticket.subject)) if update_field == 'cc': if len(source.collaborator_ids) > 0: new_collab_ids = ticket.collaborator_ids for collab_id in source.collaborator_ids: new_collab_ids.append(self.get_target_user_id(collab_id)) ticket.collaborator_ids = new_collab_ids self.target_client.tickets.update(ticket) print('- Successfully updated collaborators for ticket %s' % ticket.id) else: print('- No collaborators to update for ticket %s' % ticket.id) elif update_field == 'comment_attach': for comment in self.target_client.tickets.comments(ticket=ticket): if comment.body == 'Inline attachments': print('- Skipping, ticket already updated') return uploads = [] for source_comment in self.source_client.tickets.comments(ticket=source): matches = re.findall(self.HTML_IMG_TAG_PATTERN, source_comment.html_body) for match in matches: img_tag = match[0] url = match[1] print('- Found src url in comment: %s' % url) do_upload = False source_domain = '%s.zendesk.com' % self.SOURCE_INSTANCE if source_domain in url: do_upload = True elif self.SOURCE_HELPCENTER_DOMAIN in url: do_upload = True if do_upload: response = requests.get(url, auth=self.source_auth) if not response.status_code == 200: print('- ERROR getting attachment %s: %s' % (url, response.status_code)) continue file_name = 'attachment' content_disp = response.headers.get('content-disposition') if content_disp: file_name_match = re.search('inline; filename=\"(.*)\"', content_disp) if file_name_match: file_name = file_name_match.group(1) else: continue content_type = response.headers.get('content-type') if self.DEBUG: print('- DEBUG Attachment created - %s' % file_name) else: with tempfile.TemporaryFile() as tmp_file: tmp_file.write(response.content) tmp_file.seek(0) try: upload = self.target_client.attachments.upload(fp=tmp_file, target_name=file_name, content_type=content_type) print('- Attachment created - %s' % file_name) uploads.append(upload.token) except Exception as e: print('WARN Exception creating attachment %s - %s' % (file_name, e)) if len(uploads) > 0: ticket.comment = Comment(html_body='Inline attachments', public=False, uploads=uploads) print('- Updating ticket with attachment comment') self.target_client.tickets.update(ticket)
def migrate_ticket(self, source, status_to_migrate='all'): end_time = 'N/A' try: end_time = source.generated_timestamp except AttributeError: pass if source.status == 'deleted': print('Skipping deleted ticket: %s (timestamp: %s)' % (source.id, end_time)) return 0 if (not status_to_migrate == 'all' and not status_to_migrate == 'not_closed' and not source.status == status_to_migrate) or \ (status_to_migrate == 'not_closed' and source.status == 'closed'): print('Skipping, ticket status is %s: %s (timestamp: %s)' % (source.status, source.id, end_time)) return 0 # Look for an existing ticket existing = self.find_target_ticket_for_original_id(source.id) if existing: # Existing tickets will be updated with the events API print('Existing ticket found for %s (timestamp: %s)' % (source.id, end_time)) return existing.id print('Migrating ticket %s - %s' % (source.id, source.subject)) ticket = Ticket(created_at=source.created_at, updated_at=source.updated_at, subject=source.subject, priority=source.priority, type=source.type, status=source.status, tags=source.tags, recipient=source.recipient, brand_id=self.get_target_brand_id(source.brand_id)) if source.ticket_form_id: ticket.ticket_form_id = self.get_target_ticket_form_id(source.ticket_form_id) # Organization org_id = source.organization_id if org_id: new_org_id = self.get_target_org_id(org_id) if new_org_id: ticket.organization_id = new_org_id # Collaborators collab_ids = source.collaborator_ids new_collab_ids = [] for collab_id in collab_ids: new_collab_ids.append(self.get_target_user_id(collab_id)) ticket.collaborator_ids = new_collab_ids # Custom fields source_fields = source.custom_fields custom_fields = {} for field in source_fields: custom_fields[self.get_target_ticket_field_id(field.get('id'))] = field.get('value') custom_fields[self.original_id_field] = source.id ticket.custom_fields = custom_fields # Comments comments = self.source_client.tickets.comments(source) new_comments = [] for comment in comments: new_comment = Comment(created_at=comment.created_at, html_body=comment.html_body, public=comment.public, metadata=comment.metadata) # Author author_id = comment.author_id new_comment.author_id = self.get_target_user_id(author_id) # Inline Attachments comment_body = comment.html_body uploads = [] matches = re.findall(self.HTML_IMG_TAG_PATTERN, comment_body) if len(matches) > 0: for match in matches: img_tag = match[0] url = match[1] print('- Found src url in comment: %s' % url) do_upload = False source_domain = '%s.zendesk.com' % self.SOURCE_INSTANCE source_alt_domain = '%s.zendesk.com' % self.SOURCE_ALT_INSTANCE if source_domain in url or source_alt_domain in url: do_upload = True url = url.replace(source_alt_domain, source_domain) elif self.SOURCE_HELPCENTER_DOMAIN in url: do_upload = True if do_upload: response = requests.get(url, auth=self.source_auth) if not response.status_code == 200: print('- ERROR getting attachment %s: %s' % (url, response.status_code)) continue file_name = 'attachment' content_disp = response.headers.get('content-disposition') if content_disp: file_name_match = re.search('inline; filename=\"(.*)\"', content_disp) if file_name_match: file_name = file_name_match.group(1) else: continue content_type = response.headers.get('content-type') if self.DEBUG: print('- DEBUG Attachment created - %s' % file_name) comment_body = comment_body.replace(img_tag, '<See Attachment>') else: with tempfile.TemporaryFile() as tmp_file: tmp_file.write(response.content) tmp_file.seek(0) try: upload = self.target_client.attachments.upload(fp=tmp_file, target_name=file_name, content_type=content_type) print('- Attachment created - %s' % file_name) comment_body = comment_body.replace(img_tag, '[See Attachment]') uploads.append(upload.token) except Exception as e: print('WARN Exception creating attachment %s - %s' % (file_name, e)) new_comment.html_body = comment_body # Non-inline Attachments attachments = comment.attachments if attachments and len(attachments) > 0: for attachment in attachments: url = attachment.content_url file_name = attachment.file_name content_type = attachment.content_type response = requests.get(url) if self.DEBUG: print('- DEBUG Attachment created - %s' % file_name) else: with tempfile.TemporaryFile() as tmp_file: tmp_file.write(response.content) tmp_file.seek(0) try: upload = self.target_client.attachments.upload(fp=tmp_file, target_name=file_name, content_type=content_type) print('- Attachment created - %s' % file_name) uploads.append(upload.token) except Exception as e: print('WARN Exception creating attachment %s - %s' % (file_name, e)) new_comment.uploads = uploads new_comments.append(new_comment) ticket.comments = new_comments # Submitter ticket.submitter_id = self.get_target_user_id(source.submitter_id) # Requestor requester_id = source.requester_id if requester_id: requester = self.get_target_user(requester_id) if requester: if requester.suspended: # End-users can't be assigned tickets comment = Comment(body='Requester was %s (suspended)' % requester.name, public=False) ticket.comments.append(comment) else: ticket.requester_id = requester.id # Assignee assignee_id = source.assignee_id group_id = source.group_id if assignee_id: assignee = self.get_target_user(assignee_id) if assignee: if assignee.role == 'end-user': # End-users can't be assigned tickets comment = Comment(body='Assignee was %s (suspended)' % assignee.name, public=False) ticket.comments.append(comment) else: ticket.assignee_id = assignee.id elif group_id: ticket.group_id = self.get_target_group_id(group_id) # Linked source/problem_id source_problem_id = source.problem_id if source_problem_id: problem_ticket = self.find_target_ticket_for_original_id(source_problem_id) if problem_ticket: if problem_ticket.type == 'problem': print('- Linking existing problem ticket for %s' % source_problem_id) ticket.problem_id = problem_ticket.id else: # Can't link them comment = Comment(body='Linked ticket %s is not a problem, could not link' % problem_ticket.id, public=False) ticket.comments.append(comment) else: # Migrate the problem ticket if self.DEBUG: print('- DEBUG Problem ticket not found, creating for %s' % source_problem_id) else: print('- Problem ticket not found, creating for %s' % source_problem_id) source_problem = self.source_client.tickets(id=source_problem_id) ticket.problem_id = self.migrate_ticket(source_problem) # Wait 60 sec for this to show up time.sleep(60) new_ticket_id = None if self.DEBUG: print('- DEBUG Successfully migrated ticket %s to %s (timestamp: %s)' % (source.id, new_ticket_id, end_time)) else: new_ticket_id = self.target_client.ticket_import.create(ticket) print('- Successfully migrated ticket %s to %s (timestamp: %s)' % (source.id, new_ticket_id, end_time)) return new_ticket_id