def jiraConnect(user, pswd, host, issue):
    jira = JIRA(basic_auth=(user, pswd), options={'server': host})
    projects = jira.projects()
    for project in projects:
        if project.key == issue:
            issue_id = project.id
    if issue_id:
        tckt = prepSummary(issue)  
        #Creating ticket  
        new_issue = jira.create_issue(fields=tckt)
        print new_issue
        #Attaches the *.txt files under /tmp directory.
        files =  glob.glob(filepath)
        if len(files)==0:
            sendmail("failed","Issue created, however file attaching failed")
            exit(1)
        else:
        for file in files:
            jira.add_attachment(new_issue,file)
            jira.add_comment(new_issue, 'Required files are Attached!')
        sendmail("success","Ticket has been created with the required evidence attached!")
        
#main def
def main():
    #server, user credentials 
    user_name  = 'user'
    user_pass  = '******'
    server     = 'http://jiraexample.com:8080'
    issue_type = 'BUG'
    try:
        jiraConnect(user_name, user_pass, server, issue_type)
    except Exception, e:
        sendmail("failed", str(e))
        exit(1)
Example #2
0
def post_to_jira():

    jira=JIRA(basic_auth=(uid,jpwd),options={'server': 'https://jira.client.com','headers': {'X-Atlassian-Token': 'nocheck'}})
    
    workbook = xlrd.open_workbook(logname)
    worksheet = workbook.sheet_by_index(0)
    wb = copy(workbook)
    w_sheet = wb.get_sheet(0)

    num_rows = worksheet.nrows - 1
    num_cells = worksheet.ncols - 1
    curr_row = 0
    while curr_row < num_rows:
        curr_row+=1
        issue=jira.issue(worksheet.cell_value(curr_row, 0))
        curr_status = worksheet.cell_value(curr_row, 5)
        comment = worksheet.cell_value(curr_row, 6)
        spoolfile= working_dir+"\\"+worksheet.cell_value(curr_row,0)+"\\"+worksheet.cell_value(curr_row,4)
        # print spoolfile
        if curr_status=="DEPLOYED":
            jira.add_comment(issue,comment)            
            jira.add_attachment(issue,spoolfile)
            jira.assign_issue(issue,'sqadepartment')
            w_sheet.write(curr_row,5,"COMPLETED")
            webbrowser.open_new_tab('https://jira.client.com/browse/'+issue.key)
            
    wb.save(logname)
Example #3
0
# set the filename in the spreadsheet 
print issue.fields.attachment
sqls=0
for i in issue.fields.attachment:
    print i
    print i.get()
    if str(i).endswith('.txt'):
        sqls+=1
if sqls==1:
    print "1 found"
else:
    print "Not 1 found"
###################3

jira.add_attachment(issue,"C:\\Users\\shsrinivasan\\Desktop\\Micore\\Python\\test\\testERR.sql")

#jira.assign_issue(issue,'noc_change_manager')
#print issue.fields.assignee



#noc_change_manager
#sqadepartment

# Pertinent data fields:
#   ticket number       i.key
#   description         i.fields.summary
#   assignee            i.fields.assignee
#   str(issue.fields.status)
#jira.add_comment(issue,'Deployed to production, please see attached .log file')
Example #4
0
def pushtoJIRA(peopleid):
    jira_options={'server': 'https://ssesnexgen2055.atlassian.net'}
    jira=JIRA(options=jira_options,basic_auth=('*****@*****.**','5hp27ct#NNs2by;H'))

    conn = pymssql.connect(server='52.90.181.236', user='******', password='******', database='iCIMS')
    cursor = conn.cursor()
    cursor.execute('SELECT TOP (1) People.firstname, People.middlename, People.lastname, People.peopleid, Emails.email, Phones.phonenumber, Addresses.addressstreet1, Addresses.addressstreet2, Addresses.addresscity, Addresses.addressstate, Addresses.addresszip, Addresses.entry AS addressentryid, Education.degree, Education.entry AS educationentryid, Education.major, Education.school, Education.graduationdate FROM People LEFT OUTER JOIN Education ON People.peopleid = Education.peopleid LEFT OUTER JOIN Emails ON People.peopleid = Emails.peopleid LEFT OUTER JOIN Addresses ON People.peopleid = Addresses.peopleid LEFT OUTER JOIN Phones ON People.peopleid = Phones.peopleid WHERE (People.peopleid = ' + str(peopleid) + ');')
    row = cursor.fetchone()

    resumeurl = 'https://api.icims.com/customers/3786/people/' + str(peopleid) + '/fields/resume/binary'
    resume = requests.get(resumeurl, auth=('SoteraAPI','Tester123'))
    resumecontent = resume.content
    value, filename = cgi.parse_header(resume.headers['content-disposition'])


    fromSQL_Summary = str(row[0]) + " " + str(row[2])
    fromSQL_firstname = str(row[0])
    fromSQL_lastname = str(row[1])
    fromSQL_middlename = str(row[2])
    fromSQL_peopleid = row[3]
    fromSQL_email = str(row[4])
    fromSQL_phonenumber = str(row[5])
    fromSQL_addressstreet1 = str(row[6])
    fromSQL_addressstreet2 = str(row[7])
    fromSQL_addresscity = str(row[8])
    fromSQL_addressstate = { "value" : str(row[9]) }
    fromSQL_addresszip = str(row[10])
    fromSQL_addressentryid = str(row[11])
    fromSQL_degree = str(row[12]) + ' - ' + str(row[14])
    fromSQL_educationentryid = str(row[13])
    fromSQL_major = str(row[14])
    fromSQL_school = str(row[15])
    fromSQL_graduationdate = str(row[16])

    issue_dict = {
        'project': {'key': 'SSES2055'},
        'summary': fromSQL_Summary,
        'issuetype': {'name': 'Candidate'},
        'customfield_10026': fromSQL_firstname,
        'customfield_10027': fromSQL_middlename,
        'customfield_10028': fromSQL_lastname,
        'customfield_10030': fromSQL_peopleid,
        'customfield_10041': fromSQL_email,
        'customfield_10031': fromSQL_phonenumber,
        'customfield_10034': fromSQL_addressstreet1,
        'customfield_10035': fromSQL_addressstreet2,
        'customfield_10036': fromSQL_addresscity,
        'customfield_10038': fromSQL_addressstate,
        'customfield_10039': fromSQL_addresszip,
        'customfield_10033': fromSQL_addressentryid,
        'customfield_10045': fromSQL_degree,
        'customfield_10048': fromSQL_educationentryid,
        'customfield_10046': fromSQL_major,
        'customfield_10047': fromSQL_school,
        'customfield_10044': fromSQL_graduationdate,
    }
    issue_dict2 = dict(issue_dict)

    for k, v in issue_dict2.items():
        if v == 'None':
            del issue_dict[k]

    new_issue = jira.create_issue(fields=issue_dict)
    jira.add_attachment(new_issue, resumecontent, filename['filename'])

