def xls_to_trello(args): with open("secrets.json", "r") as f: d = json.load(f) TRELLO_KEY = d["apikey"] TRELLO_TOKEN = d["token"] trello = TrelloApi(TRELLO_KEY) trello.set_token(TRELLO_TOKEN) if args.board_id is None: board = trello.boards.new(args.board_name) BOARD_ID = board["id"] else: BOARD_ID = args.board_id df = pd.read_excel(args.path) lists = {} for name in df["Custom status"].unique(): lists[name] = trello.boards.new_list(board["id"], name) for _, row in tqdm(df.iterrows(), desc="Exporting tasks", total=len(df)): list_id = lists[row["Custom status"]]["id"] trello.lists.new_card( list_id, row["Title"], due=None if pd.isna(row["End Date"]) else row["End Date"], )
def fetch(workdir, token, board_id): tr = TrelloApi(TRELLO_PUBLIC_APP_KEY) user_token = read_token(workdir) if token is not None: if is_valid_token(tr, token): logger.warning("Overriding default Trello token") user_token = token else: logger.critical("Invalid token specified") return None if user_token is None: logger.critical("No Trello access token configured. Use `setup` command or `--token` argument") return None tr.set_token(user_token) now = time.time() try: board = tr.boards.get(board_id) except HTTPError as e: logger.error(e) return None cards = dict(map(lambda x: [x["id"], x], tr.boards.get_card(board_id))) lists = dict(map(lambda x: [x["id"], x], map(tr.lists.get, set(map(lambda c: c["idList"], cards.itervalues()))))) meta = {"board": board, "snapshot_time": now} return {"meta": meta, "cards": cards, "lists": lists}
def authorize(self): self.app.log.debug('Authorizing a Trello user.') # validate required config parameters if not self.app.config.get('trello', 'auth_key'): raise error.ConfigError( "Missing config parameter 'trello.auth_key'! " "Please run 'scrum-tools trello authorize' first! ") try: tl = TrelloApi(self.app.config.get('trello', 'auth_key')) url = tl.get_token_url('scrum-tools', expires='30days', write_access=True) cprint( os.linesep.join([ "Please follow the link below and update these entries in the [trello] section " "of your scrum-tools config: ", " auth_key = %s" % self.app.config.get('trello', 'auth_key'), " auth_token = %s" % '<generated_token>' ]), 'green') cprint("URL: %s" % url, 'green') except RuntimeError as e: raise e
def __init__(self): self.audience_id = 'c6e22b46fd' self.interest_category_id = 'interests-9872b92779' self.segement_field_id = 'interests-ddaa47f9ce' self.trello_token = os.environ['TRELLO_TOKEN'] self.trello_key = os.environ['TRELLO_API_KEY'] self.mailchimp_key = os.environ['MAILCHIMP_API_KEY'] self.never_bouce_apy_key = os.environ['NB_APY_KEY'] self.mailchimp_client = Client() self.mailchimp_client.set_config({"api_key": self.mailchimp_key}) self.trello = TrelloApi(self.trello_key, self.trello_token) self.trello.set_token(self.trello_token) self.markdown2html = Markdown() self.segments = { 'ruby': '55eaa52f81', 'python': 'febbd795e0', 'javascript (backend/node/meteor)': 'dd8317b5bb', 'php': '804ccb1e24', 'mobile': 'c71d0c8111', 'javascript (frontend/angular/react/vue)': '9d6ae89058', 'interaction design (web design/mobile design/ui/ux)': 'b7205a2deb', 'graphic design (branding/logos/animations/illustrations)': 'b00fcf9a76' }
def post_to_colony_trello(leads): lead_id = '5cf85281ceafe811d744c6d6' token = os.environ['TRELLO_TOKEN'] key = os.environ['TRELLO_API_KEY'] trello = TrelloApi(key, token) trello.set_token(token) _post(leads, lead_id, trello)
def update_trello(applicant): client = TrelloApi(current_app.config['TRELLO_API_KEY']) client.set_token(current_app.config['TRELLO_API_TOKEN']) desc = gen_text(applicant) client.lists.new_card(name=applicant.name, list_id=current_app.config['TRELLO_LIST_ID'], desc=desc)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') try: try: logging.info("connecting to Trello API") trello = TrelloApi(SECRETS.TRELLO_API_KEY) SECRETS.reload_trello_token() trello.set_token(SECRETS.TRELLO_AUTH_TOKEN) ingredients = get_trello_check_list(trello) except HTTPError as e : token_url= trello.get_token_url('My App', expires='30days', write_access=True) logging.exception(e) return func.HttpResponse( f"Authentication error with Trello API. Please access to this url and update the configuration with the new token : \n {token_url}", status_code=401 ) keep_connection,note = get_checklist_from_keep() send_checklist_to_keep(ingredients,note) sync_keep(keep_connection) logging.info("success!") return func.HttpResponse( f"Succes ! The new ingredients added are the following : \n {ingredients}", status_code=200 ) except Exception as e: logging.exception(e) return func.HttpResponse( str(e), status_code=500 )
def on_post(self, req, resp, token): trello = TrelloApi(trelloconfig.api_key, token=trelloconfig.token) trello_token = trello.get_token_url('My App', expires='30days', write_access=True) storage = ZODB.FileStorage.FileStorage('trees/' + token + '.fs') db = ZODB.DB(storage) connection = db.open() root = connection.root if hasattr(root, 'tree'): tree = root.tree else: resp.body = "Initialize first" connection.close() db.close() storage.close() return lst = list(btree.inorder(tree)) connection.close() db.close() storage.close() if len(lst) > 0: id_new = trello.boards.new_list('Le5vKw7H', token)['id'] for card in lst: trello.cards.new(card, id_new)
def main(): """ Grab Trello Token Url for a given key. """ args = parse_args() trello = TrelloApi(args.trello_key) return trello.get_token_url(args.prog_name, expires=args.expires, write_access=False)
def setup_trello(): with open('env.json') as env: config = json.load(env) trello = TrelloApi(config['TRELLO_APP_KEY']) trello.set_token(config['TRELLO_AUTH_TOKEN']) return config, trello
def on_get(self, req, resp, board): trello = TrelloApi(trelloconfig.api_key, token=trelloconfig.token) trello_token = trello.get_token_url('My App', expires='30days', write_access=True) response=trello.boards.get_list(board) lists= {} for lst in response: lists[lst['id']]=lst['name'] resp.body = json.dumps(lists)
def on_get(self, req, resp, lst): trello = TrelloApi(trelloconfig.api_key, token=trelloconfig.token) trello_token = trello.get_token_url('My App', expires='30days', write_access=True) response=trello.lists.get_card(lst) cards= [] for card in response: cards.append(card['name']) resp.body = json.dumps(cards)
def setup_trello(): with open('env.json') as env: config = json.load(env) trello = TrelloApi( config['TRELLO_APP_KEY'] ) trello.set_token( config['TRELLO_AUTH_TOKEN'] ) return config, trello
def on_get(self, req, resp): trello = TrelloApi(trelloconfig.api_key, token=trelloconfig.token) trello_token = trello.get_token_url('My App', expires='30days', write_access=True) response=trello.members.get_board('agusrumayor') boards= {} for board in response: boards[board['id']]=board['name'] resp.body = json.dumps(boards)
def main(): parser = argparse.ArgumentParser() parser.add_argument("-c", "--client-api-key", help="your app's client api key", action="store", required=True) parser.add_argument("-t", "--token", help="your app's access token", action="store", required=True) parser.add_argument("-b", "--board-id", help="your trello board id", action="store", required=True) args = vars(parser.parse_args()) log_format = '%(asctime)s - %(name)s - %(levelname)s %(message)s' logging.basicConfig(format=log_format, level=logging.WARN) trello = TrelloApi(args['client_api_key']) trello.set_token(args['token']) fields = 'fields=id,idMembers,idLabels,idList,shortUrl,dateLastActivity,\ name' cards = trello.boards.get_card(args['board_id'], fields=fields) cards = trello_add_card_creation_date(cards) cards.sort(key=lambda c: c['timeDelta']) lists = group_by_list(cards) lists = replace_id_by_label(lists, trello) members = trello.boards.get('{}/members'.format(args['board_id'])) for member in members: board_members[member['id']] = member['fullName'] last_week = Delorean() - timedelta(weeks=1) print("Since {} - {}".format(last_week.humanize(), last_week.date)) action_filter = 'filter=createCard,deleteCard,updateCard:closed,\ addMemberToCard,removeMemberFromCard,updateCard:idList' actions = trello.boards.get( '{}/actions?limit=1000&filter={}&since={}'.format( args['board_id'], action_filter, last_week.date)) # TODO add paging support if we go over 1000 if len(actions) == 1000: logging.warn('the number of retried actions is over 1000, you may \ be missing other actions that occurred during the last week, \ please support paging') simple_actions = map(lambda a: transform_action(a), actions) describe_last_week_actions(simple_actions) print "---" for action in simple_actions: print action
def listcards(): TRELLO_API_KEY, TRELLO_TOKEN = get_creds(name="workon") trello = TrelloApi(TRELLO_API_KEY) trello.set_token(TRELLO_TOKEN) b=trello.members.get_card(USERNAME, fields='name,idShort,shortUrl') print "My trello cards:" for i in b: print i['name'] +'- ID:'+ color.BLUE +str(i['idShort']) + color.END
def on_get(self, req, resp, board): trello = TrelloApi(trelloconfig.api_key, token=trelloconfig.token) trello_token = trello.get_token_url('My App', expires='30days', write_access=True) response = trello.boards.get_list(board) lists = {} for lst in response: lists[lst['id']] = lst['name'] resp.body = json.dumps(lists)
def on_get(self, req, resp): trello = TrelloApi(trelloconfig.api_key, token=trelloconfig.token) trello_token = trello.get_token_url('My App', expires='30days', write_access=True) response = trello.members.get_board('agusrumayor') boards = {} for board in response: boards[board['id']] = board['name'] resp.body = json.dumps(boards)
def on_get(self, req, resp, lst): trello = TrelloApi(trelloconfig.api_key, token=trelloconfig.token) trello_token = trello.get_token_url('My App', expires='30days', write_access=True) response = trello.lists.get_card(lst) cards = [] for card in response: cards.append(card['name']) resp.body = json.dumps(cards)
def trello2Email(formInput): apikey = formInput['apikey'] tocken = formInput['tocken'] trello = TrelloApi(apikey) trello.set_token(tocken) boardId = formInput['Board_Id'] cards = trello.boards.get_card(boardId, fields=("name", "idList")) lists = trello.boards.get_list(boardId) bufList = StringIO() bufCard = StringIO() boardLists = [] boardcard = [] cadNumber = [] lis = 0 for list in trello.boards.get_list(boardId): member_card = dict() listName = list['name'] bufList.write(listName.encode('utf-8')) boardLists.append(bufList.getvalue()) bufList.truncate(0) lis = lis + 1 for card in trello.lists.get_card(list['id']): for member in card['idMembers']: if not member_card.has_key(member): member_card[member] = [] member_card[member].append(card) cad = 0 for memberId in member_card.keys(): member = trello.members.get(memberId) for card in member_card[memberId]: cardName = card['name'] memberInitials = member['initials'] bufCard.write( memberInitials.encode('utf-8') + ' : ' + cardName.encode('utf-8')) boardcard.append(bufCard.getvalue()) bufCard.truncate(0) cad = cad + 1 cadNumber.append(cad) html = getHtml.getHtmlFromBuf(boardLists, boardcard, cadNumber) print('successful') TO = formInput['Recipient_Email_Address'] FROM = '*****@*****.**' subject = formInput['Subject'] passw = 'jeaimevous' #its not my personal account today = datetime.date.today() sendEmail.py_mail(subject, html, TO, FROM, passw)
def startChecking(webhook_data): # Constants TRELLO_API_KEY = "1c7cec096175a93ed305cff00caf0592" TRELLO_API_TOKEN = "4ad7c1fa64ecb1c3e47928e60145f67fe035dd25238d9a9e817c6d13e436cd3d" BOARD_ID = "tbU0BvI3" # Trigger word for preparing TRIGGER = "lega" # Whitelist to dedicate users WHITELIST = [ "trello", ] # Setting up trello trello = TrelloApi(TRELLO_API_KEY) trello.set_token(TRELLO_API_TOKEN) # Action type triggering action_type = "action_changed_description_of_card" # Check for action type if webhook_data["action"]["display"]["translationKey"] == action_type: # Member creator seperating member_creator = webhook_data["action"]["memberCreator"] # Check for trigger word and whitelist if TRIGGER in webhook_data["action"]["data"]["card"][ "desc"] and not member_creator["username"] in WHITELIST: # Get shortlink from webhook shortlink = webhook_data["action"]["data"]["card"]["shortLink"] # Get all custom fields from server custom_fields = trello.cards.get_custom_fields_board(BOARD_ID) # Parsing necessary custom field custom_field = None for curr_cf in custom_fields: if not curr_cf["name"] == "Курьер" or not curr_cf[ "type"] == "text": continue custom_field = curr_cf # Finded breaking... break # Check for custom field if custom_field: print(111) custom_field_id = custom_field["id"] member_creator_check = member_creator["fullName"] # Updating data in trello servers resp = trello.cards.update_custom_field( shortlink, custom_field_id, {"value": { "text": member_creator_check }})
def trello2Email(formInput): apikey = formInput['apikey'] tocken = formInput['tocken'] trello = TrelloApi(apikey) trello.set_token(tocken) boardId = formInput['Board_Id'] cards = trello.boards.get_card(boardId, fields=("name", "idList")) lists = trello.boards.get_list(boardId) bufList = StringIO() bufCard = StringIO() boardLists = [] boardcard = [] cadNumber = [] lis = 0 for list in trello.boards.get_list(boardId): member_card = dict() listName = list['name'] bufList.write(listName.encode('utf-8')) boardLists.append(bufList.getvalue()) bufList.truncate(0) lis = lis + 1 for card in trello.lists.get_card(list['id']): for member in card['idMembers']: if not member_card.has_key(member): member_card[member] = [] member_card[member].append(card) cad = 0 for memberId in member_card.keys(): member = trello.members.get(memberId) for card in member_card[memberId]: cardName = card['name'] memberInitials = member['initials'] bufCard.write(memberInitials.encode('utf-8') + ' : ' + cardName.encode('utf-8')) boardcard.append(bufCard.getvalue()) bufCard.truncate(0) cad = cad + 1 cadNumber.append(cad) html = getHtml.getHtmlFromBuf(boardLists, boardcard, cadNumber) print('successful') TO = formInput['Recipient_Email_Address'] FROM = '*****@*****.**' subject = formInput['Subject'] passw = 'jeaimevous' #its not my personal account today = datetime.date.today() sendEmail.py_mail(subject, html, TO, FROM, passw)
def __init__(self, app_key, token, board_name): if not (all((app_key, token, board_name))): raise ValueError("app_key, token and board_name must be provided") else: self._app_key = app_key self._token = token self._board_name = board_name self.trello_handler = TrelloApi(self._app_key) self.trello_handler.set_token(self._token) super(TrelloParser, self).__init__()
def init(): if os.path.isfile("Token") ==False: FirstTimeUse.main() global trello trello = TrelloApi(userpass.appKey) file = open('Token', mode="r") trelloDetails = file.readline().split(",") file.close() trello.set_token(trelloDetails[0]) global boardID boardID = trelloDetails[1] return [trello,trelloDetails[1]]
class TrelloParser(object): def __init__(self, app_key, token, board_name): if not (all((app_key, token, board_name))): raise ValueError("app_key, token and board_name must be provided") else: self._app_key = app_key self._token = token self._board_name = board_name self.trello_handler = TrelloApi(self._app_key) self.trello_handler.set_token(self._token) super(TrelloParser, self).__init__() def output_moin(self, cards, members): output = "" for card in cards: output += "== " + card.get("name") + " ==" output += "Asignados: " + ", ".join( [members[m] for m in card.get("idMembers")]) output += card.get("desc") comments = self.trello_handler.cards.get_action( card.get("id"), filter="commentCard") if comments: output += "Comments:" for comment in comments: output += comment.get("memberCreator").get( "fullName") + "(" + comment.get("date") + ") :" output += comment.get("data").get("text") output += "\n" return output def parse_cards(self, list_name): members = self.trello_handler.boards.get(self._board_name, members="all").get("members") members = {m.get("id"): m.get("fullName") for m in members} list_id = None lists = self.trello_handler.boards.get_list(self._board_name, fields="name") for l in lists: if l.get("name") == list_name: list_id = l.get("id") cards = self.trello_handler.lists.get( list_id, cards="open", card_fields="name,desc,shortUrl,idMembers").get("cards") text = self.output_moin(cards, members) return text
def main(): """ Export Trello ard data to CSV for a given List. """ args = parse_args() trello = TrelloApi(args.trello_key) trello.set_token(args.trello_token) list_items = trello.lists.get_card(args.list_id) list_data = {} for card in list_items: card_data = {} for key, value in card.iteritems(): if unicode(key) == "closed" and value: continue if unicode(key) == "name": try: match = re.match("^\((.*)\)\s(.*)$", unicode(value)) card_data["estimate"] = unicode(match.group(1)) card_data["name"] = unicode(match.group(2)).encode("ascii", "ignore") except AttributeError: pass if unicode(key) == "dateLastActivity": match = re.match("^(\d{4}-\d{2}-\d{2})T\d{2}:\d{2}:\d{2}\.\d{3}Z", unicode(value)) card_data["last_activity_timestamp"] = unicode(match.group(1)) if unicode(key) == "shortUrl": card_data["short_url"] = unicode(value) if args.mode == "csv": csv_filename = "{0}.csv".format(args.list_id) with open(csv_filename, "a") as csv_file: csv_writer = csv.DictWriter(csv_file, card_data.keys()) csv_writer.writerow(card_data) elif args.mode == "burndown": if "estimate" in card_data: if card_data["last_activity_timestamp"] in list_data: list_data[card_data["last_activity_timestamp"]].append(float(card_data["estimate"])) else: list_data[card_data["last_activity_timestamp"]] = [float(card_data["estimate"])] if args.mode == "burndown": for date in list_data.keys(): print "{0}:{1}".format(date, sum(list_data[date])) return True
def main(args): """Does the main function need a docstring?!!?!""" confRoot = os.environ.get('TRELLO', None) if confRoot is not None: fn = confRoot + os.sep + 'conf' + os.sep + 'default.json' else: print('Environment is not set correctly') sys.exit(1) with open(fn) as f: conf = json.load(f) key = conf['key'] user = conf['user'] token = conf['token'] trello = TrelloApi(key, token) me = trello.members.get(user) id = me.get('id') b = trello.members.get_board(id) print(type(b)) '''s = json.dumps(b, indent=4, sort_keys=True) print(s)''' for i in b: print(i['id'] + ' || ' + i['name'])
def run(self): """main entry point""" # connect to Jira self.logger.debug("Connecting to Jira API") j_options = { 'server': self.config.JIRA_URL, } self.jira = JIRA(j_options, basic_auth=(self.config.JIRA_USER, self.config.JIRA_PASS)) if not self.jira: self.logger.error("Error connecting to Jira") raise SystemExit(1) # connect to Trello self.logger.debug("Connecting to Trello API") self.trello = TrelloApi(self.config.TRELLO_APP_KEY, token=self.config.TRELLO_TOKEN) if not self.trello: self.logger.error("Error connecting to Trello") raise SystemExit(1) self.logger.info("Connected to Trello") self.logger.debug("Getting Trello board") self.board = self.trello.boards.get(self.config.TRELLO_BOARD_ID) self.board_id = self.board['id'] self.logger.info("Using board '{n}' ({u}; id={i})".format(n=self.board['name'], u=self.board['url'], i=self.board_id)) self.logger.debug("Getting board lists") self.list_id = None for l in self.trello.boards.get_list(self.board['id']): if l['name'].lower() == self.config.TRELLO_DONE_LIST_NAME.lower(): self.list_id = l['id'] self.logger.info("Using done list {i}".format(i=self.list_id)) break if self.list_id is None: self.logger.error("ERROR: Unable to find list with name '{n}' on board.".format(n=self.config.TRELLO_DONE_LIST_NAME)) raise SystemExit(1) self.do_cards()
def main(args): """This is the main function""" confRoot = os.environ.get('TRELLO', None) if confRoot is not None: fn = confRoot + os.sep + 'conf' + os.sep + 'default.json' else: print('Environment is not set correctly') sys.exit(1) with open(fn) as f: conf = json.load(f) key = conf.get('key') user = conf.get('user') token = conf.get('token') trello = TrelloApi(key, token) me = trello.members.get(user) print("Full name: " + me.get('fullName')) print("Boards: " + str(me.get('idBoards'))) print("Organizations: " + str(me.get('idOrganizations'))) s = json.dumps(me, indent=4, sort_keys=True) print(s)
def create_webhook(callbackURL, idModel, description=None): trello = TrelloApi(TRELLO["AppKey"], TRELLO["Token"]) _call_and_check(trello.webhooks.new, callbackURL, idModel, description=description) print("New webhook was created")
def job(): trello = TrelloApi('API-KEY-HERE') #get cards from trello cards = trello.lists.get_card('LIST-ID-HERE') # open premade card_names main file in append mode (a+) to keep track of card names card_names = open('./card_names.txt', 'a+') # open premade tasks file in append mode (a+) to use for printer tasks = open('./tasks.txt', 'a+') # iterate over each card check that card name is NOT in the card_names file for obj in cards: # if name is in the card_names file do nothing if obj['id'] in open('card_names.txt').read(): print 'already in the master list' pass else: # add name into task file and the card_names file card_names.write(obj['id'] + '\n') tasks.write('\n\n\n\n\n' + obj['name'] + '\n\n\n\n\n:)') print "yo i'm printing" # print task file if there's content if os.stat('tasks.txt').st_size > 0: call(['lpr', '-o', 'fit-to-page', 'tasks.txt']) # clear task file f = open('tasks.txt', 'r+') f.truncate()
class TrelloParser(object): def __init__(self, app_key, token, board_name): if not(all((app_key, token, board_name))): raise ValueError("app_key, token and board_name must be provided") else: self._app_key = app_key self._token = token self._board_name = board_name self.trello_handler = TrelloApi(self._app_key) self.trello_handler.set_token(self._token) super(TrelloParser, self).__init__() def output_moin(self, cards, members): output = "" for card in cards: output += "== " + card.get("name") + " ==" output += "Asignados: " + ", ".join([members[m] for m in card.get("idMembers")]) output += card.get("desc") comments = self.trello_handler.cards.get_action(card.get("id"), filter="commentCard") if comments: output += "Comments:" for comment in comments: output += comment.get("memberCreator").get("fullName") + "(" + comment.get("date") + ") :" output += comment.get("data").get("text") output += "\n" return output def parse_cards(self, list_name): members = self.trello_handler.boards.get(self._board_name, members="all").get("members") members = {m.get("id"): m.get("fullName") for m in members} list_id = None lists = self.trello_handler.boards.get_list(self._board_name, fields="name") for l in lists: if l.get("name") == list_name: list_id = l.get("id") cards = self.trello_handler.lists.get(list_id, cards="open", card_fields="name,desc,shortUrl,idMembers").get("cards") text = self.output_moin(cards, members) return text
def trello2Email(apikey, tocken, boardId, TO, FROM, subject): trello = TrelloApi(apikey) trello.set_token(tocken) cards = trello.boards.get_card(boardId, fields=("name", "idList")) lists = trello.boards.get_list(boardId) bufList = StringIO() bufCard = StringIO() boardLists = [] boardcard = [] cadNumber = [] lis = 0 for list in trello.boards.get_list(boardId): member_card = dict() listName = list['name'] bufList.write(listName.encode('utf-8')) boardLists.append(bufList.getvalue()) bufList.truncate(0) lis = lis + 1 for card in trello.lists.get_card(list['id']): for member in card['idMembers']: if not member_card.has_key(member): member_card[member] = [] member_card[member].append(card) cad = 0 for memberId in member_card.keys(): member = trello.members.get(memberId) for card in member_card[memberId]: cardName = card['name'] memberInitials = member['initials'] bufCard.write( memberInitials.encode('utf-8') + ' : ' + cardName.encode('utf-8')) boardcard.append(bufCard.getvalue()) bufCard.truncate(0) cad = cad + 1 cadNumber.append(cad) html = getHtml.getHtmlFromBuf(boardLists, boardcard, cadNumber) sendEmail.py_mail(subject, html, TO, FROM)
def __init__(self): self.user = auth.user self.trello = TrelloApi(auth.key, auth.token) self.kl = self.trello.members.get_board(self.user) self.board_id = '' for item in self.kl: if item['name'] == auth.board: self.board_id = item['id'] self.all_lists = self.trello.boards.get_list(self.board_id)
def post_to_trello(freelance, tech, tech_not_confirmed, email): freelance_id = '5bc91cfdcaee543fd465743d' tech_matches_id = '5bc91d0bf7d2b839faaf71b8' email_matches_id = '5bc91d160d6b977c2b22e90e' tech_matches_not_confirmed_id = '5cb1ec921fa7ff624beebc4b' #budget_matches_id = '5bc91d1b4dc1245f1403812f' token = os.environ['TRELLO_TOKEN'] key = os.environ['TRELLO_API_KEY'] trello = TrelloApi(key, token) trello.set_token(token) _post(freelance, freelance_id, trello) _post(tech, tech_matches_id, trello) _post(tech_not_confirmed, tech_matches_not_confirmed_id, trello) _post(email, email_matches_id, trello) tag_cards(trello, tech_matches_id) tag_cards(trello, tech_matches_not_confirmed_id) tag_cards(trello, email_matches_id)
def authorize(self): self.app.log.debug('Authorizing a Trello user.') # validate required config parameters if not self.app.config.get('trello', 'auth_key'): raise error.ConfigError("Missing config parameter 'trello.auth_key'! " "Please run 'scrum-tools trello authorize' first! ") try: tl = TrelloApi(self.app.config.get('trello', 'auth_key')) url = tl.get_token_url('scrum-tools', expires='30days', write_access=True) cprint(os.linesep.join(["Please follow the link below and update these entries in the [trello] section " "of your scrum-tools config: ", " auth_key = %s" % self.app.config.get('trello', 'auth_key'), " auth_token = %s" % '<generated_token>']), 'green') cprint("URL: %s" % url, 'green') except RuntimeError as e: raise e
def trello2Email(apikey,tocken,boardId,TO,FROM,subject): trello = TrelloApi(apikey) trello.set_token(tocken) cards = trello.boards.get_card(boardId, fields=("name", "idList")) lists = trello.boards.get_list(boardId) bufList = StringIO() bufCard = StringIO() boardLists = [] boardcard = [] cadNumber = [] lis = 0 for list in trello.boards.get_list(boardId): member_card = dict() listName = list['name'] bufList.write(listName.encode('utf-8')) boardLists.append(bufList.getvalue()) bufList.truncate(0) lis = lis + 1 for card in trello.lists.get_card(list['id']): for member in card['idMembers']: if not member_card.has_key(member): member_card[member] = [] member_card[member].append(card) cad = 0 for memberId in member_card.keys(): member = trello.members.get(memberId) for card in member_card[memberId]: cardName = card['name'] memberInitials = member['initials'] bufCard.write(memberInitials.encode('utf-8') + ' : ' + cardName.encode('utf-8')) boardcard.append(bufCard.getvalue()) bufCard.truncate(0) cad = cad + 1 cadNumber.append(cad) html = getHtml.getHtmlFromBuf(boardLists, boardcard, cadNumber) sendEmail.py_mail(subject, html, TO, FROM)
def cli(ctx): ctx.obj.config = ConfigParser() ctx.obj.config.read(CYKLE_CONFIG_FILE) if len(ctx.obj.config.items()) <= 1: return ctx.obj.trello_api = TrelloApi(ctx.obj.config.get('trello', 'apikey'), ctx.obj.config.get('trello', 'token')) ctx.obj.github_api = Github( ctx.obj.config.get('github', 'username'), base64.b64decode(ctx.obj.config.get('github', 'password')))
def __init__(self, app_key, token, board_name): if not(all((app_key, token, board_name))): raise ValueError("app_key, token and board_name must be provided") else: self._app_key = app_key self._token = token self._board_name = board_name self.trello_handler = TrelloApi(self._app_key) self.trello_handler.set_token(self._token) super(TrelloParser, self).__init__()
def setUpAuth(): trello = TrelloApi(appKey) while True : try: print("Please visit the following website and copy the key:") print('https://trello.com/1/authorize?key=' + appKey + '&name=TVC_Commit&expiration=30days&response_type=token&scope=read,write') trelloToken = str(raw_input("Please enter key:\n")) trello.set_token(trelloToken) trello.tokens.get(trelloToken) break except Exception as e: print(e) print("Key Incorrect.\n\n") file = open('Token', mode="w") file.write(trelloToken) file.close() return trello
def create_boards(self): self.app.log.debug('Creating Trello boards.') # validate required config parameters if not self.app.config.get('trello', 'auth_key') or not self.app.config.get( 'trello', 'auth_token'): raise error.ConfigError( "Missing config parameter 'trello.auth_key' and/or 'trello.auth_token'! " "Please run 'scrum-tools trello authorize' first! ") # schema keys key_group = self.app.config.get('core', 'users_schema_key_group') key_trello = self.app.config.get('core', 'users_schema_key_trello') # organization organization = self.app.config.get('trello', 'organization') # boards setup board_admins_name = self.app.config.get('trello', 'board_admins') board_pattern = self.app.config.get('trello', 'board_pattern') board_lists = self.app.config.get('trello', 'board_lists') admins_group = self.app.config.get('trello', 'board_admins_group') # get the users user_repository = data.UserRepository(self.app.config) # create trello session tl = TrelloApi(self.app.config.get('trello', 'auth_key'), self.app.config.get('trello', 'auth_token')) # get the organization org = tl.organizations.get(organization) if not org: raise RuntimeError("Organization '%s' not found" % organization) # get all organization boards boards = dict( (b['name'], b) for b in tl.organizations.get_board(organization)) # create group boards for group in user_repository.groups(): board_name = board_pattern % int(group) board_admins = set(u[key_trello] for u in user_repository.users( lambda x: x[key_group] == admins_group)) board_members = set(u[key_trello] for u in user_repository.users( lambda x: x[key_group] == group)) self.__create_board(tl, org, board_name, set(board_lists), board_admins, board_members, boards) # create admins board board_admins = set(u[key_trello] for u in user_repository.users( lambda x: x[key_group] == admins_group)) board_members = set() self.__create_board(tl, org, board_admins_name, set(board_lists), board_admins, board_members, boards)
def testUsingNewApiTrello(): # trello = TrelloApi('') # https://pypi.org/project/trello/ # https: // pythonhosted.org / trello / examples.html # print(os.environ["TRELLO_KEY"]) config = TrelloConfig() tre = TrelloApi(config.key, config.token) #print('t:',tre.boards.get_card(config.idBoard)) print('a:', tre.boards.get_action(config.idBoard)) print('x:', tre.boards.get_list(config.idBoard))
def trello(oled): ourkey = open('.trello-screen-api-key').read(); ourtoken = open('.trello-screen-token').read(); ourlist = open('.trello-screen-list').read(); trello = TrelloApi(ourkey, token=ourtoken) cards = trello.lists.get_card(ourlist) index = 0 font2 = ImageFont.truetype('redalert.ttf', 12) with canvas(oled) as draw: draw.text((0,0), "Working on " + str(len(cards)) + " things:", font=font2, fill=255) while index < len(cards) and index < 4: draw.text((12,13+(index*13)),cards[index]['name'], font=font2, fill=255) index = index + 1
def create_issue(self, request, group, form_data, **kwargs): description = TrelloSentry.reformat_to_markdown( form_data['description']) try: trello = TrelloApi(self.get_option('key', group.project), self.get_option('token', group.project)) card = trello.cards.new(name=form_data['title'], desc=description, idList=form_data['board_list']) return '%s/%s' % (card['id'], card['url']) except RequestException, e: raise forms.ValidationError( _('Error adding Trello card: %s') % str(e))
def cad_pedido_trello(dados, valor_total): trello = TrelloApi( '3e07bd7f00974e1c71db3f0d30f3d50c', '55fb23e337aa599c137b1d23c225d1f5825a6274bf010c525a5c43ffe200b906') produtos = " " for produto in dados.produtos.all(): produtos = produtos + '\n' + str(produto) card = trello.cards.new( 'Pedido ' + str(dados.id), '5cdeee36a3d935459b57d978', 'Cliente: \n\n' + 'nome: ' + str(dados.user.username) + '\n' + 'email: ' + str(dados.user.email) + '\n\n' + 'Componentes: \n' + produtos + '\n\n' + 'Valor Total: ' + str(valor_total)) return card['id']
def workon(): TRELLO_API_KEY, TRELLO_TOKEN = get_creds(name="workon") trello = TrelloApi(TRELLO_API_KEY) trello.set_token(TRELLO_TOKEN) b=trello.lists.get_card(DOINGLIST) #b=trello.members.get_card(USERNAME, fields='name,idShort,shortUrl,idBoard,idList') print "My trello cards:" for i in b: print i['name'] +'- ID:'+ color.BLUE +str(i['idShort']) +color.END input = raw_input("Choose card to work on: ") print "Card chosen is %s \n" % input val ='' for i in b: if str(i['idShort']) == input : c=trello.boards.get(i['idBoard'], fields='name,shortUrl') d=trello.lists.get(i['idList'], fields='name') val = i['name'] + '\n' + str(i['idShort']) + '\n' + str(c['shortUrl']) + '\n' + str(d['name']) trelloconf = os.path.expanduser(os.path.join("~", ".trelloenv")) f = open(trelloconf, "w+") f.seek(0) f.truncate() f.write(val) f.close()
def on_post(self, req, resp, token): trello = TrelloApi(trelloconfig.api_key, token=trelloconfig.token) trello_token = trello.get_token_url('My App', expires='30days', write_access=True) storage = ZODB.FileStorage.FileStorage('trees/'+token+'.fs') db = ZODB.DB(storage) connection = db.open() root = connection.root if hasattr(root, 'tree'): tree = root.tree else: resp.body = "Initialize first" connection.close() db.close() storage.close() return lst = list(btree.inorder(tree)) connection.close() db.close() storage.close() if len(lst)> 0: id_new = trello.boards.new_list('Le5vKw7H', token)['id'] for card in lst: trello.cards.new(card, id_new)
""" print "===== Start =====\n" print "=Import Lib=\n" import codecs import time from trello import TrelloApi print "=Load Board=\n" fanbo_key="be7282d1bcd63a4cead02f61a11d2698" #apikey="7da5326d1344701e69904bf2972bbb35" #trello = TrelloApi(apikey) trello = TrelloApi(fanbo_key) #trello.get_token_url('My App', expires='30days', write_access=True) token="087626291066fcdb5591e0c2ca03ea0e221c26ccee2fc5e6c0b3ae3bbe99dbe4" fanbo_token="72eaa424bb19dab5d9a0fb27d7ffe9e112c14a2d0e3c633835f8cdc33c0cecc1" #trello.set_token(token) trello.set_token(fanbo_token) board_id=trello.tokens.get_member(fanbo_token)["idBoards"] #board_id=trello.tokens.get_member(token)["idBoards"] print "=Get Card=\n" card_info=trello.boards.get_card(board_id[1]) #trello.boards.get_action(board_id[1]) member_list=trello.boards.get_member(board_id[1]) member_id=[] member_name=[]
from trello import TrelloApi ns = {} execfile('.trello-api-keys', ns) client = TrelloApi(ns['key']) client.boards.get_list('OWnNA1h1') client.lists.new_card client.get_token_url # put token manually into file execfile('.trello-api-keys', ns) client.set_token(ns['token']) for index, rule in enumerate(nns['rules']): client.lists.new_card('52b15e53abfcca855201ffd4', 'Rule #%d: %s' % (index+1, rule))
# test of trello python integration # pypi page: # documentation: https://pythonhosted.org/trello/index.html from trello import TrelloApi myTrello = TrelloApi("5c0d5de81fad5b32bb71379cba2f7777") token = myTrello.get_token_url('My App', expires='30days', write_access=True)
#! /usr/bin/env python ## https://pypi.python.org/pypi/trello ## See also https://pythonhosted.org/trello/trello.html from trello import TrelloApi from requests.exceptions import HTTPError import sys, os, re assert(os.path.exists('APPKEY')) assert(os.path.exists('TOKEN')) ## To get an app key, go here: ## https://trello.com/app-key APPKEY = open('APPKEY').readlines()[0].strip() trello = TrelloApi(APPKEY) ## To get a new token, call this: ## trello.get_token_url(APPKEY, write_access=False) ## and put the resulting URL in a browser TOKEN = open('TOKEN').readlines()[0].strip() trello.set_token(TOKEN) try: BOARDID = sys.argv[1] except IndexError: print "ERROR: Please provide a board id in the command line" sys.exit(-1) try:
import csv from trello import TrelloApi with open('data.csv', 'rb') as csvfile: tapi = raw_input("What is your trello app key? - ") trello = TrelloApi(tapi) # get API key from https://trello.com/app-key print trello.get_token_url('Kanboard Importer', expires='30days', write_access=True) key = raw_input("What is the token? - ") trello.set_token(key) board = raw_input("What is the board ID - ") tboard = trello.boards.get(board) print trello.boards.get_list(board) listid = raw_input("What is the list ID - ") # Don't use idBoard, use id projectname = raw_input("What is the name of the Kanboard Project? - ") csvreader = csv.reader(csvfile, delimiter=',') for row in csvreader: Project = row[1] Swimlane = row[4] Name = row[13] if Project == projectname: print Name trello.cards.new(Name, listid)
def get_trello_app_token(app_key): trello = TrelloApi(app_key) print (trello.get_token_url('Trello2Text', expires='never', write_access=True)) print ("Now got to the url above and authorize the app")
def connect(self, app_key, token=None): trello = TrelloApi(app_key) if token: trello.set_token(token) return trello
""" from fogbugz import FogBugz import os from trello import TrelloApi __author__ = "Jacob Sanford" __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "Jacob Sanford" __email__ = "*****@*****.**" __status__ = "Development" # Explicit testing / error would be nice here. trello = TrelloApi(os.environ['TRELLO_API_KEY']) if not os.environ['TRELLO_USER_TOKEN']=='' : trello.set_token(os.environ['TRELLO_USER_TOKEN']) fb = FogBugz(os.environ['FOGBUGZ_URL']) fb.logon(os.environ['FOGBUGZ_USER'],os.environ['FOGBUGZ_PASSWORD']) # Find cards in board with specified label. for cur_card in trello.boards.get_card(os.environ['TRELLO_BOARD_TO_PARSE']): for cur_card_label in cur_card['labels']: if cur_card_label['name'] == os.environ['TRELLO_LABEL_TO_PARSE'] : # Create case in Fogbugz if not exist fogbugz_response=fb.search(q='tag:"' + cur_card['id'] + '"',cols='ixBug') if len(fogbugz_response.cases) == 0 : fb.new(sTitle=cur_card['name'], sTags=cur_card['id'], ixProject=os.environ['FOGBUGZ_DEFAULT_PROJECT'])
group.add_argument('--intermediate', action='store_true', help='Returns a random Easy or Intermediate Challenge') group.add_argument('--hard', action='store_true', help='Returns ANY Challenge') args = parser.parse_args() logging.warning("Reading Yaml from %s", args.file) authDetails = getAuthDetailsFromYaml(args.file); logging.warning("Authenticating Reddit") r = praw.Reddit(user_agent='daily-programmer-selector') logging.warning("Querying Reddit") dailyQuery = get_daily_query(args) submissions = list(r.get_subreddit('dailyprogrammer').search(dailyQuery, sort="new")) randomSubmission = random.choice(submissions) logging.warning("Found Title : %s", randomSubmission.title.encode('ascii' , 'ignore')) logging.warning("URL : %s", randomSubmission.url.encode('ascii' , 'ignore')) if args.trello == True : logging.warning("Authenticating Trello") trello = TrelloApi(authDetails.get("api_key")) trello.set_token(authDetails.get("token_key")) logging.warning("Adding Card to Trello Board %s", authDetails.get("trello_board")) allBoards = trello.members.get_board(authDetails.get("trello_username")) board = getBoardWithName(allBoards, authDetails.get("trello_board")) lists = trello.boards.get_list(board.get("id")) list = getListWithName(lists, authDetails.get("trello_list")) card = trello.lists.new_card(list.get("id"), randomSubmission.title.encode('ascii' , 'ignore'), desc=randomSubmission.selftext.encode('ascii' , 'ignore')) logging.warning("Finished")
from trello import TrelloApi import sys # You can use my API key, or get yours at https://trello.com/1/appKey/generate API_KEY = 'b51d325ae73a0264377da49c031422cf' # Initialize Trello try: with open('token.txt') as f: TOKEN = f.readlines()[0].strip() except IOError: TOKEN = None trello = TrelloApi(API_KEY) if not TOKEN: print 'Visit this, and save your token in token.txt' print trello.get_token_url('My App', expires='30days', write_access=True) sys.exit(0) trello.set_token(TOKEN) def get_list_id_from_name(name): return [ l['id'] for l in trello.boards.get_list('SkHEoGHF') if l['name'].startswith(name)][0] def move_cards(from_list, to_list): for card in trello.lists.get_card(from_list): trello.cards.update_idList(card['id'], to_list)
def init(ctx): if len(ctx.obj.config.items()) > 1: print 'Cykle is already initialized' exit(0) # get trello api key trello_apikey = raw_input('Trello API Key: ') # get trello token trello_api = TrelloApi(trello_apikey) token_url = trello_api.get_token_url('Cykle', expires='30days', write_access=True) webbrowser.open(token_url) trello_token = raw_input('Trello Token: ') # get trello organization trello_orgnization = raw_input('Trello Organization: ') # get trello board id trello_board_name = raw_input('Trello Board Name: ') trello_api = TrelloApi(trello_apikey, trello_token) # get all boards of the organization # if it is not a member of the organiztion, abort try: boards = trello_api.organizations.get_board(trello_orgnization) except requests.exceptions.HTTPError as e: if e.response.status_code == 401: print 'Aborted. You MUST be member of the organization(%s)' % trello_orgnization exit(0) # filter the boards by name for b in boards: if b['name'] == trello_board_name: trello_board_id = b['id'] # get trello list per issue step trello_list_in_progress = raw_input('Trello List for IN_PROGRESS: ') trello_list_code_review = raw_input('Trello List for CODE_REVIEW: ') trello_list_closed = raw_input('Trello List for CLOSED: ') # github repository info github_owner_name = raw_input('Github Owner Name: ') github_repo_name = raw_input('Github Repository: ') github_username = raw_input('Github Username: '******'Github Password: '******'Develop Branch: ') # generate cykle config file print 'generating cykle config file...' ctx.obj.config.add_section('trello') ctx.obj.config.set('trello', 'apikey', trello_apikey) ctx.obj.config.set('trello', 'token', trello_token) ctx.obj.config.set('trello', 'orgnization', trello_orgnization) ctx.obj.config.set('trello', 'board_id', trello_board_id) ctx.obj.config.set('trello', 'list_in_progress', trello_list_in_progress) ctx.obj.config.set('trello', 'list_code_review', trello_list_code_review) ctx.obj.config.set('trello', 'list_closed', trello_list_closed) ctx.obj.config.add_section('github') ctx.obj.config.set('github', 'owner_name', github_owner_name) ctx.obj.config.set('github', 'repo_name', github_repo_name) ctx.obj.config.set('github', 'username', github_username) ctx.obj.config.set('github', 'password', base64.b64encode(github_password)) ctx.obj.config.add_section('repository') ctx.obj.config.set('repository', 'develop_branch', develop_branch) with open(CYKLE_CONFIG_FILE, 'w') as cfgfile: ctx.obj.config.write(cfgfile)
from sys import argv from trello import TrelloApi import settings import sources trello = TrelloApi(settings.KEY) trello.set_token(settings.TOKEN) if __name__ == '__main__': if not len(argv) > 1: raise Exception('You must provide the name of a data source class to use.') data_source = getattr(sources, argv[1]) if data_source is None: raise Exception('The data source class provided could not be found.') data_source(trello).sync_list()
card_id = int(card_id, 16) create_time = time.strftime('%Y-%m-%d', time.localtime(card_id)) return create_time def is_in_week( create_time ): create_time = datetime.strptime(create_time, '%Y-%m-%d').date() dt = datetime.today().date() start = dt - timedelta(days=dt.weekday()) if create_time >= start and create_time <= dt: return True else: return False trello_report = open('trello_report.html', 'w') trello = TrelloApi('a4ae903d87894a87ba4c6a7b7bf617bd') token_url = trello.get_token_url('Trello Application', expires='30days', write_access=True) user = raw_input('Enter your full name: ') user_name = raw_input('Enter trello user name: ') print '\nNavigate to the following webpage (login if necessary) and click "Allow" to receive your Trello token:\n' print token_url user_token = raw_input('\nEnter your token: ') trello.set_token(user_token) boards = trello.members.get_board(user_name) enumerated_boards = [] print '\nThese are the boards available on your account:\n'