Skip to content

Instantly share code, notes, and snippets.

@error9900
Created January 30, 2024 23:32
Show Gist options
  • Save error9900/36117bcabade5529b6139f623e42a6e8 to your computer and use it in GitHub Desktop.
Save error9900/36117bcabade5529b6139f623e42a6e8 to your computer and use it in GitHub Desktop.
Sort Todoist Labels alphabetically
"""
Make sure you add your API token to `data/token.txt`!
"""
import sys
import uuid
import requests
def load_token():
with open("data/token.txt", "r", encoding="utf-8") as file:
line = file.readline()
token = line.strip()
return token
def check_response(response):
if response.ok is False:
print(f"Error: {response.content}")
sys.exit()
def sync_post(body):
session = requests.Session()
response = session.post(
"https://api.todoist.com/sync/v9/sync",
headers={"Authorization": f"Bearer {load_token()}"},
json=body,
timeout=60,
)
check_response(response)
return response
def build_command_label_update_orders(id_order_mapping: dict):
command = {
"type": "label_update_orders",
"uuid": uuid.uuid4().hex,
"args": {"id_order_mapping": id_order_mapping},
}
return command
def get_sorted_labels():
body = {
"sync_token": "*",
"resource_types": '["labels"]',
}
response = sync_post(body)
labels = response.json()["labels"]
return sorted(labels, key=lambda x: x["name"])
def build_id_order_mapping(labels):
id_order_mapping = {}
for num, label in enumerate(labels, start=1):
id_order_mapping[label["id"]] = num
return id_order_mapping
def sort_labels() -> None:
labels = get_sorted_labels()
id_order_mapping = build_id_order_mapping(labels)
command = build_command_label_update_orders(id_order_mapping)
body = {"commands": [command]}
sync_post(body)
if __name__ == "__main__":
sort_labels()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment