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 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 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 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 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 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 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 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 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(): 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 trello_init(): trello = TrelloApi(TRELLO_APP_KEY) try: trello.set_token(open('.token.txt').read().strip()) except IOError: token_url = trello.get_token_url('Trello ', expires='never', write_access=True) print "Enter following URL in your browser:", token_url token = raw_input("Enter token please:") open('.token.txt', 'w').write(token) trello.set_token(token) return trello
def init(cls, organization): trello = TrelloApi(TRELLO_APP_KEY) try: trello.set_token(open('.token.txt').read().strip()) logger.debug("Trello token loaded") except IOError: token_url = trello.get_token_url('Trello ', expires='never', write_access=True) print("Enter following URL in your browser:", token_url) token = raw_input("Enter token please:") open('.token.txt', 'w').write(token) trello.set_token(token) return cls(trello, organization)
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
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 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 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 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 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()
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()) trello = TrelloApi(args['client_api_key']) trello.set_token(args['token']) converter = TrelloConverter(trello, args['board_id']) template = ''' # {{ title }} {% for board_list in board_lists %} ## {{ board_list.name }} {% for card in board_list.cards %} - {{ card.name }} {% if card.comments %} {% for comment in card.comments %} - comment by {{ comment.author }}: {{ comment.text }} {% endfor %} {% endif %}
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()
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)
data = json.load(json_object) boardId = data["actions"][0]["data"]["board"][ "id"] # ID of the board we're working on print( "Copy and paste the following link in your web browser to get a new token." ) print( trello.get_token_url("Similar Label Detector", expires="30days", write_access=True)) # visit site to get 64-character token # token given by website auth_token = "744be46a0777522b10e26f42a819274dcbdc490bfc6d927960dc555d0fdb94b7" trello.set_token(auth_token) cards = Cards(app_key, auth_token) boards = Boards(app_key, auth_token) cardIds = [] # empty list where we will store card ID's label_names = [] # empty list where we will store unmodified label names label_names_lc = [] # empty list where we will store lowercase label names print( "\nList of cards, their respective ID's, and their respective label names:" ) for x in range(0, len(boards.get_card(boardId))): # 0 to 9, because 10 cards y = boards.get_card(boardId)[x] # get every individual card's info card = y["name"] # get card's description
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']) # Get ixBug value fogbugz_response=fb.search(q='tag:"' + cur_card['id'] + '"',cols='ixBug')
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=[] for i in range(len(member_list)): member_id.append(member_list[i]['id']) member_name.append(member_list[i]['fullName'])
def trello(): result = request.form player = db.session.query(Player).get(1) trello = TrelloApi(TRELLO_KEY) trello.set_token(TRELLO_TOKEN) #Handle user inputs if result.get("archive"): cardid = result.get("id") trello.cards.update_closed(cardid, "true") addPoints(db, 0.1, "Archived a card") if result.get("complete"): name = result.get("name") m = re.search("\((.+)\)", name) if m: points = float(m.group(1)) else: points = float("0.25") addPoints(db, points, "Trello task: " + name) cardid = result.get("id") cardGrouping = result.get("grouping") if cardGrouping == "Home": done = HOME_DONE_LIST else: done = WORK_DONE_LIST trello.cards.update_idList(cardid, done) #get card lists homeCards = trello.lists.get_card(HOME_TODAY) if len(homeCards) == 0: homeCards = trello.lists.get_card(HOME_WEEK_LIST) if len(homeCards) == 0: homeCards = trello.lists.get_card(HOME_NEXT_WEEK) workCards = trello.lists.get_card(WORK_TODAY) if len(workCards) == 0: workCards = trello.lists.get_card(WORK_WEEK_LIST) if len(workCards) == 0: workCards = trello.lists.get_card(WORK_NEXT_WEEK) doneCards = trello.lists.get_card(HOME_DONE_LIST) doneCards += trello.lists.get_card(WORK_DONE_LIST) for card in homeCards: card["grouping"] = "Home" for card in workCards: card["grouping"] = "Work" if not datetime.datetime.today().weekday in ( 5, 6) and 9 <= datetime.datetime.now().hour <= 18: cards = homeCards + workCards else: cards = homeCards for card in cards: m = re.search("\((.+)\)", card["name"]) if m: card["points"] = float(m.group(1)) else: card["points"] = 0.25 cards = sorted(cards, key=lambda c: c["points"]) doneCards = sorted(doneCards, key=lambda c: c["dateLastActivity"], reverse=True) return render_template("trello.html", cards=cards, doneCards=doneCards, player=player)
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 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))
from trello import TrelloApi import json from datetime import datetime import datetime TRELLO_APP_KEY='b730b6c72f876470a8c4cbf5ebe41dc0' trello=TrelloApi(TRELLO_APP_KEY) #print trello.get_token_url('YellowFood', expires='90days', write_access=True) user_token='cbecb81059cebb2d026afa70977c99834a51b4c53343f4cbc280a0ad69549943' trello.set_token(user_token) boards = trello.boards.get('5a0068aabd9f13a3c7e28b7e') print boards['name'] print boards['labelNames'] lists = trello.boards.get_list('5a0068aabd9f13a3c7e28b7e') cards = trello.boards.get_card('5a0068aabd9f13a3c7e28b7e') for l in lists: print l['name'] date = datetime.date.today()
from trello import TrelloApi trello = TrelloApi('********************************') trello.set_token( '****************************************************************') boardid = '************************' board = trello.boards.get(boardid) cards = trello.boards.get_card(boardid) trello_member = trello.boards.get_member(boardid) member = {i['id']: i['fullName'] for i in trello_member} count = {i['id']: 0 for i in trello_member} for card in cards: for m in card['idMembers']: count[m] += 1 for m in count: if count[m] != 0: print member[m], str(count[m])
from trello import TrelloApi from config import * from messages import * trello = TrelloApi(TRELLO_APP_KEY) trello.set_token(TRELLO_TOKEN) board = trello.boards.get(board_id=TRELLO_MOSCOW_BOARD_ID) standart_list = trello.lists.get(TRELLO_STANDART_LIST_ID) vegetable_list = trello.lists.get(TRELLO_VEGETABLE_LIST_ID) light_list = trello.lists.get(TRELLO_LIGHT_LIST_ID) def add_card(order, user): if order.cuisine == CLASSIC: list = TRELLO_STANDART_LIST_ID elif order.cuisine == VEGETABLE: list = TRELLO_VEGETABLE_LIST_ID else: list = TRELLO_LIGHT_LIST_ID trello.lists.new_card( list, TRELLO_CARD_NAME % (order.persons_count, order.dinners_count), TRELLO_CARD_DESCRIPTION % (user.city, user.address, user.name, user.phone))
# 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) later_list = get_list_id_from_name('Later This Week')
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' i = 1 for board in boards: for key, value in board.items(): if key == 'name': enumerated_boards.append(value) print '(%s) ' % i + value i += 1 board_number = raw_input('\nEnter the board number for which you want generate a report: ')
#Vitor Daynno 16/06/2017 # -*- coding: utf-8 -*- from pymongo import MongoClient from trello import TrelloApi from Config import Config import random cliente = MongoClient('localhost', 27017) banco = cliente['Pontuacao'] tabela = banco['tarefas'] config = Config() trello = TrelloApi(config.get_Api_Key(), 'none') #API Key trello.set_token(config.get_Token()) #Token try: id = tabela.find_one({"_id": { "$exists": True }}, sort=[("_id", -1)])["_id"] + 1 except: id = 0 for quadro in config.get_Quadros(): board = trello.boards.get(str(quadro)) print "\nQuadro: " + board["name"] lista = trello.boards.get_list(quadro) print ' Lista: ' + lista[len(lista) - 2]["name"] cards = trello.lists.get_card(lista[len(lista) - 2]["id"]) for card in cards: print ' Card: ' + card["name"] card_Detalhes = trello.cards.get_action(card["id"])
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: cards = trello.boards.get_card(BOARDID) lists = trello.boards.get_list(BOARDID) except HTTPError, e: message = 'Unknown HTTPError' if e.message.startswith('400'): message = 'Undefined HTTPError (bad board id?)' if e.message.startswith('401'):
from trello import TrelloApi from secrets import trello_api_key, trello_api_secret, trello_token, trello_token_secret, trello_crm_board_id, trello_crm_list_id, trello_template, trello_checklist from goto import with_goto from tinder_bot import TinderAutoSwipeBot from utils import get_utf8_contents, create_trello_card trello = TrelloApi(trello_api_key) trello.set_token(trello_token_secret) @with_goto def main(): # Call the Bot bot = TinderAutoSwipeBot() # Start Login Process bot.login() print( '---------------------------------------------------------------------------------------' ) print( 'STEP 1: Kindly login to your Tinder account manually in newly open browser screen. ' 'Allow all required permission location, notification etc') print('STEP 2: One You done with login. Input Yes or 1 and Hit Enter Key') print('STEP 3: Enjoy! Auto Swiping :)') print( '---------------------------------------------------------------------------------------' ) # Start the Auto Liking / Disliking label.begin
class MailChimpCampaignCreator(object): 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 get_cards_to_send(self): return self.trello.lists.get_card('5bb1e965e5336c5390e7e505') def create_campaigns(self, trello_cards, in_flask=False): for card in trello_cards: if self.validate_links(card) and self.validate_email(card): segments = self.get_list_segments(card) data_dict = {} data_dict['type'] = 'regular' data_dict['content_type'] = 'multichannel' data_dict["recipients"] = { 'list_id': self.audience_id, 'segment_opts': { 'match': 'any' } } # Here is a stack overflow link explaining how to # create dynamic segments because the mailchimp api docs # doesn't explain how to do it # #https://stackoverflow.com/questions/35785278/create-campaign-with-dynamic-segment-using-mailchimp-api-v3-0 data_dict["recipients"]['segment_opts']['conditions'] = [{ "condition_type": "Interests", 'op': 'interestcontains', 'field': self.interest_category_id, 'value': segments }] data_dict['settings'] = { "title": card['name'], "subject_line": card['name'], "from_name": "FeastFlow", "reply_to": '*****@*****.**' } screenshot_url = self.get_screenshot(card, in_flask) if screenshot_url: html = premium_w_screenshot else: html = premium_no_screenshot html.encode('utf-8') html = html.replace("%IMAGE%", screenshot_url) html = html.replace("%TITLE%", card['name']) html = html.replace("%CONTENT%", self.get_card_content(card)) # campaign = self.mailchimp_client.campaigns campaign = self.mailchimp_client.campaigns.create(data_dict) # campaign.content.get(campaign.campaign_id) self.mailchimp_client.campaigns.set_content( campaign['id'], {'html': html}) # campaign.content.update( # campaign.campaign_id, {'html': html}) # Old code that would schedule a campaign for the free list # if card['badges']['checkItemsChecked'] == 1: # checkedItems = self.trello.checklists.get_checkItem( # card['idChecklists'][0]) # # get date to send # time_str = checkedItems[0]['name'].lower().strip('send on ') # mdy = time_str.split('/') # # set for 6pm est on date given # schedule_time = datetime( # int(mdy[2]), int(mdy[0]), int(mdy[1]), 17) # local = pytz.timezone ("America/Atikokan") # local_dt = local.localize(schedule_time, is_dst=None) # utc_schedule_time = local_dt.astimezone(pytz.utc) # free_campaign = self.mailchimp_client.campaigns # data_dict['type'] = 'regular' # data_dict['recipients'] = {'list_id': self.free_list_id} # free_campaign.create(data_dict) # free_campaign.content.get(campaign.campaign_id) # free_campaign.content.update( # free_campaign.campaign_id, {'html': html}) # free_campaign.actions.schedule( # free_campaign.campaign_id, # {'schedule_time': utc_schedule_time}) def get_list_segments(self, trello_card): segments = [] for label in trello_card['labels']: segments.append(self.segments[label['name'].lower()]) return segments def get_screenshot(self, trello_card, in_flask=False): attachment = self.trello.cards.get_attachment(trello_card['id']) try: # if an attachment exists and its an image # do not get a screenshot if attachment[0]["url"][-3] == 'png': return attachment[0]["url"] else: # if its not an image then raise a key error so # we can hit the exception below and get a screenshot raise KeyError except (KeyError, IndexError): try: url_regex = r'URL: <https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)>' url = re.search( url_regex, str(trello_card['desc'].encode('utf-8'))).group() url = url.strip('URL: <') url = url.strip('>') if in_flask: chrome_options = Options() chrome_options.binary_location = \ os.environ['GOOGLE_CHROME_BIN'] chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome(executable_path=str( os.environ.get('CHROMEDRIVER_PATH')), chrome_options=chrome_options) else: driver = webdriver.Chrome(chrome_driver_path) driver.get(url) time.sleep(3) # wait for page to load driver.save_screenshot('lead_screenshot.png') driver.quit() # resize image with open('lead_screenshot.png', 'r+b') as f: with Image.open(f) as image: img = resizeimage.resize_width(image, 600) img.save('lead_screenshot.png', image.format) ss_path = os.path.abspath('lead_screenshot.png') self.upload_file_to_trello_card(trello_card['id'], ss_path) os.remove(ss_path) return self.trello.cards.get_attachment( trello_card['id'])[0]["url"] except AttributeError: card_name = trello_card['name'].encode('utf-8') print(f'Failed to get screenshot for {card_name}') return '' def get_card_content(self, trello_card): return self.markdown2html.convert(trello_card['desc']) def upload_file_to_trello_card(self, card_id, file_path): """ Upload a local file to a Trello card as an attachment. File must be less than 10MB (Trello API limit). :param card_id: The relevant card id :param file_path: path to the file to upload Returns a request Response object. It's up to you to check the status code. """ ATTACHMENTS_URL = 'https://api.trello.com/1/cards/%s/attachments' params = {'key': self.trello_key, 'token': self.trello_token} files = {'file': open(file_path, 'rb')} url = ATTACHMENTS_URL % card_id requests.post(url, params=params, files=files) def validate_links(self, trello_card): url_regex = r'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)' links = re.finditer(url_regex, str(trello_card['desc'].encode('utf-8'))) for link in links: try: request = requests.get(link.group(0)) except ConnectionError: self.__move_card_to_broken_link_column(trello_card) return False if request.status_code in [200, 403, 999, 406]: continue else: self.__move_card_to_broken_link_column(trello_card) card_name = trello_card['name'].encode('utf-8') print( f"Broken Link in {card_name} with status code {request.status_code}: {link.group(0)}" ) return False return True def validate_email(self, trello_card): zb.initialize(os.environ.get('ZB_API_KEY')) # client = neverbounce_sdk.client(api_key=self.never_bouce_apy_key) email_regex = r'[\w\.-]+@[\w\.-]+' emails = re.findall(email_regex, str(trello_card['desc'].encode('utf-8'))) for address in emails: if not address[-1].isalpha(): address = address[:-1] resp = zb.validate(address) # resp = client.single_check(address) if resp.status not in [ZBValidateStatus.valid]: self.__move_card_to_broken_link_column(trello_card) card_name = trello_card['name'] print( f"Email Bounced in {card_name}: {address} with return code '{resp.status}" ) return False return True def __move_card_to_broken_link_column(self, trello_card): # move card to broken link column self.trello.cards.update_idList(trello_card['id'], "5c55ae09f1d4eb1efb039019")
def connect(self, app_key, token=None): trello = TrelloApi(app_key) if token: trello.set_token(token) return trello
import os import ssl from datetime import timedelta from time import sleep from trello import TrelloApi from lib.config import config from lib.mailer import MailReceiver, MailSender trello = TrelloApi(config.secure.trello.api_key) trello_token = os.environ.get("TRELLO_TOKEN") trello.set_token(trello_token) ssl_context = ssl.create_default_context() mailer = MailSender( address=config.secure.sender.address, password=config.secure.sender.password, server_address=config.secure.sender.server_address, port=config.secure.sender.server_port, ssl_context=ssl_context, ) receiver = MailReceiver( address=config.secure.sender.address, password=config.secure.sender.password, server_address=config.secure.sender.server_address, ssl_context=ssl_context, ) while True:
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 = [] for i in range(len(member_list)): member_id.append(member_list[i]['id']) member_name.append(member_list[i]['fullName']) list_info = trello.boards.get_list(board_id[1])
from trello import TrelloApi #ref docs # https://pythonhosted.org/trello/trello.html#trello.Boards.get_list_filter #created by Michael Milord trello = TrelloApi("596e2ae73702acd0ae6eb0f8f0ebaf52") trello.set_token( "2e4eada2861e709648fa4fb8b824e3287b78888eae838521a51e61b4058847ed") #functions# def getLabels(board): result = {} lbl = board['labelNames'] for i in lbl: if lbl[i] != '': result[lbl[i]] = i return result def getCategories(boardID): result = {} foo = trello.boards.get_list(boardID) for i in foo: for j in i: #print j,i[j] result[i['name']] = i['id'] #print "" return result
def get_client(self): client = TrelloApi(self.config.get('Access', 'api_key'), ) client.set_token(self.config.get('Access', 'token')) return client