def get_client(self): client = None while client is None: self._set_creds() client = TrelloClient(api_key=self._api_key, token=self._token) try: client.list_hooks(self._token) except Unauthorized: print('Trello client is not authorized.') client = None self._write_config() print('Trello client successfully authorized.') return client
def get(self, request): try: token = request.GET.get('token') user = request.user if token is None: boards = None return super(BoardView, self).get(request) else: trello_client = TrelloClient(api_key=settings.TRELLO_APIKEY, token=token) boards = trello_client.list_boards() if boards: result = [h.delete() for h in trello_client.list_hooks()] print("delete trello hook :: result={}".format(result)) for board in boards: print("BOARD_ID:", board.id) slug_board = slugify(board.name, allow_unicode=False) b, created = Board.objects.get_or_create( name=slug_board, user=user, trello_board_id=board.id, trello_token=token) host = getenv("MATTERLLO_HOST") or request.get_host() url = "{}://{}/callback/{}/".format( request.scheme, host, b.id) result = trello_client.create_hook(url, board.id) print( "create trello hook :: callback={} :: board={} :: result={}" .format(url, slug_board, result)) return super(BoardView, self).get(request) except Exception as e: print("unable to display board :: {}".format(e)) return super(BoardView, self).get(request)
def create_card(pedido): cliente = pedido.cliente placa_video = get_component(pedido, 'Placa de Vídeo') processador = get_component(pedido, 'Processadores') memoria = get_component(pedido, 'Memória RAM') disco = get_component(pedido, 'Disco Rígido/SSD') gabinete = get_component(pedido, 'Gabinete') placa_mae = get_component(pedido, 'Placa mãe') fonte = get_component(pedido, 'Fonte') data = { 'statu_pedido': str(pedido.statu_pedido), 'username': str(cliente.username), 'email': str(cliente.email), 'telefone': str(cliente.telefone), 'placa_video': str(placa_video), 'processador': str(processador), 'memoria': str(memoria), 'disco': str(disco), 'gabinete': str(gabinete), 'placa_mae': str(placa_mae), 'fonte': str(fonte), } client = TrelloClient(api_key=settings.API_KEY, token=settings.TRELLO_API_SECRET) if settings.BOARD_NAME: board = check_board(client.list_boards()) if client.list_hooks() == []: client.create_hook(settings.CALLBACK_DOMAIN, board.id) for lista in board.all_lists(): if lista.name == pedido.statu_pedido: lista.add_card(name=f'Pedido {pedido.id}', desc=loader.render_to_string( 'pedido_template.txt', data))
def main(): try: parser = argparse.ArgumentParser(description="Webhook helpers") parser.add_argument('--cleanup', dest='cleanup', action='store_true', help='delete webhook from your SETTINGS.') parser.add_argument('--update', dest='update', action='store_true', help='upsert webhook from your SETTINGS.') parser.add_argument('--init', dest='init', action='store_true', help='delete and create webhook from your SETTINGS.') args = parser.parse_args() if not args.cleanup and not args.update and not args.init: print parser.print_help() sys.exit(0) client = TrelloClient(api_key=SETTINGS['trello_api_key'], token=SETTINGS['trello_api_token']) trello_boards = client.list_boards() boards_name = [slugify(b['name']) for b in SETTINGS.get('boards', {}).values()] # cleanup part if args.cleanup or args.init: result = [h.delete() for h in client.list_hooks()] LOGGING.info('delete {} webhook'.format(len(result))) # update / init part if args.update or args.init: for board in trello_boards: board_name = slugify(board.name) if board_name not in boards_name: continue LOGGING.info('try to create webhook board :: {}'.format(board_name)) url = SETTINGS['callback_url'] + '/trelloCallbacks/' result = client.create_hook(url, board.id) LOGGING.info('create webhook board :: {} :: {}'.format(board_name, result)) except Exception as e: LOGGING.error('unable init webhook :: {}'.format(e)) sys.exit(1)
class TrelloClientTestCase(unittest.TestCase): """ Tests for TrelloClient API. Note these test are in order to preserve dependencies, as an API integration cannot be tested independently. """ def setUp(self): self._trello = TrelloClient(os.environ['TRELLO_API_KEY'], token=os.environ['TRELLO_TOKEN']) def test01_list_boards(self): self.assertEqual( len(self._trello.list_boards(board_filter="open")), int(os.environ['TRELLO_TEST_BOARD_COUNT'])) def test10_board_attrs(self): boards = self._trello.list_boards() for b in boards: self.assertIsNotNone(b.id, msg="id not provided") self.assertIsNotNone(b.name, msg="name not provided") self.assertIsNotNone(b.description, msg="description not provided") self.assertIsNotNone(b.closed, msg="closed not provided") self.assertIsNotNone(b.url, msg="url not provided") def test20_board_all_lists(self): boards = self._trello.list_boards() for b in boards: try: b.all_lists() except Exception: self.fail("Caught Exception getting lists") def test21_board_open_lists(self): boards = self._trello.list_boards() for b in boards: try: b.open_lists() except Exception: self.fail("Caught Exception getting open lists") def test22_board_closed_lists(self): boards = self._trello.list_boards() for b in boards: try: b.closed_lists() except Exception: self.fail("Caught Exception getting closed lists") def test30_list_attrs(self): boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): self.assertIsNotNone(l.id, msg="id not provided") self.assertIsNotNone(l.name, msg="name not provided") self.assertIsNotNone(l.closed, msg="closed not provided") break # only need to test one board's lists def test50_list_cards(self): boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): for c in l.list_cards(): self.assertIsNotNone(c.id, msg="id not provided") self.assertIsNotNone(c.name, msg="name not provided") self.assertIsNotNone(c.description, msg="description not provided") self.assertIsNotNone(c.closed, msg="closed not provided") self.assertIsNotNone(c.url, msg="url not provided") break break pass def test51_fetch_cards(self): """ Tests fetching all attributes for all cards """ boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): for c in l.list_cards(): c.fetch() self.assertIsInstance(c.date_last_activity, datetime, msg='date not provided') self.assertTrue(len(c.board_id) > 0, msg='board id not provided') break break pass def test52_list_hooks(self): self.assertIsInstance(self._trello.list_hooks(), list) def test53_unauthorized(self): client = TrelloClient('a') self.assertRaises(Unauthorized, client.list_boards) def test54_resource_unavailable(self): self.assertRaises(ResourceUnavailable, self._trello.get_card, '0') def test_list_stars(self): """ Test trello client star list """ self.assertEqual(len(self._trello.list_stars()), int(os.environ["TRELLO_TEST_STAR_COUNT"]), "Number of stars does not match TRELLO_TEST_STAR_COUNT") def test_add_delete_star(self): """ Test add and delete star to/from test board """ test_board_id = self._trello.search(os.environ["TRELLO_TEST_BOARD_NAME"])[0].id new_star = self._trello.add_star(test_board_id) star_list = self._trello.list_stars() self.assertTrue(new_star in star_list, "Star id was not added in list of starred boards") deleted_star = self._trello.delete_star(new_star) star_list = self._trello.list_stars() self.assertFalse(deleted_star in star_list, "Star id was not deleted from list of starred boards")
class TrelloClientTestCase(unittest.TestCase): """ Tests for TrelloClient API. Note these test are in order to preserve dependencies, as an API integration cannot be tested independently. """ def setUp(self): self._trello = TrelloClient(os.environ['TRELLO_API_KEY'], token=os.environ['TRELLO_TOKEN']) def test01_list_boards(self): self.assertEquals(len(self._trello.list_boards()), int(os.environ['TRELLO_TEST_BOARD_COUNT'])) def test10_board_attrs(self): boards = self._trello.list_boards() for b in boards: self.assertIsNotNone(b.id, msg="id not provided") self.assertIsNotNone(b.name, msg="name not provided") self.assertIsNotNone(b.description, msg="description not provided") self.assertIsNotNone(b.closed, msg="closed not provided") self.assertIsNotNone(b.url, msg="url not provided") def test20_board_all_lists(self): boards = self._trello.list_boards() for b in boards: try: b.all_lists() except Exception: self.fail("Caught Exception getting lists") def test21_board_open_lists(self): boards = self._trello.list_boards() for b in boards: try: b.open_lists() except Exception: self.fail("Caught Exception getting open lists") def test22_board_closed_lists(self): boards = self._trello.list_boards() for b in boards: try: b.closed_lists() except Exception: self.fail("Caught Exception getting closed lists") def test30_list_attrs(self): boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): self.assertIsNotNone(l.id, msg="id not provided") self.assertIsNotNone(l.name, msg="name not provided") self.assertIsNotNone(l.closed, msg="closed not provided") break # only need to test one board's lists def test50_list_cards(self): boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): for c in l.list_cards(): self.assertIsNotNone(c.id, msg="id not provided") self.assertIsNotNone(c.name, msg="name not provided") self.assertIsNotNone(c.description, msg="description not provided") self.assertIsNotNone(c.closed, msg="closed not provided") self.assertIsNotNone(c.url, msg="url not provided") break break pass def test51_fetch_cards(self): """ Tests fetching all attributes for all cards """ boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): for c in l.list_cards(): c.fetch() self.assertIsInstance(c.date_last_activity, datetime, msg='date not provided') self.assertTrue(len(c.board_id) > 0, msg='board id not provided') break break pass def test52_list_hooks(self): self.assertIsInstance(self._trello.list_hooks(), list)
class TrelloClientTestCase(unittest.TestCase): """ Tests for TrelloClient API. Note these test are in order to preserve dependencies, as an API integration cannot be tested independently. """ def setUp(self): self._trello = TrelloClient(os.environ["TRELLO_API_KEY"], token=os.environ["TRELLO_TOKEN"]) def test01_list_boards(self): self.assertEquals(len(self._trello.list_boards()), int(os.environ["TRELLO_TEST_BOARD_COUNT"])) def test10_board_attrs(self): boards = self._trello.list_boards() for b in boards: self.assertIsNotNone(b.id, msg="id not provided") self.assertIsNotNone(b.name, msg="name not provided") self.assertIsNotNone(b.description, msg="description not provided") self.assertIsNotNone(b.closed, msg="closed not provided") self.assertIsNotNone(b.url, msg="url not provided") def test20_board_all_lists(self): boards = self._trello.list_boards() for b in boards: try: b.all_lists() except Exception: self.fail("Caught Exception getting lists") def test21_board_open_lists(self): boards = self._trello.list_boards() for b in boards: try: b.open_lists() except Exception: self.fail("Caught Exception getting open lists") def test22_board_closed_lists(self): boards = self._trello.list_boards() for b in boards: try: b.closed_lists() except Exception: self.fail("Caught Exception getting closed lists") def test30_list_attrs(self): boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): self.assertIsNotNone(l.id, msg="id not provided") self.assertIsNotNone(l.name, msg="name not provided") self.assertIsNotNone(l.closed, msg="closed not provided") break # only need to test one board's lists def test50_list_cards(self): boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): for c in l.list_cards(): self.assertIsNotNone(c.id, msg="id not provided") self.assertIsNotNone(c.name, msg="name not provided") self.assertIsNotNone(c.description, msg="description not provided") self.assertIsNotNone(c.closed, msg="closed not provided") self.assertIsNotNone(c.url, msg="url not provided") break break pass def test51_fetch_cards(self): """ Tests fetching all attributes for all cards """ boards = self._trello.list_boards() for b in boards: for l in b.all_lists(): for c in l.list_cards(): c.fetch() self.assertIsInstance(c.date_last_activity, datetime, msg="date not provided") self.assertTrue(len(c.board_id) > 0, msg="board id not provided") break break pass def test52_list_hooks(self): self.assertIsInstance(self._trello.list_hooks(), list) def test53_unauthorized(self): client = TrelloClient("a") self.assertRaises(Unauthorized, client.list_boards) def test54_resource_unavailable(self): self.assertRaises(ResourceUnavailable, self._trello.get_card, "0")
def trelloSprintBurndown(event, context): """ Extracts Trello Webhook Payload information and automates Trello :param event: Event data from API Gateway contains Trello Webhook Payload :param context: This object provides methods and properties that provide information about the invocation, function and execution environment :return: returns nothing """ # Connect to Trello client = TrelloClient( api_key=TRELLO_API_KEY, token=TRELLO_TOKEN ) # S3 Client s3 = boto3.resource('s3') if event: if current_day not in ('Saturday', 'Sunday'): payload = json.loads(event['payload']) print(payload) board_id = payload['action']['data']['board']['id'] # Create Webhook for new board if payload['action']['type'] == 'addToOrganizationBoard': existing_webhooks = client.list_hooks(TRELLO_TOKEN) create_new_board_hook(client, payload, existing_webhooks) if payload['action']['type'] in ('updateCard', 'createCard'): # Get PowerUp Data powerup_data = get_powerup_data(client, board_id) # Get Monitor lists monitor_lists = json.loads(powerup_data)['selected_list'] if (payload['action']['data'].get('listBefore', {}).get('id') in monitor_lists or payload['action']['data'].get('listAfter', {}).get('id') in monitor_lists or (payload['action'].get('display').get('translationKey') in 'action_create_card' and payload['action']['data'].get('list', {}).get('id') in monitor_lists)): # Download Sprint data and Card Attachment data files from S3 try: s3.Bucket(DEPLOYMENT_BUCKET).download_file(sprint_data_file_name, '/tmp/' + sprint_data_file_name) except Exception as error: print(error) pass # Check PowerUp Data exists if powerup_data is not None: sprint_start_day = json.loads(powerup_data)['sprint_start_day'] total_sprint_days = int(json.loads(powerup_data)['total_sprint_days']) # Get Done lists done_list = json.loads(powerup_data)['selected_done_list'] # Get counts of Stories/Tasks stories_defects_remaining, stories_defects_done, tasks_remaining, ideal_tasks_remaining = get_counts(client, payload, monitor_lists, done_list, sprint_start_day) print(f'Board ID: {board_id}') print(f'Stories Remaining: {stories_defects_remaining}') print(f'Stories Done: {stories_defects_done}') print(f'Tasks Remaining: {tasks_remaining}') print(f'Ideal Tasks Remaining: {ideal_tasks_remaining}') # Current Sprint Dates sprint_dates = get_sprint_dates(sprint_start_day, (total_sprint_days - 1), board_id) print(f'Start Date: {sprint_dates[0]} End Date: {sprint_dates[len(sprint_dates)-1]}') team_members = json.loads(powerup_data)['team_member_list'] is_show_team_size = eval(json.loads(powerup_data).get('is_show_team_size', 'False')) team_members_days_ooo = json.loads(powerup_data)['team_members_days_ooo'] team_members_days_ooo = team_members_days_ooo.split(",") team_members_days_ooo_list = [0] for ooo_per_day in team_members_days_ooo: team_members_days_ooo_list.append(float(ooo_per_day.split("-")[1])) team_size = len(team_members) # Update sprint data sprint_data = update_sprint_data(sprint_start_day, board_id, sprint_dates, stories_defects_remaining, stories_defects_done, tasks_remaining, ideal_tasks_remaining, team_size) # Create Sprint Burndown Chart create_chart(sprint_data, total_sprint_days, board_id, team_members, team_members_days_ooo_list, is_show_team_size) attachment_card_id = json.loads(powerup_data)['selected_card_for_attachment'] # Delete previously attached Chart from the card delete_chart(client, attachment_card_id) # Attach Chart to Card attach_chart(client, attachment_card_id, board_id) # Upload Sprint data and Card Attachment data files from S3 try: s3.Object(DEPLOYMENT_BUCKET, sprint_data_file_name).put(Body=open('/tmp/' + sprint_data_file_name, 'rb')) except Exception as error: print(error) pass # Return Success success() else: # Create Webhook for Trello Organization client.create_hook(CALLBACK_URL, TRELLO_ORGANIZATION_ID, "Trello Organiztion Webhook", TRELLO_TOKEN) # Get existing Trello Webhooks existing_webhooks = client.list_hooks(TRELLO_TOKEN) # Create Webhook for Exisiting Boards create_existing_boards_hook(client, existing_webhooks) # Return Success success()