#pushtoJIRA(86000)
Example #5
0
class JiraRobot:
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    jira = None

    def connect_to_jira(self,
                        JIRAUsername=None,
                        JIRAPassword=None,
                        options=None):
        """
        Connect to a JIRA server.

            Arguments:
                |  JIRAUsername (string)  	|  (Optional) A JIRA Username you wish to authenticate with, will authorise with anonymous account if left empty      				|
                |  JIRAPassword (string)  	|  (Optional) If a username was specified and a password is not the user will be prompted for password at runtime 					|
                |  options (dictionary) 	|  (Optional) A dictionary of options that the JIRA connection will be initialied with 	                                            |

            This must be called first to be able to do most JIRA actions such as creating a new issue and assigning users.
            When connecting to JIRA you may need to authenticate a user. This can be done by passing in Username and Password as parameters. However, should you wish to not have a sensitive password saved in a file,  an option is available to not pass in a Password and a prompt will appear asking for the JIRA password at runtime.


            'connect to jira' can be called on its own and will default options to:
                '{'rest_api_version': '2', 'verify': True,
                'server': 'http://*****:*****@ssword 						| {'server': http://devjira01'} 	|
        """

        if JIRAUsername is not None and (JIRAPassword is ""
                                         or JIRAPassword is None):
            JIRAPassword = getpass.getpass("\nJIRA Password: "******"\nAuthentication to JIRA unsuccessful. Ensure the user used has sufficient access and that Username and Password were correct\n\n"
                )
                sys.exit(1)

        else:
            try:
                self.jira = JIRA(options=JIRAOptions,
                                 basic_auth=(str(JIRAUsername),
                                             str(JIRAPassword)))
            except:
                sys.__stdout__.write(
                    "\nAuthentication to JIRA unsuccessful. Ensure the user used has sufficient access and that Username and Password were correct\n\n"
                )
                sys.exit(1)

    def create_issue(self, issue_field_dict, assign_current_user=False):
        """
        Creates a new JIRA issue.

            Arguments:
                |  issue_field_dict (string)  			| A dictionary in the form of a string that the user can specify the issues fields and field values 			|
                |  assign_current_user (string/bool)  	| (Optional) A flag to assign the current user to the issue once it is successfully created, defaults to False	|

            Will create a new issue and returns an Issue Key.
            The user will use the issue_field_dict variable to specify the issues field and their respective values. This must be in the form of a string written as a dictionary
                e.g. {'FieldName':'FieldValue'}

            The field value can also be another dictionary (in some field cases this is needed)
                e.g. {'FieldName1':{'key':'value'}, 'FieldName2':FieldValue, 'FieldName3':{'name':'value'}}

            This Create Issue Example page (https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue) is full of useful information in what is required for creating issues, including customfields and issue field value types, it is very important to get the value type right or an error will be thrown.


            Examples:
                |  *Keyword*        	|  *Parameters*   	| 														| 		|
                |  ${issue_field_dict} 	|  {'project':{'key': 'PROJ'}, 'summary':'Create New Issue', 'description':'Creating a new issue', 'issuetype':{'name': 'Bug'}} |    |
                |  connect to jira      |  asimmons         | options= {'http://devjira01'}                         |       |
                |  ${issue}				|  create issue 	|  ${issue_field_dict}									|      	|

                |  connect to jira      |  asimmons         | options= {'http://devjira01'}                         |  		|
                |  ${issue}				|  create issue 	|  ${issue_field_dict}									|  True |
        """
        issue_field_dict = eval(str(issue_field_dict))
        print(issue_field_dict)

        new_issue = self.jira.create_issue(issue_field_dict)
        if assign_current_user is True:
            self.assign_user_to_issue(new_issue, self.jira.current_user())
        return new_issue

    def create_issue_link(self,
                          link_type,
                          inwardissue,
                          outwardissue,
                          comment=None):
        """
        Create a link between two issues.

            Arguments:
                |  link_type (string)  	| The type of link									|
                |  inwardissue (string)  	| The issue to link from  							|
                |  outwardissue (string)  	| The issue to link to 								|
                |  comment (string)  		| (Optional) A comment to add when joining issues	|

            Example:
                |  *Keyword*        	|  *Parameters* | 									| 			|
                |  connect to jira      |  asimmons     | options= {'http://devjira01'}     |  			|
                |  ${issue}				|  create issue |  ${issue_field_dict}				|  True 	|
                |  create issue link	|  relates to   |  ${issue} 						|  PROJ-385	|
        """
        self.jira.create_issue_link(type=link_type,
                                    inwardIssue=str(inwardissue),
                                    outwardIssue=str(outwardissue))

    def assign_user_to_issue(self, issue, JIRAUsername):
        # TODO: Review docs
        """
        Adds a user to a specified issue's watcher list

        Arguments:
            |  issue (string)  		| A JIRA Issue that a user needs to be assigned to, can be an issue ID or Key		|
            |  JIRAUsername (string)  	| A JIRA Username to assign a user to an issue   									|

        Example:
           |  *Keyword*        		|  *Parameters* | 									|
           |  connect to jira       |  asimmons     | options= {'http://devjira01'}     |
           |  ${issue}				|  create issue |  ${issue_field_dict}				|
           |  assign user to issue	|  ${issue}		|  aSample 							|
        """
        self.jira.assign_issue(issue=issue, assignee=JIRAUsername)

    def get_current_user(self):
        """
        Returns the current user used in the Connect to JIRA keyword.
        """
        return self.jira.current_user()

    def add_watcher_to_issue(self, issue, JIRAUsername):
        """
        Adds a user to a specified issue's watcher list.

        Arguments:
            |  issue (string)  		| A JIRA Issue that a watcher needs added to, can be an issue ID or Key		|
            |  JIRAUsername (string)  	| A JIRA Username to add as a watcher to an issue   					|

        Example:
            |  *Keyword*        	|  *Parameters* | 								|		|
            |  connect to jira  |  asimmons     | options= {'http://devjira01'}     | 		|
            |  ${issue}				|  create issue |  ${issue_field_dict}			|  True |
            |  add watcher to issue	|  ${issue}		|  aSample 						| 		|

        """
        self.jira.add_watcher(issue=issue, watcher=JIRAUsername)

    def add_comment_to_issue(self, issue, comment, visibility=None):
        """
        Adds a comment to a specified issue from the current user.

            Arguments:
                |  issue (string)  		| A JIRA Issue that a watcher needs added to, can be an issue ID or Key	|
                |  comment (string)  		| A body of text to add as a comment to an issue   						|
                |  visibility (string)  	| (Optional)															|

            Example:
                |  *Keyword*        	|  *Parameters* | 									|		|
                |  connect to jira      |  asimmons     |  options= {'http://devjira01'}    | 		|
                |  ${issue}				|  create issue |  ${issue_field_dict}				|  True |
                |  add comment to issue	|  ${issue}		|  Starting work on this issue		| 		|
        """
        self.jira.add_comment(issue=issue, body=comment)

    def add_attachment_to_issue(self, issue, attachment, filename=None):
        """
        Uploads and attaches a file a specified issue. (Note: include the file extention when using the 'filename' option or this will change the file type.)

        Arguments:
            |   issue (string)  	| A JIRA Issue that a watcher needs added to, can be an issue ID or Key		|
            |   attachment (string) | A string pointing to a file location to upload and attach to the issue	|
            |   filename (string)  	| (Optional) A string to rename the file to upon attaching to the issue  	|

        Example:
            |  *Keyword*        		|  *Parameters* | 							         |						|
            |  connect to jira          |  asimmons     | options= {'http://devjira01'}      | 						|
            |  ${issue}					|  create issue |  ${issue_field_dict}	             |  True 			 	|
            |  add attchment to issue	|  ${issue}		|  ./logfile.text			         |  LogInformation.txt	|
        """
        self.jira.add_attachment(issue=issue,
                                 attachment=attachment,
                                 filename=filename)
Example #6
0
from jira.client import JIRA

options = {

'server': 'our_server'

}

jira = JIRA(options=options,basic_auth=('u_name', 'pswrd'))

issue = jira.issue('issue_id')

file=open('/Desktop/test.xlsx','rb')

attachement_object=jira.add_attachment(issue,file)

