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(self, user, ticket_fields): """Create a ticket in Zendesk.""" ticket = Ticket( subject=ticket_fields.get("subject"), comment={"body": ticket_fields.get("description")}, ticket_form_id=settings.ZENDESK_TICKET_FORM_ID, custom_fields=[ { "id": settings.ZENDESK_PRODUCT_FIELD_ID, "value": ticket_fields.get("product") }, { "id": settings.ZENDESK_CATEGORY_FIELD_ID, "value": ticket_fields.get("category") }, { "id": settings.ZENDESK_OS_FIELD_ID, "value": ticket_fields.get("os") }, { "id": settings.ZENDESK_COUNTRY_FIELD_ID, "value": ticket_fields.get("country") }, ], ) if user.profile.zendesk_id: # TODO: is this necessary if we're updating users as soon as they're updated locally? ticket.requester_id = self.update_user(user).id else: ticket.requester_id = self.create_user(user).id return self.client.tickets.create(ticket)
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()
class TestProxyDict(TestCase): __test__ = True 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 test_proxy_dict_assign(self): self.proxy_dict['things'] = True self._assert_dirty() def test_proxy_dict_del(self): del self.proxy_dict['comment'] self._assert_dirty() def test_proxy_dict_update(self): self.proxy_dict.update({10: 10}) self._assert_dirty() def test_proxy_dict_pop(self): self.proxy_dict.pop(self.attribute_name) self._assert_dirty() def test_proxy_dict_popitem(self): self.proxy_dict.popitem() self._assert_dirty() def test_proxy_dict_clear(self): self.proxy_dict.clear() self._assert_dirty() def test_proxy_dict_wraps_list(self): some_list = self.proxy_dict['list'] self.assertIsInstance(some_list, ProxyList) def test_proxy_list_wraps_dict(self): some_dict = self.proxy_dict['dict'] self.assertIsInstance(some_dict, ProxyDict) def test_proxy_dict_wraps_zenpy_object(self): comment = self.proxy_dict['comment'] self.assertTrue(callable(comment._dirty_callback)) def _assert_dirty(self): self.assertTrue(self.proxy_dict._dirty) self.assertIn(self.attribute_name, self.test_object.to_dict(serialize=True))
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 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 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 create_ticket(self, data, request): """ # | Function to create a ticket. # | # | Arguments: # | Data in dictionary, required to create a ticket # | # | Return Type: Ticket object """ #Checking the user have the email, if no then error message need to show if not self._user_has_email(): LOG.error("No email address found for the user") raise ZendeskError(403, "No email address found for the user") try: zendesk_user_id = self._get_zendesk_user_id(data) data['requester_id'] = zendesk_user_id #if the submitter selected the user from the list if data['user'] != '': data['submitter_id'] = zendesk_user_id #Creating the ticket using the data ticket = Ticket(**data) created_ticket = self._zenpy.tickets.create(ticket) return created_ticket except Exception as e: LOG.error(str(e)) raise ZendeskError(500, str(e))
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 test_object_retrieval(self): ticket_id = 1 ticket = Ticket(id=ticket_id) self.cache[ticket_id] = ticket self.assertEqual(len(self.cache), 1) self.assertIs(self.cache[ticket_id], ticket)
def create_zendesk_ticket(self, cleaned_data): request_data = {**cleaned_data} if not self.request.user.is_authenticated: request_data["text"] = "account reactivation request\n" else: request_data["email"] = self.request.user.email application = self.request.session.get( LAST_FAILED_APPLICATION_SESSION_KEY, "Unspecified") request_data[ "text"] = f"require access to application: {application}\n" zendesk_user = ZendeskUser(name=cleaned_data["full_name"], email=request_data["email"]) description = "Name: {full_name}\nTeam: {team}\nEmail: {email}\n{text}".format( **request_data) ticket = Ticket( subject=settings.ZENDESK_TICKET_SUBJECT, description=description, requester=zendesk_user, custom_fields=[CustomField(id="31281329", value="auth_broker")], ) response = self.get_zendesk_client().tickets.create(ticket) return response.ticket.id
def create_zendesk_ticket(self, description, zendesk_user): ticket = Ticket( subject='Invest feedback', description=description, submitter_id=zendesk_user.id, requester_id=zendesk_user.id, ) _get_client().tickets.create(ticket)
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 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)
def run(self, subject, description): try: # Create a new ticket object with subject and description newTicket = Ticket(subject=subject, description=description) # call api to create it response = self.client.tickets.create(newTicket) # capture and return the id return response.ticket.id except APIException as e: print('Adding ticket with subject {} failed with API exception {}'. format(subject, e)) except Exception as e: print( 'Adding ticket with subject {} failed with General exception {}' .format(subject, e))
def create_zendesk_ticket(self, cleaned_data, zendesk_user): description = ( 'Name: {full_name}\n' 'Email: {email_address}\n' 'Company: {company_name}\n' 'Country: {country}\n' 'Comment: {comment}' ).format(**cleaned_data) ticket = Ticket( subject=settings.ZENDESK_TICKET_SUBJECT, description=description, submitter_id=zendesk_user.id, requester_id=zendesk_user.id, ) zenpy_client.tickets.create(ticket)
def create_support_request(user, email, message): 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) ], )) return ticket_audit.ticket.id
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 report(request, **kwargs): """Report issues with block diagram.""" bd = get_object_or_404(BlockDiagram, pk=kwargs.get('pk')) description = request.data.get('description') user = request.user source_id = bd.id source_name = bd.name bd.pk = None bd.name = f'{source_id} - {bd.name}' support = User.objects.get(email=settings.SUPPORT_CONTACT) bd.user = support if BlockDiagram.objects.filter(user=support, name=bd.name).exists(): bd.name = BlockDiagramViewSet._find_unique_name(bd.name, support) bd.save() body = loader.render_to_string( 'email/issue_report.html', { 'user': user, 'id': source_id, 'name': source_name, 'description': description, }) ZENDESK.tickets.create( Ticket( subject='Program Issue Reported', description=body, type='problem', tags=['program'], requester=ZendeskUser(name=user.username, email=user.email), )) SUMO_LOGGER.info( json.dumps({ 'event': 'report', 'userId': user.id, 'sourceProgramId': source_id, 'newProgramId': bd.id, })) return Response(status.HTTP_200_OK)
def create_ticket(self, subject, payload, zendesk_user, service_name): description = [ '{0}: {1}'.format(key.title().replace('_', ' '), value) for key, value in sorted(payload.items()) if not key.title().startswith('_') ] ticket = Ticket( subject=subject, description='\n'.join(description), submitter_id=zendesk_user.id, requester_id=zendesk_user.id, tags=payload.get('_tags') or None, custom_fields=[{ 'id': self.custom_field_id, 'value': service_name }] + (payload.get('_custom_fields') or []), ) return self.client.tickets.create(ticket)
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 send_data(self, analyzer_responses: List[AnalyzerResponse], config: ZendeskSinkConfig, **kwargs): responses = [] payloads = [] for analyzer_response in analyzer_responses: payloads.append( self.convertor.convert( analyzer_response=analyzer_response, base_payload=dict() if config.base_payload is None else deepcopy(config.base_payload), summary_max_length=config.summary_max_length, labels_count=config.labels_count)) for payload in payloads: response = config.get_client().tickets.create(Ticket(**payload)) logger.info(f"response='{response}'") responses.append(response) return responses
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 create_zendesk_ticket(self, cleaned_data): email = self.request.user.email application = self.request.session.get('_last_failed_access_app', 'Unspecified') zendesk_user = ZendeskUser(name=cleaned_data['full_name'], email=email) description = ( 'Name: {full_name}\n' 'Team: {team}\n' 'Email: {email}\n' 'Application: {application}\n' ).format(email=email, application=application, **cleaned_data) ticket = Ticket( subject=settings.ZENDESK_TICKET_SUBJECT, description=description, requester=zendesk_user, custom_fields=[CustomField(id='31281329', value='auth_broker')] ) response = self.get_zendesk_client().tickets.create(ticket) return response.ticket.id
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)
"""insert into %s values (%%s,%%s,%%s,%%s,%%s)""" % ("offenen_eigene_rechnungen_VIP"), (date_, date_, row[11], "yes", 29.95)) von = "Internes To Do: VIP Model Abbuchung pending" email = "*****@*****.**" betreff = "Abbuchung VIP Model " + str( now.month) + "/" + str( now.year ) + " pending: Kundennummer #" + row[11] message = """Abbuchnung von 29,95 EUR fuer VIP Model """ + str( now.month ) + "/" + str( now.year ) + """ noch durchzufuehren. Email-Adresse des Kunden ist """ + row[ 0] + """. Zahlungsmittel ist """ + row[56] creds = { 'email': '*****@*****.**', 'token': 'oY8q9R9T4io7ZwQ1KdDktKwXgF3sWhMneMECjpL0', 'subdomain': 'darlinglace' } zenpy_client = Zenpy(**creds) zenpy_client.tickets.create( Ticket(description=message, subject=betreff, requester=User(name=von, email=email))) conn.commit()
def populate_cache(self, num_objects): for i in range(num_objects): self.cache[i] = Ticket(id=i)
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
payload_zoom.append({ "action": "create", "user_info": { "email": x, "type": "2", "first_name": y, "last_name": z } }) for x in payload_zoom: try: zoom_invite = requests.request("POST", zoom_url, json=x, headers=zoom_headers) except: pass for x in user: if x['primaryEmail'] in skippable_emails: continue try: zenpy_client.tickets.create( Ticket( subject="New Hire | {}".format(x['primaryEmail']), description="User Created {}\n username: {}\n password: {}" .format(x['primaryEmail'], x['primaryEmail'], x['password']))) except: pass
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