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 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 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)
``` """ @app.route('/', methods=['POST']) def callback(): json = request.get_json() if json['action']['type'] == "updateCard": # TODO: Find a messages with the same card id and update it, # because changes could have been made user = json['action']['memberCreator']['fullName'] desc = json['action']['data']['card']['desc'] card_id = json['action']['data']['card']['id'] assingees = get_assignees(json['action']['data']['card']['idMembers']) discord.send_message(template.format(card_id, user, assignees, desc)) return "200" def get_assignees(member_ids): assignees = [] for id in member_ids: assignees.append('@' + trello_client.get_member(id).full_name) if assignees: # List is not empty return ', '.join(str(a) for a in assignees) return " " if __name__ == '__main__': trello_client.create_hook(TRELLO_API_KEY, MODEL_ID) app.run(host="0.0.0.0", port=1337)
def print_hook(hook): print(f"{hook.desc} -> {hook.callback_url} (Active: {hook.active})") def delete_all_webhooks(): for hook in client.list_hooks(): print_hook(hook) hook.delete() def list_orgs(): for org in client.list_organizations(): print(f"{org.id} {org.name}") if __name__ == "__main__": # delete_all_webhooks() # list_orgs() org = client.get_organization(os.getenv("TRELLO_ORG_ID")) for board in org.all_boards(): print(f"{board.name}") hook = client.create_hook( os.getenv("ULTRAHOOK_CALLBACK_URL"), board.id, desc="Ludus" ) if hook: print_hook(hook) else: print("failed to create hook")
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()