file.close() 
def hardware_ticket(jira_server, jira_auth, ticket):
    settings = get_config()
    jira_options = {"server": jira_server + settings["General"]["path_suffix"]}
    hardware_dict = settings.get("hardware")
    jira = JIRA(options=jira_options, basic_auth=jira_auth)

    # hardware stuff. We can get them from servermon
    serial = ticket.get("serial")
    rackposition = ticket.get("rack_position")
    hostname = ticket.get("hostname")

    if hardware_dict["DescriptionFooter"]:
        with codecs.open(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), hardware_dict["DescriptionFooter"]),
            mode="r",
            encoding="utf-8",
        ) as f:
            template = Template(f.read())
    context = Context({"ticket": ticket})
    description = template.render(context)
    issue_dict = {
        "project": {"key": hardware_dict["Project"]},
        "summary": hardware_dict["Summary"] + " (" + hostname + " - S/N " + serial + " - " + rackposition + ")",
        "description": description,
        "labels": [settings["General"]["label"]],
        "issuetype": {"name": hardware_dict["IssueType"]},
        settings["CustomFields"]["GroupAssignee"]: [{"name": hardware_dict["GroupAssignee"]}],
        settings["CustomFields"]["S/N"]: serial,
    }
    parent_ticket = jira.create_issue(fields=issue_dict)  # Create parent issue
    if ticket.get("attachment"):
        with open(ticket.get("attachment").path, "r") as f:
            attachment = f.read()
        jira.add_attachment(parent_ticket, attachment)
    list_issues = []
    list_issues.append(parent_ticket)

    if settings.get("hardware").get("SubTasks"):  # Check if SubTasks exist and parse them if so
        first_item = True
        for item in settings.get("hardware").get("SubTasks"):
            issue_dict = {
                "parent": {"id": parent_ticket.key},
                "project": {"key": hardware_dict["Project"]},
                "summary": item["Summary"],
                "description": item["Description"],
                "labels": [settings["General"]["label"]],
                "issuetype": {"name": item["IssueType"]},
                settings["CustomFields"]["GroupAssignee"]: [{"name": item["GroupAssignee"]}],
                settings["CustomFields"]["S/N"]: serial,
            }

            child_ticket = jira.create_issue(fields=issue_dict)  # Create child issue
            list_issues.append(child_ticket)
            if item.get("BlockedByPrevious", False) and not first_item:
                jira.create_issue_link(
                    type="Blocks",
                    inwardIssue=list_issues[len(list_issues) - 2].key,
                    outwardIssue=list_issues[len(list_issues) - 1].key,
                )
            first_item = False
    return parent_ticket.key
Example #8
0
def main():
    settings = options()
    rally = pyral.Rally(settings["rally"]["server"],
                        settings["rally"]["username"],
                        settings["rally"]["password"],
                        project=settings["rally"]["project"])

    import_into_jira = settings["import_into_jira"]

    jira = None
    if import_into_jira:
        jira = JIRA(
            server=settings["jira"]["server"],
            basic_auth=(settings["jira"]["username"], settings["jira"]["password"])
        )

    stories = [rally.get(kind_of_story(story)[0], query='FormattedID = "{0}"'.format(story)).next() for story in settings["rally"]["stories"]]

    # Weep for me...
    for story in stories:
        if import_into_jira:
            issue = jira.create_issue(
                project={"key": settings["jira"]["project"]},
                summary=story.Name,
                description=html2confluence(story.Description),
                reporter={"name": settings["jira"]["on_behalf_of"]},
                issuetype={"name": kind_of_story(story.FormattedID)[1]}
            )
            header = "{0} -> {1}: {2}".format(story.FormattedID, issue.key, story.Name)
        else:
            header = "{0}: {1}".format(story.FormattedID, story.Name)

        print(header)

        names = []
        for attachment in story.Attachments:
            names.append(attachment.Name)

            if import_into_jira:
                tmp = tempfile.mkstemp()[1]

                with open(tmp, "wb") as fh:
                    fh.write(base64.b64decode(attachment.Content.Content))
                    fh.close()

                jira.add_attachment(issue.key, tmp, attachment.Name)
                os.remove(tmp)

        print("\tAttachments: " + ", ".join(names))

        print("\tDiscussion:")
        for ConversationPost in story.Discussion:
            print("\t\t{0}:".format(ConversationPost.User.Name))
            print("\n".join(["\t\t" + line for line in html2confluence(ConversationPost.Text).split("\n")]))

            if import_into_jira:
                jira.add_comment(issue=issue.key,
                                 body=html2confluence(
                                     "On behalf of {0}:<br/><br/>{1}".format(ConversationPost.User.Name,
                                                                             ConversationPost.Text)))

        # ...a little more
        for rally_task in story.Tasks:
            jira_task = None
            if import_into_jira:
                jira_task = jira.create_issue(
                    project={"key": settings["jira"]["project"]},
                    parent={"key": issue.key},
                    summary=rally_task.Name,
                    description=html2confluence(rally_task.Description),
                    reporter={"name": settings["jira"]["on_behalf_of"]},
                    issuetype={"id": "5"}
                )
                header = "\t{0} -> {1}: {2}".format(rally_task.FormattedID, jira_task.key, rally_task.Name)
            else:
                header = "\t{0}: {1}".format(rally_task.FormattedID, rally_task.Name)
            
            print(header)

            names = []
            for attachment in rally_task.Attachments:
                names.append(attachment.Name)

                if import_into_jira:
                    tmp = tempfile.mkstemp()[1]

                    with open(tmp, "wb") as fh:
                        fh.write(base64.b64decode(attachment.Content.Content))
                        fh.close()

                    jira.add_attachment(jira_task.key, tmp, attachment.Name)
                    os.remove(tmp)

            print("\t\tAttachments: " + ", ".join(names))

            print("\t\tDiscussion:")
            for ConversationPost in rally_task.Discussion:
                print("\t\t\t{0}:".format(ConversationPost.User.Name))
                print("\n".join(["\t\t\t" + line for line in html2confluence(ConversationPost.Text).split("\n")]))

                if import_into_jira:
                    jira.add_comment(issue=jira_task.key,
                                     body=html2confluence(
                                         "On behalf of {0}:<br/><br/>{1}".format(ConversationPost.User.Name,
                                                                                 ConversationPost.Text)))
Example #9
0
class jiralib:
	"""
	Library for creating and updating the issue on adtran jira database.
	"""
	def __init__(self):

		# password = os.environ.get('JIRA_PSWD')
		options = {
		    'server': 'https://jira.abcd.com'}
		self.jira = JIRA(basic_auth=('user', 'password'), options = options)

	def create_jira(self, issue_dict = None):
		'''
		This method creates new issue based on the given jira fields. Jira fields may vary depending on the project.

	    *Parameters:* issue_dict which should contian mandatory fields and their values in the form of dictionary. This dictionary will be used to create an issue.

	    *Return:* It returns the jira id of new issue which was created

		'''
		if issue_dict is not None:
			try:
				new_issue = self.jira.create_issue(fields=issue_dict)
				print('Issue created: ',  new_issue)
				return new_issue
			except Exception as e:
				print(e)

	def update_jira(self, jira_id, summary=None, description=None, attachment=None, comment = None):
		'''
		This method updates the issue which is limited to few fields of jira database like attachements, summary,descrption and comment.

		*Parameters:* 
	    | *Key*               | *Value*                                         |
	    | *jira_id*           | jira ID of the issue that needs to be updated   |
	    | *summary*           | New summary of the issue                        |
	    | *description*       | New description of the issue 			        |
	    | *Attachment*        | file/file path that needs to attached 			|
	    | *comment*           | Add comment										|

	    *Return:* None

		'''

		try:
			issue = self.jira.issue(jira_id)
			if attachment:
				self.jira.add_attachment(issue=issue, attachment=attachment)
			if summary:
				issue.update(summary=summary)
			if description:
				issue.update(description=description)
			if comment:
				issue.update(comment = comment)
			print('jira updated successfuly')
		except Exception as e:
			print(e)

	def close_jira(self, jira_id, comment):
		'''
		This method closes the issue based on the jira_id and its current status. If the issue is not allowed to close , then it will print an error.

				*Parameters:* 
	    | *Key*               | *Value*                                     |
	    | *jira_id*           | jira ID of the issue                        |
	    | *comment*           | comment that needs to added during updation |

	    *Return:* None

		'''

		issue = self.jira.issue(jira_id)
		transitions = self.jira.transitions(issue)
		list_transitions = list()
		for each in transitions:
			list_transitions.append(each['name'])
		print(list_transitions)
		if 'Close Issue' in list_transitions:
			try:
				self.jira.transition_issue(issue, 'Close Issue', comment = comment)
				print('Closed jira ' + jira_id + ' successfully')
			except Exception as e:
				print(e)
		else:
			print('Error: Unable to close the jira ' + jira_id)

	def query_jira(self, jql_str):
		'''
		This method returns the list of issues which are queried through jql

		*Parameters:* jql query in the form a string

	    *Return:* list of jira IDs of the issues which are queried through jql

		'''

		return self.jira.search_issues(jql_str)

	def get_description(self, jira_id):
		'''
		This method returns the description of the issue of jira ID

		*Parameters:* jira ID of the issue

	    *Return:* Description of the issue in string format

		'''

		return self.jira.issue(jira_id).fields.description

	def close_all_jira(self, jql_str):
		'''
		This method closes the list of issues which are queried through jql

		*Parameters:* jql query in the form a string

	    *Return:* None

		'''

		issues = self.jira.search_issues(jql_str)

		if issues:
			for issue in issues:
				close_jira(issue)

	def label_jira(self, jira_id, label = None):
		'''
		This method does label the issue. Currently "CN" project is not allowing to label affer creation of jira
		
		*Parameters:* 
	    | *Key*               | *Value*                                          |
	    | *jira_id*           | jira ID of the issue that needs to be labelled   |
	    | *label*             | label -> can be a single label or list of labels that can be appended to jira  |

	    *Return:* None

		Ex: label_jira('CN-13531', label = ['ONT_CI_HYD', 'BBB', '424'])

		'''
		if label:
			try:
				issue = self.jira.issue(jira_id)
				issue.update(fields={"labels": label})
				print('jira labelled successfuly')
			except Exception as e:
				print(e)
