def setUp(self): self.api_key = os.environ['TOGGL_API_KEY'] if self.api_key is None: raise Exception("Unable to execute api tests without an api key") self.workspace_id = os.environ['WORKSPACE_ID'] if self.workspace_id is None: raise Exception( "Unable to execute api tests without a workspace key to query") self.toggl = Toggl() self.toggl.setAPIKey(self.api_key)
class Toggl2GSuiteTest(unittest.TestCase): def setUp(self): self.api_key = os.environ['TOGGL_API_KEY'] self.toggl = Toggl() self.toggl.setAPIKey(self.api_key) # see https://stackoverflow.com/questions/19153462/get-excel-style-column-names-from-column-number LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' @staticmethod def excel_style(row, col): """ Convert given row and column number to an Excel-style cell name. """ result = [] while col: col, rem = divmod(col - 1, 26) result[:0] = Toggl2GSuiteTest.LETTERS[rem] return ''.join(result) + str(row) def test_toggl2gsuite(self): # have to do this year by year data = { 'workspace_id': os.environ['WORKSPACE_ID'], } y = self.toggl.getDetailedReport(data) credentials = ServiceAccountCredentials.from_json_keyfile_name( os.environ['KEYFILE'], ['https://spreadsheets.google.com/feeds']) client = gspread.authorize(credentials) sheet = client.open_by_url(os.environ['SHEET_URL']) worksheet = sheet.get_worksheet(0) wrote_header = False columns_to_write = [ 'user', 'updated', 'start', 'end', 'client', 'project', 'description', 'is_billable', 'billable' ] cell_row = 0 for row_idx, rec in enumerate(y['data']): if wrote_header == False: for col_idx, header in enumerate(columns_to_write): worksheet.update_acell( Toggl2GSuiteTest.excel_style(row_idx + 1, col_idx + 1), header) wrote_header = True for col_idx, header in enumerate(columns_to_write): worksheet.update_acell( Toggl2GSuiteTest.excel_style(row_idx + 2, col_idx + 1), rec[header])
def getTrackedHours(self, payslip): #_logger = logging.getLogger(__name__) toggl = Toggl() toggl.setAPIKey("83aa5f3cd6854b57221a0df67a366d3a") data = { 'grouping' : "users", 'subgrouping' : "projects", 'workspace_id' : 709530, 'since' : payslip.date_from, 'until' : payslip.date_to, 'order_field' : "duration", 'order_desc' : "on", 'user_ids' : self.toggl_user_id, } response = toggl.getSummaryReport(data) return round( response['total_grand'] / 1000.00 / 60.00 /60.00 )
def toggl(start, end, api_key): toggl = Toggl() toggl.setAPIKey(api_key) data = [] for w in toggl.getWorkspaces(): w_name = w.get("name", "") w_id = w.get("id", "") if not w_id: continue for r in toggl.getDetailedReport({ 'workspace_id': w_id, 'since': start.strftime("%Y-%m-%d"), 'until': end.strftime("%Y-%m-%d"), }).get("data", []): data.append({ "item": { "title": r.get("description", "").strip(), }, "start": ciso8601.parse_datetime(r.get("start", "")), "end": ciso8601.parse_datetime(r.get("end", "")), "duration": datetime.timedelta(milliseconds=r.get("dur", 0)), "tags": r.get("tags", []) + [r.get("client", ""), r.get("project", ""), w_name], "source": "toggl", "idle": False, }) return data
action="store_true", help="interactive mode") parser.add_argument("-m", "--mail", action="store_true", help="send report via email") args = parser.parse_args() # https://github.com/matthewdowney/TogglPy # ---------------------------------------- import json from TogglPy import Toggl toggl = Toggl() id_path = "data/old-reports-id.txt" id_vals = {} id_file = open(id_path, "r", encoding="utf-8") id_path = id_file.readline().strip() # print(id_path) id_file = open(id_path, "r", encoding="utf-8") for line in id_file: line = line.strip().split("::") id_key = line[0] id_val = line[1] id_vals[id_key] = id_val # pprint(id_vals)
class TogglPyTests(unittest.TestCase): def setUp(self): self.api_key = os.environ['TOGGL_API_KEY'] if self.api_key is None: raise Exception("Unable to execute api tests without an api key") self.workspace_id = os.environ['WORKSPACE_ID'] if self.workspace_id is None: raise Exception( "Unable to execute api tests without a workspace key to query") self.toggl = Toggl() self.toggl.setAPIKey(self.api_key) def test_connect(self): response = self.toggl.request("https://www.toggl.com/api/v8/clients") self.assertTrue(response is not None) def test_putTimeEntry(self): request_args = { 'workspace_id': self.workspace_id, } entries = self.toggl.getDetailedReport(request_args) #for this tests I'm tagging my Pomodoro Entries missing_projects = [ r for r in entries['data'] if r['project'] is None and 'Pomodoro' in r['description'] ] me = missing_projects[0] me_id = me['id'] #remember for later #I've tagged my pomodoro entries as Self/Self cp = self.toggl.getClientProject("Self", "Self") project_id = cp['data']['id'] me['pid'] = project_id #his is the new stuff response = self.toggl.putTimeEntry({"id": me_id, "pid": project_id}) self.assertTrue(response is not None) self.assertTrue('data' in response) self.assertTrue(response['data']['pid'] == project_id) def test_getDetailedReportCSV(self): data = { 'workspace_id': self.workspace_id, } csvfile = 'data.csv' self.toggl.getDetailedReportCSV(data, csvfile) self.assertTrue(os.path.isfile(csvfile)) os.remove(csvfile) data = self.toggl.getDetailedReportCSV(data) self.assertTrue(data is not None) def test_getDetailedReport(self): data = { 'workspace_id': self.workspace_id, } d = self.toggl.getDetailedReport(data) self.assertTrue(d is not None) self.assertTrue(len(d.keys()) > 0) fields = ['total_count', 'total_currencies', 'total_billable', 'data'] for f in fields: self.assertTrue(f in d.keys()) data = d['data'] self.assertTrue(len(data) > 0) dr = data[0] self.assertTrue('client' in dr) self.assertTrue('start' in dr) self.assertTrue('end' in dr) self.assertTrue('task' in dr) self.assertTrue('user' in dr) self.assertTrue('project' in dr)
#!/usr/bin/env python3 # This will retrieve summary reports from the toggl API for consecutive weeks # and store the logged times by project for further comparisons. # Imports # ------- from pprint import pprint from datetime import date,datetime,timedelta from TogglPy import Toggl # https://github.com/matthewdowney/TogglPy toggl = Toggl() from time import sleep # Variables # --------- firstMonday = date(2017,8,28) firstSunday = date(2017,9,3) # # dates for API tests # firstMonday = date(2018,11,5) # firstSunday = date(2018,11,11) dayDelta = timedelta(1,0,0) curMonday = firstMonday curSunday = firstSunday
api_key_file = argv[1] settings_ini_file = argv[2] if len(argv) > 2 else 'config.ini' with open(api_key_file, 'r') as f: api_key = f.read() config = configparser.ConfigParser() config.read(settings_ini_file) start_date = config.get('Time', 'StartDate') end_date = config.get('Time', 'EndDate') internal_time = config.get('Time', 'InternalTime') display_time = config.get('Time', 'DisplayTime') dump_path = config.get('IO', 'DumpPath') print('starting API') # Initial setup toggl = Toggl() toggl.setAPIKey(api_key) params = {'start_date': start_date, 'end_date': end_date} print('Making request') # Get the raw data on time entries response = toggl.request(time_entry_url, parameters=params) print('%d records' % len(response)) df = pd.DataFrame(response) # Get a list of project ids pids = df['pid'].unique() pids = pids[np.isfinite(pids)].astype(int) # Add column with name of project, so not just project id in df print('Making project request') response = [toggl.request(pid_req_fmt % pp)['data'] for pp in pids]
import math import csv from datetime import date, timedelta, datetime # https://baxeico.wordpress.com/2014/03/13/build-excel-timesheet-toggl-api-python/ # Toggle Docs # https://github.com/toggl/toggl_api_docs from TogglPy import Toggl _start_date = "2015-11-11" _workspace_id = keyring.get_password('toggl', 'toggl_workspace_id') _api_token = keyring.get_password('toggl', 'toggl_api_token') toggl = Toggl() toggl.setAPIKey(_api_token) # Get time entries started in a specific time range # https://github.com/toggl/toggl_api_docs/blob/50a0c8ef6dcd7acff9057bad9957b2d5c921b677/chapters/time_entries.md class Utils: # Update the file with newly added entries # It is okay to delete several entries manually. The code will append the missing new entries. @staticmethod def update_new_entries(): updated_entries = 0 print("Updating...") global first_id
def setUp(self): self.api_key = os.environ['TOGGL_API_KEY'] self.toggl = Toggl() self.toggl.setAPIKey(self.api_key)
import ScanRFID from TogglPy import Toggl import json from time import sleep toggl = Toggl() toggl.setAPIKey("") def autoScan(): """ This function loops the RFID scanning function and returns UID of RFID card. It is polling and sleeping the program at 1 sec intervals. """ while True: card = ScanRFID.getSerial() if card != 0: return card else: sleep(1) def lookupCards(UID): """ Looks up the Unique ID of the RFID card in the cards.json file in the program directory. Throws a KeyError if card is not registered. """ print "Looking up card in json file..." try: with open('./cards.json') as cardsFile: cards = json.load(cardsFile)