DEV Community

Cover image for Daily Task Automator (+ Notion API with Python) - Tutorial
TnvMadhav⚡
TnvMadhav⚡

Posted on • Originally published at tnvmadhav.me

Daily Task Automator (+ Notion API with Python) - Tutorial

In this tutorial, I'll show you how to set your own Task Automation System with Notion and Python.

Brief Introduction:

We have to follow these two main steps:

  1. Notion integration setup
  2. Python code setup

The link between these two steps, lie in the magic of Notion API.

If you're new to Notion API and Notion Integration itself, I'll explain how you can get started with it in this tutorial.

Want the Notion Template? Get it here!

If you dont have access to the notion template yet, get it 👉🏻 here👈🏻

Now that you've gotten your hands on this template and duplicated into your workspace, let's get started:

The Notion integration setup

This step ensures the python script makes updates to the right notion database.

To ensure this, the python code needs to first 'identify' the notion database so that it can 'talk' to it.

Each notion database has a unique id that is part of the url link.

To make this process easier, we can create a 'secret token' that can be used to connect to your notion database.

Let's do just that,

1. Create notion integration secret token

If you haven't already, create a free Notion Account

  1. Go to https://notion.so/my-integrations/

  2. Click + New Integration button

Daily Task Automator (+ Notion API with Python) - Tutorial

  1. Give name My Notion Task Automator and submit

Daily Task Automator (+ Notion API with Python) - Tutorial)

  1. Show and copy secret token (keep it aside safely)

Daily Task Automator (+ Notion API with Python) - Tutorial

  1. Click Save Changes

Daily Task Automator (+ Notion API with Python) - Tutorial

Copy and keep the notion integration secret token so that you can later share it to your python script.

2. Connect it to the notion page

  1. Click ... on the top right corner

Daily Task Automator (+ Notion API with Python) - Tutorial

  1. Click on Add Connections and search and select the newly created Notion Integration

Daily Task Automator (+ Notion API with Python) - Tutorial

3. Create tasks to automatically populate everyday

Let’s start with a simple habit,

💪 “Doing 10 pushups at 10:30 AM — everyday of the week”

In Task Definition notion database, click + new, and create a new task:

  1. Task Name Perform 10 Pushups
  2. Date 10:30 AM (any date but time should be 10:30 AM)
  3. Days of the week (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)

Here is how it will look like,

Daily Task Automator (+ Notion API with Python) - Tutorial Tasks into the Task Definition database](/2.png)

Daily Task Automator (+ Notion API with Python) - Tutorial

Woo-hoo! Look at you!

Now let's focus on running the python script. Jumping right in:

The Python code setup

To do this, you don't have to run python on your PC or laptop.

You can:

1. Create a free account on Replit and login,

Daily Task Automator (+ Notion API with Python) - Tutorial

Daily Task Automator (+ Notion API with Python) - Tutorial

Daily Task Automator (+ Notion API with Python) - Tutorial

2. Copy and paste the python code

Copy the below python code:

import requests
import json
from datetime import date
import calendar
import os
import dateutil.parser
import datetime


class MyNotionIntegration:

    def __init__(self):
      self.headers = {
        'Content-Type': 'application/json',
        'Notion-Version': '2021-05-13',
        'Authorization': f'Bearer {os.getenv("NOTION_DAILY_TASK_SCHEDULER_INTEGRATION_SECRET")}'
      }
      self.read_db = self.write_db = self.list_of_tasks = None

    @staticmethod
    def getSameTimeButToday(date_string):
      if not date_string:
        return
      iso_parser = dateutil.parser.isoparse(date_string)
      today_date_obj = iso_parser.replace(
        day=datetime.datetime.now().day,
        month=datetime.datetime.now().month,
        year=datetime.datetime.now().year,
      )
      return today_date_obj.isoformat('T')

    def getReadAndWriteDBs(self, name=None):
      if not name:
        name = "TASKS TEMPLATE"
      url = "https://api.notion.com/v1/search/"
      payload = json.dumps({
        "filter": {
          "property": "object",
          "value": "database"
        }
      })
      response = requests.request("POST", url, headers=self.headers, data=payload)
      databases = response.json().get('results')
      for database in databases:
        if database.get('title')[0].get('text').get('content').upper() == name:
          self.read_db = database
        else:
          self.write_db = database

    def getTodaysTasks(self):
      url = f"https://api.notion.com/v1/databases/{self.read_db.get('id')}/query"
      payload = json.dumps({
        "filter": {
          "property": "Day of the Week",
          "multi_select": {
             "contains": calendar.day_name[date.today().weekday()]
          }
        }
      })
      response = requests.request("POST", url, headers=self.headers, data=payload)
      self.list_of_tasks = response.json().get('results')

    def createTasks(self):
      url = "https://api.notion.com/v1/pages/"
      for task in self.list_of_tasks:
        print(task.get('properties').get('Date').get('date').get('start'))
        payload = json.dumps({
          "parent": {
            "type": "database_id",
            "database_id": self.write_db.get('id'),
          },
          "icon": task.get('icon'),
          "properties": {
            "Due For": {
              "type": "date",
              "date": {
                "start": self.getSameTimeButToday(
                  task.get('properties').get('Date').get('date').get('start')
                ),
                "end": self.getSameTimeButToday(
                  task.get('properties').get('Date').get('date').get('end')
                ),
              }
            },
            "Task": {
              "type": "title",
              "title": [
                {
                  "type": "text",
                  "text": {
                    "content": task.get('properties').get('Name').get('title')[0].get('plain_text'),
                  },
                  "plain_text": task.get('properties').get('Name').get('title')[0].get('plain_text'),
                }
              ]
            }
          }
        })
        response = requests.request("POST", url, headers=self.headers, data=payload)
        print(f"HTTP Status {response.status_code}", response.text)

    def RunWorkflow(self):
      self.getReadAndWriteDBs()
      self.getTodaysTasks()
      self.createTasks()

if __name__ == "__main__":
  MyNotionIntegration().RunWorkflow()
Enter fullscreen mode Exit fullscreen mode

Daily Task Automator (+ Notion API with Python) - TutorialReplit setup

3. Share the notion integration secret key with the python script

Daily Task Automator (+ Notion API with Python) - Tutorial

Daily Task Automator (+ Notion API with Python) - Tutorial

4. Run the script from your browser!

Daily Task Automator (+ Notion API with Python) - Tutorial

Daily Task Automator (+ Notion API with Python) - Tutorial

After running the Python script on Replit, you can see that today’s tasks are auto-populated in Task Automator database.

Daily Task Automator (+ Notion API with Python) - Tutorial

🥳 Nice! You now have a automated todo-list!

Add any habits to the Task Definition database and run the python script on replit (automation) every day to auto generate the todo-list in the Task Automator database.

😆 Thank you

...for being part of this experiment and hope you use this to enhance your productivity 😃

If you dont have access to the notion template yet, get it 👉🏻 here👈🏻

If you liked this product, you'll probably love my other products which can be found 🔗 👉🏻 here👈🏻

Let's connect on Twitter @TnvMadhav if you don't wanna miss out on newer projects!

Top comments (0)