Example #10
0
# set the filename in the spreadsheet
print issue.fields.attachment
sqls = 0
for i in issue.fields.attachment:
    print i
    print i.get()
    if str(i).endswith('.txt'):
        sqls += 1
if sqls == 1:
    print "1 found"
else:
    print "Not 1 found"
###################3

jira.add_attachment(
    issue,
    "C:\\Users\\shsrinivasan\\Desktop\\Micore\\Python\\test\\testERR.sql")

#jira.assign_issue(issue,'noc_change_manager')
#print issue.fields.assignee

#noc_change_manager
#sqadepartment

# Pertinent data fields:
#   ticket number       i.key
#   description         i.fields.summary
#   assignee            i.fields.assignee
#   str(issue.fields.status)
#jira.add_comment(issue,'Deployed to production, please see attached .log file')
#jira.add_comment(issue,'Run with errors, please see attached .log file')
	if options.type == "notification":
		summary = "AlfrescoCustom version " + options.version + " deployed to " + instance + " SugarCRM"
		description = "AlfrescoCustom version " + options.version + " has been uploaded and deployed to " + instance + " SugarCRM.  This package resolves the linked issues.  Thanks!"

	if options.type == "request":
		summary = "Please deploy AlfrescoCustom version " + options.version + " to " + instance + " SugarCRM"
		description = "Hi ITS - Please could the attached AlfrescoCustom package (version " + options.version + ") be uploaded and installed on " + instance + " SugarCRM, followed by a 'Quick Repair and Rebuild' from the Admin -> Repair menu.  This package resolves the linked issues.  Thanks!"

	issue_dict = {
	    'project': {'key': 'ITS'},
	    'summary': summary,
	    'description': description,
	    'issuetype': {'name': 'Change request'},
	    'components': [{'name': 'SugarCRM'}],
	}

	print "Creating ticket..."
	new_issue = jira.create_issue(fields=issue_dict)

	#This bit is specific to my machine, screw you
	os.chdir('/web/sites/_releases')
	file = open('sugarcrm-' + options.version + ".zip")

	print "Attaching package..."
	attachment_object = jira.add_attachment(new_issue, file)

	if options.type == "notification":
		#Immediately resolve tickets we're creating just for ITS logs
		jira.transition_issue(new_issue,11)

	print "Deployment ticket " + new_issue.key + " has been created successfully."
Example #12
0
class JiraRobot:
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    jira = None

    def connect_to_jira(self, JIRAUsername=None,
                        JIRAPassword=None, options=None):
        """
        Connect to a JIRA server.

            Arguments:
                |  JIRAUsername (string)  	|  (Optional) A JIRA Username you wish to authenticate with, will authorise with anonymous account if left empty      				|
                |  JIRAPassword (string)  	|  (Optional) If a username was specified and a password is not the user will be prompted for password at runtime 					|
                |  options (dictionary) 	|  (Optional) A dictionary of options that the JIRA connection will be initialied with 	                                            |

            This must be called first to be able to do most JIRA actions such as creating a new issue and assigning users.
            When connecting to JIRA you may need to authenticate a user. This can be done by passing in Username and Password as parameters. However, should you wish to not have a sensitive password saved in a file,  an option is available to not pass in a Password and a prompt will appear asking for the JIRA password at runtime.


            'connect to jira' can be called on its own and will default options to:
                '{'rest_api_version': '2', 'verify': True,
                'server': 'http://*****:*****@ssword 						| {'server': http://devjira01'} 	|
        """

        if JIRAUsername is not None and (JIRAPassword is "" or JIRAPassword is None):
            JIRAPassword = getpass.getpass("\nJIRA Password: "******"\nAuthentication to JIRA unsuccessful. Ensure the user used has sufficient access and that Username and Password were correct\n\n")
                sys.exit(1)

        else:
            try:
                self.jira = JIRA(options=JIRAOptions, basic_auth=(str(JIRAUsername),
                                 str(JIRAPassword)))
            except:
                sys.__stdout__.write("\nAuthentication to JIRA unsuccessful. Ensure the user used has sufficient access and that Username and Password were correct\n\n")
                sys.exit(1)

    def create_issue(self, issue_field_dict, assign_current_user=False):
        """
        Creates a new JIRA issue.

            Arguments:
                |  issue_field_dict (string)  			| A dictionary in the form of a string that the user can specify the issues fields and field values 			|
                |  assign_current_user (string/bool)  	| (Optional) A flag to assign the current user to the issue once it is successfully created, defaults to False	|

            Will create a new issue and returns an Issue Key.
            The user will use the issue_field_dict variable to specify the issues field and their respective values. This must be in the form of a string written as a dictionary
                e.g. {'FieldName':'FieldValue'}

            The field value can also be another dictionary (in some field cases this is needed)
                e.g. {'FieldName1':{'key':'value'}, 'FieldName2':FieldValue, 'FieldName3':{'name':'value'}}

            This Create Issue Example page (https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue) is full of useful information in what is required for creating issues, including customfields and issue field value types, it is very important to get the value type right or an error will be thrown.


            Examples:
                |  *Keyword*        	|  *Parameters*   	| 														| 		|
                |  ${issue_field_dict} 	|  {'project':{'key': 'PROJ'}, 'summary':'Create New Issue', 'description':'Creating a new issue', 'issuetype':{'name': 'Bug'}} |    |
                |  connect to jira      |  asimmons         | options= {'http://devjira01'}                         |       |
                |  ${issue}				|  create issue 	|  ${issue_field_dict}									|      	|

                |  connect to jira      |  asimmons         | options= {'http://devjira01'}                         |  		|
                |  ${issue}				|  create issue 	|  ${issue_field_dict}									|  True |
        """
        issue_field_dict = eval(str(issue_field_dict))
        print issue_field_dict

        new_issue = self.jira.create_issue(issue_field_dict)
        if assign_current_user is True:
            self.assign_user_to_issue(new_issue, self.jira.current_user())
        return new_issue

    def create_issue_link(self, link_type, inwardissue,
                          outwardissue, comment=None):
        """
        Create a link between two issues.

            Arguments:
                |  link_type (string)  	| The type of link									|
                |  inwardissue (string)  	| The issue to link from  							|
                |  outwardissue (string)  	| The issue to link to 								|
                |  comment (string)  		| (Optional) A comment to add when joining issues	|

            Example:
                |  *Keyword*        	|  *Parameters* | 									| 			|
                |  connect to jira      |  asimmons     | options= {'http://devjira01'}     |  			|
                |  ${issue}				|  create issue |  ${issue_field_dict}				|  True 	|
                |  create issue link	|  relates to   |  ${issue} 						|  PROJ-385	|
        """
        self.jira.create_issue_link(type=link_type,
                                    inwardIssue=str(inwardissue),
                                    outwardIssue=str(outwardissue))

    def assign_user_to_issue(self, issue, JIRAUsername):
    # TODO: Review docs
        """
        Adds a user to a specified issue's watcher list

        Arguments:
            |  issue (string)  		| A JIRA Issue that a user needs to be assigned to, can be an issue ID or Key		|
            |  JIRAUsername (string)  	| A JIRA Username to assign a user to an issue   									|

        Example:
           |  *Keyword*        		|  *Parameters* | 									|
           |  connect to jira       |  asimmons     | options= {'http://devjira01'}     |
           |  ${issue}				|  create issue |  ${issue_field_dict}				|
           |  assign user to issue	|  ${issue}		|  aSample 							|
        """
        self.jira.assign_issue(issue=issue, assignee=JIRAUsername)

    def get_current_user(self):
        """
        Returns the current user used in the Connect to JIRA keyword.
        """
        return self.jira.current_user()

    def add_watcher_to_issue(self, issue, JIRAUsername):
        """
        Adds a user to a specified issue's watcher list.

        Arguments:
            |  issue (string)  		| A JIRA Issue that a watcher needs added to, can be an issue ID or Key		|
            |  JIRAUsername (string)  	| A JIRA Username to add as a watcher to an issue   					|

        Example:
            |  *Keyword*        	|  *Parameters* | 								|		|
            |  connect to jira  |  asimmons     | options= {'http://devjira01'}     | 		|
            |  ${issue}				|  create issue |  ${issue_field_dict}			|  True |
            |  add watcher to issue	|  ${issue}		|  aSample 						| 		|

        """
        self.jira.add_watcher(issue=issue, watcher=JIRAUsername)

    def add_comment_to_issue(self, issue, comment, visibility=None):
        """
        Adds a comment to a specified issue from the current user.

            Arguments:
                |  issue (string)  		| A JIRA Issue that a watcher needs added to, can be an issue ID or Key	|
                |  comment (string)  		| A body of text to add as a comment to an issue   						|
                |  visibility (string)  	| (Optional)															|

            Example:
                |  *Keyword*        	|  *Parameters* | 									|		|
                |  connect to jira      |  asimmons     |  options= {'http://devjira01'}    | 		|
                |  ${issue}				|  create issue |  ${issue_field_dict}				|  True |
                |  add comment to issue	|  ${issue}		|  Starting work on this issue		| 		|
        """
        self.jira.add_comment(issue=issue, body=comment)

    def add_attachment_to_issue(self, issue, attachment, filename=None):
        """
        Uploads and attaches a file a specified issue. (Note: include the file extention when using the 'filename' option or this will change the file type.)

        Arguments:
            |   issue (string)  	| A JIRA Issue that a watcher needs added to, can be an issue ID or Key		|
            |   attachment (string) | A string pointing to a file location to upload and attach to the issue	|
            |   filename (string)  	| (Optional) A string to rename the file to upon attaching to the issue  	|

        Example:
            |  *Keyword*        		|  *Parameters* | 							         |						|
            |  connect to jira          |  asimmons     | options= {'http://devjira01'}      | 						|
            |  ${issue}					|  create issue |  ${issue_field_dict}	             |  True 			 	|
            |  add attchment to issue	|  ${issue}		|  ./logfile.text			         |  LogInformation.txt	|
        """
        self.jira.add_attachment(issue=issue, attachment=attachment,
                                 filename=filename)
