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.

Share:

Dec 31, 2022 746 Words

Read Time: 4 Minutes

In this tutorial, I'll show you how to set your own Task Automation System with Notion and Python. Now that you've gotten your hands on this template and duplicated into your workspace, let's get started: 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.

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, lies 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?

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 Create notion integration secret token

  3. Give name My Notion Task Automator and submit

    Create notion integration secret token

  4. Show and copy secret token (keep it aside safely) Create notion integration secret token

  5. Click Save Changes Create notion integration secret token

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

    Connect it to the notion page

  2. Click on Add Connections and search and select the newly created Notion Integration Connect it to the notion page

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,

Adding Tasks into the Task Definition database

Adding Tasks into the Task Definition database

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,

Replit setup

Replit setup

Replit setup

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()

Replit setup

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

Replit setup Replit setup

4. Run the script from your browser!

Replit setup

Replit setup

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

Replit setup

πŸ₯³ 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!

πŸ“© Get My Latest Updates

Join 1000+ subscribers and customers


Find more posts from following topics

accurate-requests
api-development
api-testing
api-testing-tools
array
automated-testing
bad-habits
base64-decoder
base64-encoder
binding
blog
blogging
bulma-css
bulma.io
button-swiftui
chatgpt
clipboard
code
code-block
code-snippet
comparison
compile
configuring-debugger-for-django-in-vs-code
configuring-launch.json-for-python-debugger
copy
copy-to-clipboard
copy-to-clipboard-neovim
css
current-date
current-time
current-timestamp
debugger-setup-in-visual-studio-code
debugging-django-app-in-visual-studio-code
debugging-python-code-in-visual-studio-code
debugging-python-programs-with-visual-studio-code
debugging-python-with-virtual-environment-in-vs-code
developer-productivity
developers
development-workflow
dom
dynamic-sitemap-in-nextjs
engineering-dashboard
flowcharts
git
git-diff
github
global-keyboard-shorcut
global-shortcut
go
go-hugo
go-programming
go-to-line
golang
golang-development
good-habits
gorilla-websocket
gpt
gpt-3.5
gpt-4
gpt-4-api
guide
gumroad
habits
habits-tracker-notion-template
hamburger-menu
hotkeys
html
hugo
ide
image
image-sharing
image-tool-for-ios
imagerenderer
include-timestamp
integrated-development-environment
ios
ios-16
ios16
javascript
keyboard-shortcut
linux
macos
map
markdown
markdown-code
mental-programming
menu
menubarextra
mermaid-syntax
mistake-tracker-notion
mobile-view
modifier
navbar
navigationlink
navigationstack
neovim
next.js
nextjs
nextjs-markdown
nextjs-sitemap
nextjs-sitemaps
nice-shot
nice-shot-pro
notion
notion-api
notion-api-python
notion-budget
notion-budget-template
notion-budget-tracker
notion-bug-report-tracker
notion-dashboard
notion-expense-manager
notion-habits
notion-habits-dashboard
notion-habits-template
notion-habits-tracker
notion-habits-tracker-template
notion-issue-tracker
notion-mistake-tracker
notion-product
notion-product-dashboard
notion-product-roadmap
notion-product-roadmap-dashboard
notion-tasks
notion-tasks-dashboard
notion-tasks-template
notion-tasks-tracker
notion-template
notionworkspaces
openai
osx
personal-ifttt-framework
photospicker
photospickeritem
phpickerfilter
postman-capabilities
postman-request
pre-request-script
product-roadmap-notion-template
product-roadmap-template
productivity
programming
python
python-api
python-debugger-tutorial-for-vs-code
python-debugging-mode-in-vs-code
python-notion-api
real-time-communication
rehype
remark
request-data
running-debugger-in-visual-studio-code
running-django-app-in-debugging-mode
running-program-in-debugging-mode-in-vs-code
running-python-code-in-debugging-mode
screenshot-app-for-ios
screenshot-app-ios
screenshot-ios
screenshot-tool-for-ios
set-current-timestamp
setting-up-debugger-in-vs-code-for-python
share-extension
sharelink
sharepreview
sharesheet
simple-websocket-server
sitemap
slice
slider
step-by-step-guide
stocks-profits-tracker
stocks-profits-tracker-template
stocks-tracker
struct
sustained-vigilance
swift
swiftui
swiftui-button
swiftui-button-action
swiftui-button-style
table-of-contents
tasks-tracker-notion-template
textfield-swiftui
timeliness
timestamp-integration
transferable
triggers-and-actions
tutorial
us-stocks
usa-stocks
useful-ios-features
using-breakpoints-in-python-debugger
using-virtual-environment-with-python-debugger
vanilla-javascript
variable
vim
visual-mode
visual-studio-code
vs-code
vscode
vscode-go-to-line
web-sockets-in-go
websocket-client
websocket-programming
websocket-server
xcode