def authenticate(self): #creds = self.get_creds() client = trello.TrelloClient( api_key=self.config['trello_api_key'], api_secret=self.config['trello_api_secret'], token=self.config['trello_auth_token']) return client
def step_2(request): try: trello_client = trello.TrelloClient(api_key=request["trello_api_key"], token=request["trello_api_token"]) tboard_daily = fetch_tboards_by_name(trello_client, request["message"])[0] tlists = tboard_daily.list_lists(list_filter="open") last_tlist = tlists[-1] tlists = tlists[:-1] execute_sql( "UPDATE users SET trello_board='{}', step=3 WHERE vk_id={}".format( request["message"], request["vk_id"]), POSTGRES_CONNECTION_PARAMS) message = "Отлично. Теперь выбери список, в котором ты указываешь задачи на день.\n\n" \ "Вот они, слева направо: " for tlist in tlists: message = message + tlist.name + ", " message += last_tlist.name keyboard = None if len(tlists) < 9: tlists = [tlist.name for tlist in tlists] tlists.append(last_tlist.name) keyboard = labels_to_keyboard(tlists) send_message(request["vk_id"], message=message, keyboard=keyboard) except IndexError: send_message(request["vk_id"], message="Выбери доску, с которой нужно брать задачи")
def __init__(self, pull, board): self.client = trello.TrelloClient(api_key=settings.API_KEY, token=settings.API_TOKEN) self.pull = pull self.board = board self.trello_list = [x for x in self.board.open_lists() if x.name == settings.LIST_NAME][0] self.label = self.get_or_create_label() self.urls = self.get_commits()
def daily_update(): users = execute_sql("SELECT * FROM users", POSTGRES_CONNECTION_PARAMS) for user in users: try: trello_client = trello.TrelloClient(api_key=user["trello_api_key"], token=user["trello_api_token"]) tboard_daily = fetch_tboards_by_name(trello_client, user["trello_board"])[0] tlist_daily = fetch_tlists_by_name(tboard_daily, user["trello_list"])[0] checklists_daily_dict = fetch_checklists_by_tlist(tlist_daily) percent_done_today = calculate_percent_done(checklists_daily_dict) percent_done_total = (user["days"] * user["total_percent"] + percent_done_today) / (user["days"] + 1) message = "Выполненных задач за сегодня: " + str(percent_done_today) + "%\n" + \ "В день выполняется в среднем: " + str(percent_done_total) + "%" send_message(user["vk_id"], message=message) execute_sql( "UPDATE users SET days={}, total_percent={} WHERE vk_id={}". format(user["days"] + 1, percent_done_total, user["vk_id"]), POSTGRES_CONNECTION_PARAMS) except: pass
def _initialize_connection(self): """ This connects to trello, and searches for the specified board. It raises an exception of the connection is not successful. If no board is specified it prints a list of boards and their ids. :return: """ # Initialize trello client print("Inside Init") self._client = trello.TrelloClient( api_key=self._config['Trello API Keys']['trello_api_key'], api_secret=self._config['Trello API Keys']['trello_api_secret'], # token='your-oauth-token', # token_secret='your-oauth-token-secret' ) # Ensure that authorization passed, and that we can retrieve the board try: self._game_board = self._client.get_board( self._config['Trello Board Settings']['trello_board_id']) except trello.Unauthorized: print( "Trello authorization failed. Check api key and api secret.") raise except trello.ResourceUnavailable: print("Trello couldn't retrieve the board.", "Board id needs to be set to an existing board:") print(' ', 'Board ID'.ljust(24), 'Board Name') for board in self._client.list_boards(): print(' ', board.id.rjust(24), board.name) raise
def auth(): client = trello.TrelloClient(keys.api_key, token=keys.oauth_token) #get all the boards boards = client.list_boards() #only want the tasks board return boards
def authenticate(self): creds = self.get_creds() client = trello.TrelloClient(api_key=creds['trello_api_key'], api_secret=creds['trello_api_secret'], token=creds['trello_auth_token']) del creds return client
def step_1(request): try: trello_api_key, trello_api_token = request["message"].split(" ") trello_client = trello.TrelloClient(api_key=trello_api_key, token=trello_api_token) trello_boards = trello_client.list_boards(board_filter="open") last_board = trello_boards[-1] trello_boards = trello_boards[:-1] execute_sql( "UPDATE users SET trello_api_key='{}', trello_api_token='{}', step=2 WHERE vk_id= {}" .format(trello_api_key, trello_api_token, request["vk_id"]), POSTGRES_CONNECTION_PARAMS) message = "Ура, все получилось!\n\n" \ "Теперь отправь название доски, с которой нужно брать задачи.\n\n" \ "Твои доски: " for board in trello_boards: message = message + board.name + ", " message += last_board.name keyboard = None if len(trello_boards) < 9: trello_boards = [board.name for board in trello_boards] trello_boards.append(last_board.name) keyboard = labels_to_keyboard(trello_boards) send_message(request["vk_id"], message=message, keyboard=keyboard) except (trello.exceptions.Unauthorized, ValueError, IndexError): send_message( request["vk_id"], message="Хмм, что-то не так. Перечитай мануал и попробуй снова")
def init_client(): for key in ('TRELLO_API_KEY', 'TRELLO_TOKEN'): if not key in os.environ: print('env variable %s not set. Aborting' % key) sys.exit(1) return trello.TrelloClient(os.environ['TRELLO_API_KEY'], token=os.environ['TRELLO_TOKEN'])
def main(): temp = ApigetKeyFile() # print(type(temp[0])) client = trello.TrelloClient( api_key=temp[0], token=temp[1], ) return client
def client(self): """Get a Trello api.""" if not self._client: # This isn't super nice if somebody else in the same # process is uinsg it... self._client = trello.TrelloClient(api_key=self.api_key, api_secret=self.api_secret) return self._client
def get_client(): """ Yields a trello client. """ client = trello.TrelloClient(api_key=TRELLO_API_KEY, api_secret=TRELLO_API_SECRET, token=TRELLO_TOKEN) while 1: yield client
def _get_client(self) -> trello.TrelloClient: if not self._client: self._client = trello.TrelloClient( api_key=self.api_key, api_secret=self.api_secret, token=self.token, ) return self._client
def __init__(self): #initialize trello client settings = self.getSettings() self.client = trello.TrelloClient(api_key=settings['api_key'], token=settings['token']) #get board by boards's identifier (you can see it on url to board https://trello.com/b/S0JZaTMR) self.board = self.client.get_board(settings['board_id']) #get lists of board by his identifier (you identifier we get programly using command board.id) self.trlist = self.board.get_list(settings['list_id'])
def initialize_trello(self, config): '''Initializes our connection to the trello API :param dict config: parsed configuration from the yaml file :returns: trello.TrelloClient client ''' trello_client = trello.TrelloClient( api_key=config.api_key, api_secret=config.api_secret, token=config.oauth_token, token_secret=config.oauth_token_secret) return trello_client
def write_card_data(): # get the client to login config = get_trello_config() client = trello.TrelloClient( api_key=config.get('trello', 'api_key'), api_secret=config.get('trello', 'api_secret'), token=config.get('trello', 'token'), token_secret=config.get('trello', 'token_secret'), ) # get the board associated with our sales pipeline board = client.get_board(config.get('trello', 'pipeline_board')) # set up our output writing writer = csv.writer(sys.stdout) writer.writerow([ # can get these directly from the API 'id', 'url', 'opportunity', 'first contact', 'last update', # can infer this directly from the API 'company name', # from the card name 'outcome', # from the list name # stuff we can fill in on our own? 'proposal cost', 'proposal timeline', # stuff that Whitney can get for us 'client number of employees', 'approximate annual revenues', 'client wikipedia page (if exists)', 'client main contact (linkedin)', ]) # go through all of the lists to determine the outcome of different engagement for l in board.open_lists(): for card in l.list_cards(): card.fetch() sys.stderr.write("%s\n" % card.name) writer.writerow([ card.id, card.url, card.name, card.create_date, card.date_last_activity, card.name.split(':', 1)[0], card.trello_list.name, ])
def get_api_client(conf): """ Returns a new Trello API client object with the provided configuration. :returns: a TrelloClient object """ return trello.TrelloClient( api_key=conf.trello.api_key, api_secret=conf.trello.api_secret, token=conf.trello.token, token_secret=conf.trello.token_secret, )
def __init__(self, API_Key, API_Token, Board_ID): '''todo''' super(TrelloSource, self).__init__() self.client = trello.TrelloClient(api_key=API_Key, token=API_Token) self.board = self.client.get_board(Board_ID) for list_name in ( 'Inbox', 'Today', 'Someday', 'Later', ): self.list_sources[list_name] = self.get_list_by_name(list_name)
def setUp(self): g = github.Github(settings.GITHUB_TOKEN) self.user = g.get_user() self.org = [ x for x in self.user.get_orgs() if x.login == 'this-is-a-test-org' ][0] self.repo_dict = {x.name: x for x in self.org.get_repos()} self.repo = self.repo_dict['this_is_also_a_test'] self.client = trello.TrelloClient(api_key=settings.API_KEY, token=settings.API_TOKEN) self.board = self.client.get_board('PnJ7VVo8') self.clear_board() self.pull = self.repo.get_pulls('open')[0] self.gitrello = gitrello.Gitrello(self.pull, self.board) self.commits = self.pull.get_commits() self.card = self.gitrello.create_card()
def step_4(request): trello_client = trello.TrelloClient(api_key=request["trello_api_key"], token=request["trello_api_token"]) tboard_daily = fetch_tboards_by_name(trello_client, request["trello_board"])[0] tlist_daily = fetch_tlists_by_name(tboard_daily, request["trello_list"])[0] checklists_daily_dict = fetch_checklists_by_tlist(tlist_daily) pretty_checklists = make_checklists_pretty(checklists_daily_dict) percent_done_today = calculate_percent_done(checklists_daily_dict) message = "Твои задачи на сегодня\n\n" + pretty_checklists + "Выполненных задач за сегодня: " + \ str(percent_done_today) + "%\n" + "В день выполняется в среднем: " + \ str(request["total_percent"]) + "%" keyboard = labels_to_keyboard(["Проверить задачи"]) send_message(request["vk_id"], message=message, keyboard=keyboard)
def __init__(self, config): trello_args = config.get('trello') # todo check if board exist api_key = trello_args.get('api_key') token = trello_args.get('token') api_secret = trello_args.get('api_secret') board_id = trello_args.get('board_id') try: client = trello.TrelloClient(api_key=api_key, token=token, api_secret=api_secret) self._trello_board = client.get_board(board_id) except Exception as e: logging.error(e) logging.error("Can't connect to the board: {}".format(board_id)) logging.debug("Trello configuration: {}".format(trello_args)) raise e
def __connect(self, config): trello_client = trello.TrelloClient( api_key=config.api_key, api_secret=config.api_secret, token=config.oauth_token, token_secret=config.oauth_token_secret, ) try: # A simple API call (data reused in self.main_board) to initiate connection & test our credentials etc self.boards = trello_client.fetch_json( '/members/me/boards/?filter=open') return trello_client except requests.exceptions.ConnectionError: print('[FATAL] Could not connect to the Trello API!') raise GTDException(1) except trello.exceptions.Unauthorized: print('[FATAL] Trello API credentials are invalid') raise GTDException(1)
def main(board, list_name, config, title): with open(config, 'r') as fh: user_config = yaml.safe_load(fh) key = user_config.get('api_key', '') token = user_config.get('token', '') secret = user_config.get('api_secret', '') client = trello.TrelloClient( api_key=key, api_secret=secret, token=token, token_secret=secret, ) data = compile_automation_list_data(client, board, list_name) plot_data(data, title)
def get_working_board_id(api_key, api_secret, oauth_token, oauth_token_secret): client = trello.TrelloClient( api_key=api_key, api_secret=api_secret, token=oauth_token, token_secret=oauth_token_secret, ) board_id = '' all_boards = client.list_boards() for board in all_boards: if board.name == "TareasPoli": board_id = board.id if board_id == '': print("No se encontró el board \"TareasPoli\", será creado ahora") client.add_board("TareasPoli") all_boards = client.list_boards() for board in all_boards: if board.name == "TareasPoli": board_id = board.id return board_id, board.all_members()[-1].id
def __init__(self): ''' Default constructor ''' # Todo: put all of the key, secret, and tokens to env variables when deploying try: #Loads credentials from the credential file with open("credentials.json") as f: creds = json.load(f) self.client = trello.TrelloClient( api_key=creds["trello"]["api_key"], api_secret=creds["trello"]["api_secret"], token=creds["trello"]["token"] ) except: raise TrelloAuthException all_boards = self.client.list_boards() self.hack_board = all_boards[2] # Second index is the hack board self.hack_members = self.hack_board.get_members()
def setUp(self, name): name.return_value = 'test' g = github.Github(settings.GITHUB_TOKEN) self.user = g.get_user() self.org = [ x for x in self.user.get_orgs() if x.login == 'this-is-a-test-org' ][0] self.repo_dict = {x.name: x for x in self.org.get_repos()} self.repo = self.repo_dict['this_is_also_a_test'] self.client = trello.TrelloClient(api_key=settings.API_KEY, token=settings.API_TOKEN) self.board = self.client.get_board('PnJ7VVo8') self.pull = self.repo.get_pulls('open')[0] self.gitrello = gitrello.Gitrello(self.pull, self.board) self.commits = self.pull.get_commits() for card in self.board.open_cards(): card.delete() self.trello_list = [x for x in self.board.open_lists()][0] test_card = self.trello_list.add_card('test') test_card.add_checklist('test checklist', ['a', 'b', 'c'], itemstates=[True, False, False]) test_card.fetch() self.card = self.gitrello.create_card()
def step_3(request): try: trello_client = trello.TrelloClient(api_key=request["trello_api_key"], token=request["trello_api_token"]) tboard_daily = fetch_tboards_by_name(trello_client, request["trello_board"])[0] tlist_daily = fetch_tlists_by_name(tboard_daily, request["message"])[0] checklists_daily_dict = fetch_checklists_by_tlist(tlist_daily) execute_sql( "UPDATE users SET trello_list='{}', step=4 WHERE vk_id={}".format( request["message"], request["vk_id"]), POSTGRES_CONNECTION_PARAMS) pretty_checklists = make_checklists_pretty(checklists_daily_dict) percent_done_today = calculate_percent_done(checklists_daily_dict) message = "Твои задачи на сегодня\n\n" + pretty_checklists + "Выполненных задач за сегодня: " + \ str(percent_done_today) + "%" keyboard = labels_to_keyboard(["Проверить задачи"]) send_message(request["vk_id"], message=message, keyboard=keyboard) except IndexError: send_message(request["vk_id"], message="Но такого списка нет...")
def get_working_board_id(api_key: str, api_secret: str, oauth_token: str, oauth_token_secret: str) -> (str, str): """This function is for getting the TareasPoli Board ID that is created in the onboard process Args: api_key (str): The api key to acceso Trello api_secret (str): The api secret to acceso Trello oauth_token (str): The oauth token to acceso Trello oauth_token_secret (str): The oauth token secret to acceso Trello Returns: board_id (str): This is the board id of TareasPoli board owner_id (str): This is the owner id of Trello user """ client = trello.TrelloClient( api_key=api_key, api_secret=api_secret, token=oauth_token, token_secret=oauth_token_secret, ) board_id = "" owner_id = "" all_boards = client.list_boards() for board in all_boards: if board.name == "TareasPoli": board_id = board.id if board_id == "": logging.error( ('No se encontró el board "TareasPoli", será creado ahora')) print('No se encontró el board "TareasPoli", será creado ahora') client.add_board("TareasPoli") all_boards = client.list_boards() for board in all_boards: if board.name == "TareasPoli": board_id = board.id owner_id = board.all_members()[-1].id return board_id, owner_id
def validate_token(self, token): try: trello.TrelloClient(api_key=trello_credentials.api_key, token=token.data).list_boards() except: raise ValidationError("Invalid Trello Token")
def get_trello_client(api_key=settings.TRELLO_API_KEY, api_secret=settings.TRELLO_API_SECRET, token=None): # noqa return trello.TrelloClient(api_key, api_secret=api_secret, token=token)