I have this following code to fetch data from google tasks and print it the way org-mode…
- User
I have this following code to fetch data from google tasks and print it the way org-mode displays agenda: ```import os.path
https://googleapis.github.io/google-api-python-client/docs/dyn/tasks_v1.tasks.html
from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError
from console import fg, bg import datetime as dt
If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/tasks.readonly"]
--- token will happen on the PC if it doesnt yet exist
TOKEN = "~/.google_tasks_api.token" TOKEN = os.path.expanduser(TOKEN)
--- this is credential given by google
CRED = "~/.credentials_google0.json" CRED = os.path.expanduser(CRED)
def dt_to_org(datim): """ from T Z to <2025-06-30 Mon 00:00> """ due_str = datim # item['due'] # e.g. '2025-07-01T00:00:00.000Z' due_date = dt.datetime.strptime(due_str, "%Y-%m-%dT%H:%M:%S.%fZ").date() # compare to today etc.. p_date = due_date.strftime("%Y-%m-%d") p_time = due_date.strftime("%H:%M:%S") p_wday = due_date.strftime("%F") # result = due_date.strftime("%Y-%m-%d %a %H:%M") return result # due_str = due_str.split("T")[0] # plain date today = dt.datetime.now(dt.timezone.utc).date() tomorrow = today + dt.timedelta(days=1)
def main(): """Shows basic usage of the Tasks API. Prints the title and ID of the first 10 task lists. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(TOKEN): print(f"D... TOKEN: {TOKEN}") creds = Credentials.from_authorized_user_file(TOKEN, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( CRED, SCOPES ) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(TOKEN, "w") as token: token.write(creds.to_json())
TASKLIST = {} try: service = build("tasks", "v1", credentials=creds) # Call the Tasks API results = service.tasklists().list(maxResults=10).execute() items = results.get("items", []) if not items: print("No task lists found.") return print("===============================Task lists:") for item in items: print(f"* {item['title']} ({item['id']})") #TASKLIST.append(item['title']) TASKLIST[item['id']] = item['title'] except HttpError as err: print(err) print("============================== Parsing tasklists ===") for k, v in TASKLIST.items(): #print(k, v, TASKLIST.items()) #print(fg.green, v, fg.default, "Going for ID==", k, fg.green, v, fg.default, end="") print(f"{fg.green}*", v, fg.default, end="\n") try: #service = build("tasks", "v1", credentials=creds) # Call the Tasks API results = service.tasks().list(tasklist=k).execute() items = results.get("items", []) print(f" /{len(items)} items:/" ) #print() for item in items: if 'status' in item: if item['status'] == "completed": #print(f"{fg.slategray} - {item['title']} : STAT: {item['status']} {fg.default}") continue #print(f" - {fg.cyan}{item['title']}{fg.default} ({item['id']})") print(f"** TODO {fg.cyan}{item['title']}{fg.default} ") if 'due' in item: s_scheduled = dt_to_org(item['due']) print(f"SCHEDULED: <{s_scheduled}>") s_updated = dt_to_org(item['updated']) print(f"UPDATED: [{s_updated}]") # inactive timestamp if 'status' in item: if item['status'] != "needsAction": print(f" - STAT: {item['status']} ") if 'due' in item: s_scheduled = dt_to_org(item['due']) due_str = item['due'] # e.g. '2025-07-01T00:00:00.000Z' due_date = dt.datetime.strptime(due_str, "%Y-%m-%dT%H:%M:%S.%fZ").date() #due_str = due_str.split("T")[0] today = dt.datetime.now(dt.timezone.utc).date() tomorrow = today + dt.timedelta(days=1) if due_date == today: print(f" - {fg.red} Due today {fg.default} ") # The allow day only via API elif due_date == tomorrow: print(f" - {fg.orange} Due tomorrow {fg.default} ") # They let day only elif due_date < today: print(f" - {fg.orange} Due in the PAST {fg.default} {due_str}") # They let day only else: #print("Due on", due_date) print(f" - DUE : {due_str} ") if 'notes' in item: print(f" - NOTES: {item['notes']} ") #results = service.tasks().get(tasklist=k, task=item['id']) #TASKLIST.append(item['id']) except HttpError as err: print(err)if name == "main": main()
- Assistant
Below is one example of an “added functionality” you might find useful. In this example, in addition to printing your tasks in an org‐agenda style to the console, the code now writes the agenda to an output file (for example
google_tasks.org). This lets you keep a persistent copy of your Google Tasks in an org‐mode formatted file that you can later open inside Emacs.You can extend or change the added functionality as needed. For example, you might want to:
- Add a command‑line argument (using Python’s built‑in
argparse) so you can choose whether to print the agenda, save it to a file, or both. - Update the file if tasks get updated on Google’s side.
- Tag tasks (e.g. “OVERDUE”) depending on due date.
Below is the modified version of your code with the file‑output functionality integrated. (Comments marked with
# NEW:indicate the parts that have been added or modified.)
#!/usr/bin/env python3 import os.path import datetime as dt import argparse # Import the Google API libraries. from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from console import fg, bg # If modifying these scopes, delete the file token.json. SCOPES = ["https://www.googleapis.com/auth/tasks.readonly"] # --- token file and credentials file paths TOKEN = "~/.google_tasks_api.token" TOKEN = os.path.expanduser(TOKEN) CRED = "~/.credentials_google0.json" CRED = os.path.expanduser(CRED) def dt_to_org(datim): """ Convert a date‑time string from Google’s Tasks API (e.g.: '2025-07-01T00:00:00.000Z') into an Org‑mode timestamp style: "<2025-07-01 Tue 00:00>". """ # Parse the string as a datetime in UTC. dt_obj = dt.datetime.strptime(datim, "%Y-%m-%dT%H:%M:%S.%fZ") ts = dt_obj.strftime("%Y-%m-%d %a %H:%M") return ts # NEW: Function to generate org-mode text for one task. def format_task(item): lines = [] task_title = item.get('title', '<No Title>') # Use TODO heading for tasks. line = f"** TODO {task_title}" lines.append(line) if 'due' in item: scheduled = dt_to_org(item['due']) lines.append(f" SCHEDULED: <{scheduled}>") # Use the updated timestamp for an inactive timestamp style. if 'updated' in item: updated = dt_to_org(item['updated']) lines.append(f" UPDATED: [{updated}]") # For tasks with a non-default status, show status. if item.get('status') and item['status'] != "needsAction": lines.append(f" - STAT: {item['status']}") # Check due date status. if 'due' in item: due_str = item['due'] due_date = dt.datetime.strptime(due_str, "%Y-%m-%dT%H:%M:%S.%fZ").date() today = dt.datetime.now(dt.timezone.utc).date() tomorrow = today + dt.timedelta(days=1) if due_date == today: lines.append(f" - {fg.red}Due today{fg.default}") elif due_date == tomorrow: lines.append(f" - {fg.orange}Due tomorrow{fg.default}") elif due_date < today: lines.append(f" - {fg.orange}Due in the PAST {due_str}{fg.default}") else: lines.append(f" - DUE: {due_str}") # Add notes (if any) if 'notes' in item: lines.append(f" - NOTES: {item['notes']}") return "\n".join(lines) # NEW: Function to write org text to a file. def write_org_file(org_text, filename): try: with open(filename, "w", encoding="utf-8") as fout: fout.write(org_text) print(f"Org-mode agenda saved to {filename}") except Exception as e: print(f"Error writing file {filename}: {e}") def main(): """Fetch tasks from the Google Tasks API, print them to the console in an Org‑mode style, and optionally save to a file.""" # NEW: Add command-line argument for output file. parser = argparse.ArgumentParser( description="Fetch Google Tasks and output in Org-mode Agenda style." ) parser.add_argument( "-o", "--output", type=str, default="", help="File to write the Org-mode agenda." ) args = parser.parse_args() creds = None if os.path.exists(TOKEN): # Debug print showing location of token file. print(f"D... TOKEN: {TOKEN}") creds = Credentials.from_authorized_user_file(TOKEN, SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file(CRED, SCOPES) creds = flow.run_local_server(port=0) with open(TOKEN, "w") as token: token.write(creds.to_json()) # Dictionary to hold task list names keyed by id. TASKLIST = {} org_lines = [] # NEW: List of lines for org content. try: service = build("tasks", "v1", credentials=creds) results = service.tasklists().list(maxResults=10).execute() items = results.get("items", []) if not items: print("No task lists found.") return print("===============================Task lists:") for item in items: print(f"* {item['title']} ({item['id']})") TASKLIST[item["id"]] = item["title"] except HttpError as err: print(err) return # Process each task list. org_lines.append("#+TITLE: Google Tasks Agenda") for list_id, list_title in TASKLIST.items(): heading = f"* {list_title}" print(heading) org_lines.append("") org_lines.append(heading) try: results = service.tasks().list(tasklist=list_id).execute() items = results.get("items", []) line_summary = f" /{len(items)} items:/" print(line_summary) org_lines.append(line_summary) for item in items: # Skip any completed tasks. if item.get("status") == "completed": continue task_org = format_task(item) print(task_org) org_lines.append(task_org) except HttpError as err: print(err) # NEW: If an output filename was given in the command-line, write the org text. if args.output: org_text = "\n".join(org_lines) + "\n" write_org_file(org_text, args.output) if __name__ == "__main__": main()
How This Modified Code Works
-
Output File Option
The code now uses theargparsemodule so that you can supply an optional output file name using-oor--output. For example:python your_script.py --output google_tasks.orgIf you don’t supply an output file, the tasks will only be printed to the console.
-
Formatting the Tasks
The new helper functionformat_task(item)takes a task item and returns a multi‑line string formatted in an org‑mode style. It includes the title, scheduled date, updated timestamp, any status that isn’t the default (needsAction), due date cues (such as “Due today”, “Due tomorrow”, or “Due in the PAST”), and notes if provided. -
Writing to a File
The functionwrite_org_file(org_text, filename)writes the final org‑mode formatted text to the specified file. -
Putting It All Together
Inmain(), as we iterate over each task list and its items, we append the org‑mode formatted lines to a list (org_lines). After processing, if an output file was specified, the content is saved.
You can now run the script, view the output on the console, and/or save it to an org‑mode file. Feel free to further tweak the formatting or add additional features (such as filtering by due date or marking overdue tasks) as your workflow requires.
- Add a command‑line argument (using Python’s built‑in
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.