Example #13
0
class Jira(Config):
    def __init__(self, **kwargs):

        super(Jira, self).__init__()
        self.description = None
        self.issue_aus = None
        self.issue_us = None
        self.issue_uk = None
        self.issue_es = None
        self.issue_de = None
        self.issue_fr = None
        self.issue_apac = None
        self.issue_mea = None

        self.create_aus = None
        self.create_us = None
        self.create_apac = None
        self.create_de = None
        self.create_mea = None
        self.create_fr = None
        self.create_es = None
        self.create_uk = None

        self.options = {'server': self.section_value[4], 'verify': False}

        self.client = None

        if len(kwargs) != 2:
            raise JiraException(
                'In order to use this class you need to specify a user and a password as keyword arguments!'
            )
        else:
            if 'username' in kwargs.keys():
                self.username = kwargs['username']
            else:
                raise JiraException(
                    'You need to specify a username as keyword argument!')
            if 'password' in kwargs.keys():
                self.password = kwargs['password']
            else:
                raise JiraException(
                    'You need to specify a password as keyword argument!')

            try:
                self.client = JIRA(self.options,
                                   basic_auth=(self.username, self.password))
            except Exception:
                raise JiraException(
                    'Could not connect to the API, invalid username or password!'
                )

    def get_projects(self, raw=False):

        projects = []
        for project in self.client.projects():
            if raw:
                projects.append(project)
            else:
                projects.append({
                    'Name': str(project.key),
                    'Description': str(project.name)
                })
        return projects

    @staticmethod
    def date_create():
        my_date = datetime.datetime.now().date()
        return my_date

    @staticmethod
    def sixth_day():
        now = datetime.datetime.now().date()
        start_month = datetime.datetime(now.year, now.month, 1)
        date_on_next_month = start_month + datetime.timedelta(35)
        start_next_month = datetime.datetime(date_on_next_month.year,
                                             date_on_next_month.month, 1)
        last_day_month = start_next_month - datetime.timedelta(1)
        sixth_day_month = last_day_month.date() + timedelta(6)
        return sixth_day_month

    def issue_description(self):

        description = "Hi Team" + "\n" + "Hope you are doing well" + "\n" + \
                      "Kindly confirm the current advertisers and accounts from the PDF attached." + "\n" + \
                      "Making sure that for each platform the correct account id, advertiser or account name get" + \
                      "\n" + "included in the NDP data for ALL channels." + "\n" + \
                      "Note: Do let us know if there is any account that needs to be removed." + "\n" + \
                      "Please make sure that the media plan is uploaded on the NeoSageCentral SharePoint Folder." \
                      + "\n" \
                      + "https://insidemedia.sharepoint.com/sites/neosagecentral/Shared%20Documents/" \
                        "Forms/AllItems.aspx?id=%2Fsites%2Fneosagecentral%2FShared%20Documents%2FFY18%20Media%" \
                        "20Plans%2FQ4%20Media%20Plans" + "\n" + "Thanks," + "\n" + "Nikita"

        self.description = description

    def de(self):
        watch = [
            'Dharmendra.mishra', 'ankit.singhal', 'ubaidullah.arifshah',
            'ayush.sharma', 'nikita.borah', 'deepak.garg', 'mohammad.dilshad',
            'jennifer.marquez', 'ajaysingh.yadav', 'Ing-y.Chenn',
            'anastasia.lanina', 'thilo.babel1'
        ]
        assignees = 'anastasia.lanina'
        attachment = [self.section_value[3] + 'DE.xlsx']

        try:
            self.issue_de = {
                'project': {
                    'key': 'MOS'
                },
                'issuetype': {
                    'name': 'Reporting'
                },
                'summary':
                'NDP Data Audit {} DE'.format(
                    Jira.date_create().strftime('%B')),
                'description':
                self.description,
                'customfield_10038': {
                    'value': 'DE'
                },
                'customfield_10052': {
                    'value': 'Ad hoc'
                },
                'customfield_10053': {
                    'value': 'Monthly'
                },
                "assignee": {
                    "name": assignees
                },
                'duedate':
                str(Jira.sixth_day())
            }

            create_de = self.client.create_issue(fields=self.issue_de,
                                                 prefetch=True)
            self.create_de = create_de

            for j in attachment:
                self.client.add_attachment(self.create_de.id, j)

            for i in watch:
                self.client.add_watcher(self.create_de.id, i)

        except JIRAError as e:
            logger.error(str(e))
            pass

    def fr(self):
        watch = [
            'Dharmendra.mishra', 'ankit.singhal', 'ubaidullah.arifshah',
            'ayush.sharma', 'nikita.borah', 'deepak.garg', 'mohammad.dilshad',
            'jennifer.marquez', 'ajaysingh.yadav', 'Maxime.Sarrazin',
            'philippine.gurs', 'manon.mercier'
        ]
        assignees = 'manon.mercier'
        attachment = [self.section_value[3] + 'FR.xlsx']

        try:
            self.issue_fr = {
                'project': {
                    'key': 'MOS'
                },
                'issuetype': {
                    'name': 'Reporting'
                },
                'summary':
                'NDP Data Audit {} FR'.format(
                    Jira.date_create().strftime('%B')),
                'description':
                self.description,
                'customfield_10038': {
                    'value': 'FR'
                },
                'customfield_10052': {
                    'value': 'Ad hoc'
                },
                'customfield_10053': {
                    'value': 'Monthly'
                },
                "assignee": {
                    "name": assignees
                },
                'duedate':
                str(Jira.sixth_day())
            }

            self.create_fr = self.client.create_issue(fields=self.issue_fr,
                                                      prefetch=True)

            for j in attachment:
                self.client.add_attachment(self.create_fr.id, j)

            for i in watch:
                self.client.add_watcher(self.create_fr.id, i)

        except JIRAError as e:
            logger.error(str(e))
            pass

    def es(self):
        watch = [
            'Dharmendra.mishra', 'ankit.singhal', 'ubaidullah.arifshah',
            'ayush.sharma', 'nikita.borah', 'deepak.garg', 'mohammad.dilshad',
            'jennifer.marquez', 'ajaysingh.yadav', 'silvia.orofino',
            'carmen.candela', 'raquel.hernandez'
        ]
        assignees = 'silvia.orofino'
        attachment = [
            self.section_value[3] + 'ES.xlsx',
            self.section_value[3] + 'PT.xlsx'
        ]

        try:
            self.issue_es = {
                'project': {
                    'key': 'MOS'
                },
                'issuetype': {
                    'name': 'Reporting'
                },
                'summary':
                'NDP Data Audit {} ES'.format(
                    Jira.date_create().strftime('%B')),
                'description':
                self.description,
                'customfield_10038': {
                    'value': 'ES'
                },
                'customfield_10052': {
                    'value': 'Ad hoc'
                },
                'customfield_10053': {
                    'value': 'Monthly'
                },
                "assignee": {
                    "name": assignees
                },
                'duedate':
                str(Jira.sixth_day())
            }

            self.create_es = self.client.create_issue(fields=self.issue_es,
                                                      prefetch=True)

            for j in attachment:
                self.client.add_attachment(self.create_es.id, j)

            for i in watch:
                self.client.add_watcher(self.create_es.id, i)

        except JIRAError as e:
            logger.error(str(e))
            pass

    def us(self):
        watch = [
            'Dharmendra.mishra', 'ankit.singhal', 'ubaidullah.arifshah',
            'ayush.sharma', 'nikita.borah', 'deepak.garg', 'mohammad.dilshad',
            'jennifer.marquez', 'ajaysingh.yadav', 'vanessa.ezeta'
        ]
        assignees = 'vanessa.ezeta'
        attachment = [
            self.section_value[3] + 'CA.xlsx',
            self.section_value[3] + 'US.xlsx',
            self.section_value[3] + 'US & CA.xlsx'
        ]

        try:
            self.issue_us = {
                'project': {
                    'key': 'MOS'
                },
                'issuetype': {
                    'name': 'Reporting'
                },
                'summary':
                'NDP Data Audit {} US'.format(
                    Jira.date_create().strftime('%B')),
                'description':
                self.description,
                'customfield_10038': {
                    'value': 'US'
                },
                'customfield_10052': {
                    'value': 'Ad hoc'
                },
                'customfield_10053': {
                    'value': 'Monthly'
                },
                "assignee": {
                    "name": assignees
                },
                'duedate':
                str(Jira.sixth_day())
            }

            self.create_us = self.client.create_issue(fields=self.issue_us,
                                                      prefetch=True)

            for j in attachment:
                self.client.add_attachment(self.create_us.id, j)

            for i in watch:
                self.client.add_watcher(self.create_us.id, i)

        except JIRAError as e:
            logger.error(str(e))
            pass

    def uk(self):
        watch = [
            'Dharmendra.mishra', 'ankit.singhal', 'ubaidullah.arifshah',
            'ayush.sharma', 'nikita.borah', 'deepak.garg', 'mohammad.dilshad',
            'jennifer.marquez', 'ajaysingh.yadav', 'aman.mastana',
            'manon.leymat', 'james.hill', 'alex.ooi', 'sophie.corcinos',
            'mireia.nadal', 'nick.gardiner'
        ]
        assignees = 'manon.leymat'
        attachment = [
            self.section_value[3] + 'UK.xlsx',
            self.section_value[3] + 'IE.xlsx'
        ]

        try:
            self.issue_uk = {
                'project': {
                    'key': 'MOS'
                },
                'issuetype': {
                    'name': 'Reporting'
                },
                'summary':
                'NDP Data Audit {} UK'.format(
                    Jira.date_create().strftime('%B')),
                'description':
                self.description,
                'customfield_10038': {
                    'value': 'UK'
                },
                'customfield_10052': {
                    'value': 'Ad hoc'
                },
                'customfield_10053': {
                    'value': 'Monthly'
                },
                "assignee": {
                    "name": assignees
                },
                'duedate':
                str(Jira.sixth_day())
            }

            self.create_uk = self.client.create_issue(fields=self.issue_uk,
                                                      prefetch=True)

            for j in attachment:
                self.client.add_attachment(self.create_uk.id, j)

            for i in watch:
                self.client.add_watcher(self.create_uk.id, i)

        except JIRAError as e:
            logger.error(str(e))
            pass

    # Done
    def mea(self):
        watch = [
            'Dharmendra.mishra', 'ankit.singhal', 'ubaidullah.arifshah',
            'ayush.sharma', 'nikita.borah', 'deepak.garg', 'mohammad.dilshad',
            'jennifer.marquez', 'ajaysingh.yadav', 'marthinus.matthee',
            'Brunette Nkuna'
        ]
        assignees = 'gareth.macgregor'
        attachment = [self.section_value[3] + 'ZA.xlsx']

        try:
            self.issue_mea = {
                'project': {
                    'key': 'MOS'
                },
                'issuetype': {
                    'name': 'Reporting'
                },
                'summary':
                'NDP Data Audit {} MEA'.format(
                    Jira.date_create().strftime('%B')),
                'description':
                self.description,
                'customfield_10038': {
                    'value': 'MEA'
                },
                'customfield_10052': {
                    'value': 'Ad hoc'
                },
                'customfield_10053': {
                    'value': 'Monthly'
                },
                "assignee": {
                    "name": assignees
                },
                'duedate':
                str(Jira.sixth_day())
            }

            self.create_mea = self.client.create_issue(fields=self.issue_mea,
                                                       prefetch=True)

            for j in attachment:
                self.client.add_attachment(self.create_mea.id, j)

            for i in watch:
                self.client.add_watcher(self.create_mea.id, i)

        except JIRAError as e:
            logger.error(str(e))
            pass

    def aus(self):
        watch = [
            'Dharmendra.mishra', 'ankit.singhal', 'ubaidullah.arifshah',
            'ayush.sharma', 'nikita.borah', 'deepak.garg', 'mohammad.dilshad',
            'jennifer.marquez', 'ajaysingh.yadav', 'jon.windred',
            'corinne.hewlett'
        ]
        assignees = 'corinne.hewlett'
        attachment = [self.section_value[3] + 'AUS.xlsx']

        try:
            self.issue_aus = {
                'project': {
                    'key': 'MOS'
                },
                'issuetype': {
                    'name': 'Reporting'
                },
                'summary':
                'NDP Data Audit {} AUS'.format(
                    Jira.date_create().strftime('%B')),
                'description':
                self.description,
                'customfield_10038': {
                    'value': 'AUS'
                },
                'customfield_10052': {
                    'value': 'Ad hoc'
                },
                'customfield_10053': {
                    'value': 'Monthly'
                },
                "assignee": {
                    "name": assignees
                },
                'duedate':
                str(Jira.sixth_day())
            }

            self.create_aus = self.client.create_issue(fields=self.issue_aus,
                                                       prefetch=True)

            for j in attachment:
                self.client.add_attachment(self.create_aus.id, j)

            for i in watch:
                self.client.add_watcher(self.create_aus.id, i)

        except JIRAError as e:
            logger.error(str(e))
            pass

    def apac(self):
        watch = [
            'Dharmendra.mishra', 'ankit.singhal', 'ubaidullah.arifshah',
            'ayush.sharma', 'nikita.borah', 'deepak.garg', 'mohammad.dilshad',
            'jennifer.marquez', 'ajaysingh.yadav', 'ravi.chettiar'
        ]
        assignees = 'ravi.chettiar'
        attachment = [
            self.section_value[3] + 'HK.xlsx',
            self.section_value[3] + 'ID.xlsx',
            self.section_value[3] + 'MY.xlsx',
            self.section_value[3] + 'SG.xlsx',
            self.section_value[3] + 'TH.xlsx'
        ]

        try:
            self.issue_apac = {
                'project': {
                    'key': 'MOS'
                },
                'issuetype': {
                    'name': 'Reporting'
                },
                'summary':
                'NDP Data Audit {} APAC'.format(
                    Jira.date_create().strftime('%B')),
                'description':
                self.description,
                'customfield_10038': {
                    'value': 'APAC'
                },
                'customfield_10052': {
                    'value': 'Ad hoc'
                },
                'customfield_10053': {
                    'value': 'Monthly'
                },
                "assignee": {
                    "name": assignees
                },
                'duedate':
                str(Jira.sixth_day())
            }

            self.create_apac = self.client.create_issue(fields=self.issue_apac,
                                                        prefetch=True)

            for j in attachment:
                self.client.add_attachment(self.create_apac.id, j)

            for i in watch:
                self.client.add_watcher(self.create_apac.id, i)

        except JIRAError as e:
            logger.error(str(e))
            pass

    def main(self):
        self.get_projects()
        logger.info('reading issue Description' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.issue_description()
        logger.info('Done!reading issue Description' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for DE' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.de()
        logger.info('Done!creating issue for DE' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for FR' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.fr()
        logger.info('Done!creating issue for FR' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for ES' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.es()
        logger.info('Done!creating issue for ES' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for US' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.us()
        logger.info('Done!creating issue for US' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for UK' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.uk()
        logger.info('Done!creating issue for UK' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for MEA' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.mea()
        logger.info('Done!creating issue for MEA' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for AUS' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.aus()
        logger.info('Done!creating issue for AUS' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for APAC' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.apac()
        logger.info('Done!creating issue for APAC' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
Example #14
0
class Jira(object):
    def __init__(self, **kwargs):

        self.description = None
        self.issue_aus = None
        self.issue_us = None
        self.issue_uk = None
        self.issue_es = None
        self.issue_de = None
        self.issue_fr = None
        self.issue_apac = None
        self.issue_mea = None

        self.create_aus = None
        self.create_us = None
        self.create_apac = None
        self.create_de = None
        self.create_mea = None
        self.create_fr = None
        self.create_es = None
        self.create_uk = None

        self.options = {
            'server': 'https://neomediaworld.atlassian.net',
            'verify': False
        }

        self.client = None

        if len(kwargs) != 2:
            raise JiraException(
                'In order to use this class you need to specify a user and a password as keyword arguments!'
            )
        else:
            if 'username' in kwargs.keys():
                self.username = kwargs['username']
            else:
                raise JiraException(
                    'You need to specify a username as keyword argument!')
            if 'password' in kwargs.keys():
                self.password = kwargs['password']
            else:
                raise JiraException(
                    'You need to specify a password as keyword argument!')

            try:
                self.client = JIRA(self.options,
                                   basic_auth=(self.username, self.password))
            except Exception:
                raise JiraException(
                    'Could not connect to the API, invalid username or password!'
                )

    def get_projects(self, raw=False):

        projects = []
        for project in self.client.projects():
            if raw:
                projects.append(project)
            else:
                projects.append({
                    'Name': str(project.key),
                    'Description': str(project.name)
                })
        return projects

    @staticmethod
    def date_create():
        my_date = datetime.datetime.now().date()
        return my_date

    @staticmethod
    def sixth_day():
        now = datetime.datetime.now().date()
        start_month = datetime.datetime(now.year, now.month, 1)
        date_on_next_month = start_month + datetime.timedelta(35)
        start_next_month = datetime.datetime(date_on_next_month.year,
                                             date_on_next_month.month, 1)
        last_day_month = start_next_month - datetime.timedelta(1)
        sixth_day_month = last_day_month.date() + timedelta(6)
        return sixth_day_month

    def issue_description(self):

        description = "Hi Team" + "\n" + "Hope you are doing well" + "\n" + \
                      "Kindly confirm the current advertisers and accounts from the PDF attached." + "\n" + \
                      "Making sure that for each platform the correct account id, advertiser or account name get" + \
                      "\n" + "included in the NDP data for ALL channels." + "\n" + \
                      "Note: Do let us know if there is any account that needs to be removed." + "\n" + \
                      "Please make sure that the media plan is uploaded on the NeoSageCentral SharePoint Folder." \
                      + "\n" \
                      + "https://insidemedia.sharepoint.com/sites/neosagecentral/Shared%20Documents/" \
                        "Forms/AllItems.aspx?id=%2Fsites%2Fneosagecentral%2FShared%20Documents%2FFY18%20Media%" \
                        "20Plans%2FQ4%20Media%20Plans" + "\n" + "Thanks," + "\n" + "Ubaid"

        self.description = description

    def de(self):
        watch = [
            'anastasia.lanina', 'Ing-y.Chenn', 'thilo.babel',
            'jennifer.marquez', 'manon.leymat', 'mohammad.dilshad',
            'deepak.garg', 'matthew.perrone'
        ]
        assignees = 'anastasia.lanina'
        attachment = ['C://Adops-Git//Files//DE.xlsx']

        self.issue_de = {
            'project': {
                'key': 'MOS'
            },
            'issuetype': {
                'name': 'Reporting'
            },
            'summary':
            'NDP Data Audit {} DE'.format(Jira.date_create().strftime('%B')),
            'description':
            self.description,
            'customfield_10038': {
                'value': 'DE'
            },
            'customfield_10052': {
                'value': 'Ad hoc'
            },
            'customfield_10053': {
                'value': 'Monthly'
            },
            "assignee": {
                "name": assignees
            },
            'duedate':
            str(Jira.sixth_day())
        }

        create_de = self.client.create_issue(fields=self.issue_de,
                                             prefetch=True)
        self.create_de = create_de

        for i in watch:
            self.client.add_watcher(self.create_de.id, i)

        for j in attachment:
            self.client.add_attachment(self.create_de.id, j)

    def fr(self):
        watch = [
            'manon.mercier', 'maxime.sarrazin', 'jennifer.marquez',
            'manon.leymat', 'mohammad.dilshad', 'deepak.garg',
            'matthew.perrone'
        ]
        assignees = 'manon.mercier'
        attachment = ['C://Adops-Git//Files//FR.xlsx']
        self.issue_fr = {
            'project': {
                'key': 'MOS'
            },
            'issuetype': {
                'name': 'Reporting'
            },
            'summary':
            'NDP Data Audit {} FR'.format(Jira.date_create().strftime('%B')),
            'description':
            self.description,
            'customfield_10038': {
                'value': 'FR'
            },
            'customfield_10052': {
                'value': 'Ad hoc'
            },
            'customfield_10053': {
                'value': 'Monthly'
            },
            "assignee": {
                "name": assignees
            },
            'duedate':
            str(Jira.sixth_day())
        }

        self.create_fr = self.client.create_issue(fields=self.issue_fr,
                                                  prefetch=True)
        for i in watch:
            self.client.add_watcher(self.create_fr.id, i)

        for j in attachment:
            self.client.add_attachment(self.create_fr.id, j)

    def es(self):
        watch = [
            'carmen.candela', 'antonio.desantos', 'raquel.hernandez',
            'jennifer.marquez', 'manon.leymat', 'mohammad.dilshad',
            'deepak.garg', 'matthew.perrone'
        ]
        assignees = 'antonio.desantos'
        attachment = [
            'C://Adops-Git//Files//ES.xlsx', 'C://Adops-Git//Files//PT.xlsx'
        ]
        self.issue_es = {
            'project': {
                'key': 'MOS'
            },
            'issuetype': {
                'name': 'Reporting'
            },
            'summary':
            'NDP Data Audit {} ES'.format(Jira.date_create().strftime('%B')),
            'description':
            self.description,
            'customfield_10038': {
                'value': 'ES'
            },
            'customfield_10052': {
                'value': 'Ad hoc'
            },
            'customfield_10053': {
                'value': 'Monthly'
            },
            "assignee": {
                "name": assignees
            },
            'duedate':
            str(Jira.sixth_day())
        }

        self.create_es = self.client.create_issue(fields=self.issue_es,
                                                  prefetch=True)
        for i in watch:
            self.client.add_watcher(self.create_es.id, i)

        for j in attachment:
            self.client.add_attachment(self.create_es.id, j)

    def us(self):
        watch = [
            'christine.ciarcia', 'vanessa.ezeta', 'jennifer.marquez',
            'manon.leymat', 'mohammad.dilshad', 'deepak.garg',
            'matthew.perrone'
        ]
        assignees = 'vanessa.ezeta'
        attachment = [
            'C://Adops-Git//Files//CA.xlsx', 'C://Adops-Git//Files//US.xlsx',
            'C://Adops-Git//Files//US & CA.xlsx'
        ]
        self.issue_us = {
            'project': {
                'key': 'MOS'
            },
            'issuetype': {
                'name': 'Reporting'
            },
            'summary':
            'NDP Data Audit {} US'.format(Jira.date_create().strftime('%B')),
            'description':
            self.description,
            'customfield_10038': {
                'value': 'US'
            },
            'customfield_10052': {
                'value': 'Ad hoc'
            },
            'customfield_10053': {
                'value': 'Monthly'
            },
            "assignee": {
                "name": assignees
            },
            'duedate':
            str(Jira.sixth_day())
        }

        self.create_us = self.client.create_issue(fields=self.issue_us,
                                                  prefetch=True)
        for i in watch:
            self.client.add_watcher(self.create_us.id, i)

        for j in attachment:
            self.client.add_attachment(self.create_us.id, j)

    def uk(self):
        watch = [
            'mireia.nadal', 'marta.fiascaris', 'nick.gardiner',
            'yasmin.andrews', 'ye-eun.kim', 'jennifer.marquez', 'manon.leymat',
            'mohammad.dilshad', 'deepak.garg', 'matthew.perrone'
        ]
        assignees = 'ye-eun.kim'
        attachment = [
            'C://Adops-Git//Files//UK.xlsx', 'C://Adops-Git//Files//IE.xlsx'
        ]
        self.issue_uk = {
            'project': {
                'key': 'MOS'
            },
            'issuetype': {
                'name': 'Reporting'
            },
            'summary':
            'NDP Data Audit {} UK'.format(Jira.date_create().strftime('%B')),
            'description':
            self.description,
            'customfield_10038': {
                'value': 'UK'
            },
            'customfield_10052': {
                'value': 'Ad hoc'
            },
            'customfield_10053': {
                'value': 'Monthly'
            },
            "assignee": {
                "name": assignees
            },
            'duedate':
            str(Jira.sixth_day())
        }

        self.create_uk = self.client.create_issue(fields=self.issue_uk,
                                                  prefetch=True)
        for i in watch:
            self.client.add_watcher(self.create_uk.id, i)

        for j in attachment:
            self.client.add_attachment(self.create_uk.id, j)

    def mea(self):
        watch = [
            'cindy.booysen', 'kyle.ackermann', 'jennifer.marquez',
            'manon.leymat', 'mohammad.dilshad', 'deepak.garg',
            'matthew.perrone'
        ]
        assignees = 'cindy.booysen'
        attachment = ['C://Adops-Git//Files//ZA.xlsx']
        self.issue_mea = {
            'project': {
                'key': 'MOS'
            },
            'issuetype': {
                'name': 'Reporting'
            },
            'summary':
            'NDP Data Audit {} MEA'.format(Jira.date_create().strftime('%B')),
            'description':
            self.description,
            'customfield_10038': {
                'value': 'MEA'
            },
            'customfield_10052': {
                'value': 'Ad hoc'
            },
            'customfield_10053': {
                'value': 'Monthly'
            },
            "assignee": {
                "name": assignees
            },
            'duedate':
            str(Jira.sixth_day())
        }

        self.create_mea = self.client.create_issue(fields=self.issue_mea,
                                                   prefetch=True)
        for i in watch:
            self.client.add_watcher(self.create_mea.id, i)

        for j in attachment:
            self.client.add_attachment(self.create_mea.id, j)

    def aus(self):
        watch = [
            'corinne.hewlett', 'thuy.le', 'jon.windred', 'jennifer.marquez',
            'manon.leymat', 'mohammad.dilshad', 'deepak.garg',
            'matthew.perrone'
        ]
        assignees = 'corinne.hewlett'
        attachment = ["C://Adops-Git//Files//AUS.xlsx"]

        self.issue_aus = {
            'project': {
                'key': 'MOS'
            },
            'issuetype': {
                'name': 'Reporting'
            },
            'summary':
            'NDP Data Audit {} AUS'.format(Jira.date_create().strftime('%B')),
            'description':
            self.description,
            'customfield_10038': {
                'value': 'AUS'
            },
            'customfield_10052': {
                'value': 'Ad hoc'
            },
            'customfield_10053': {
                'value': 'Monthly'
            },
            "assignee": {
                "name": assignees
            },
            'duedate':
            str(Jira.sixth_day())
        }

        self.create_aus = self.client.create_issue(fields=self.issue_aus,
                                                   prefetch=True)

        for i in watch:
            self.client.add_watcher(self.create_aus.id, i)

        for j in attachment:
            self.client.add_attachment(self.create_aus.id, j)

    def apac(self):
        watch = [
            'ravi.chettiar', 'jennifer.marquez', 'manon.leymat',
            'mohammad.dilshad', 'deepak.garg', 'matthew.perrone'
        ]
        assignees = 'ravi.chettiar'
        attachment = [
            'C://Adops-Git//Files//HK.xlsx', 'C://Adops-Git//Files//ID.xlsx',
            'C://Adops-Git//Files//MY.xlsx', 'C://Adops-Git//Files//SG.xlsx',
            'C://Adops-Git//Files//TH.xlsx'
        ]

        self.issue_apac = {
            'project': {
                'key': 'MOS'
            },
            'issuetype': {
                'name': 'Reporting'
            },
            'summary':
            'NDP Data Audit {} APAC'.format(Jira.date_create().strftime('%B')),
            'description':
            self.description,
            'customfield_10038': {
                'value': 'APAC'
            },
            'customfield_10052': {
                'value': 'Ad hoc'
            },
            'customfield_10053': {
                'value': 'Monthly'
            },
            "assignee": {
                "name": assignees
            },
            'duedate':
            str(Jira.sixth_day())
        }

        self.create_apac = self.client.create_issue(fields=self.issue_apac,
                                                    prefetch=True)
        for i in watch:
            self.client.add_watcher(self.create_apac.id, i)

        for j in attachment:
            self.client.add_attachment(self.create_apac.id, j)

    def main(self):
        self.get_projects()
        logger.info('reading issue Description' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.issue_description()
        logger.info('Done!reading issue Description' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for DE' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.de()
        logger.info('Done!creating issue for DE' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for FR' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.fr()
        logger.info('Done!creating issue for FR' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for ES' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.es()
        logger.info('Done!creating issue for ES' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for US' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.us()
        logger.info('Done!creating issue for US' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for UK' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.uk()
        logger.info('Done!creating issue for UK' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for MEA' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.mea()
        logger.info('Done!creating issue for MEA' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for AUS' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.aus()
        logger.info('Done!creating issue for AUS' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

        logger.info('Start!creating issue for APAC' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))
        self.apac()
        logger.info('Done!creating issue for APAC' + " at " +
                    str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))