Skip to content

Instantly share code, notes, and snippets.

@AtsushiSakai
Forked from tangjeff0/random_notion.py
Created March 5, 2022 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AtsushiSakai/b7de81878d67304bce8d00f27853dae0 to your computer and use it in GitHub Desktop.
Save AtsushiSakai/b7de81878d67304bce8d00f27853dae0 to your computer and use it in GitHub Desktop.
get random notion notes to resurface your old ideas!
'''
author:
@tangjeff0
https://www.notion.so/tangjeff0/Public-Home-0e2636bd409b454ea64079ad8213491f
inspired by: https://praxis.fortelabs.co/p-a-r-a-iii-building-an-idea-generator-400347ef3bb6/
with help from: https://medium.com/@jamiealexandre/introducing-notion-py-an-unofficial-python-api-wrapper-for-notion-so-603700f92369
credits:
@jamiealexandre
@fortelabs
@HiredThought
'''
import sys
import os
import random
from notion.client import NotionClient
def main(num_rand_rows):
'''
inputs: a dictionary mapping a collection page to its URL
outputs: a random row from each collection, plus its URL
'''
NOTION_TOKEN = '<replace me>'
token_v2 = os.environ['NOTION_TOKEN'] or NOTION_TOKEN
if not token_v2:
raise Exception('Please set a token in the code or your environment.')
client = NotionClient(token_v2=token_v2)
# replace these urls with any of the collection pages you seek to get a random note from
# this only works on collection pages (e.g. table, board, calendar, list, gallery)
urls = [
# 'https://www.notion.so/...', # 1 Projects
# 'https://www.notion.so/...', # 2 Areas
# 'https://www.notion.so/...', # 3 Resources
# 'https://www.notion.so/tangjeff0/9a502814b56f47a08579374990effa98', # Notebook
'https://www.notion.so/tangjeff0/2e6a09bec7a34632a40cebe1828b3b9f', # Content
'https://www.notion.so/tangjeff0/ce1468140ef742d4a15f84e08fc82d1b', # Someday/Maybe
]
for url in urls:
page = client.get_block(url)
rows = page.collection.get_rows()
if not rows:
page.collection.refresh()
rows = page.collection.get_rows()
if not rows:
continue
n = len(rows)
print(f"{page.title}:")
for i in range(num_rand_rows):
rand_idx = random.randint(0, n-1)
rand_row = rows[rand_idx]
title = rand_row.title
url = f"https://www.notion.so/{rand_row.id}"
print(f"\ttitle={title}, url={url}")
if __name__ == '__main__':
# execute only if run as the entry point into the program
# either take in user arg for number of rows
# default to five since the API call is kinda slow XD
if (len(sys.argv) == 2):
num_rand_rows = int(sys.argv[1])
else:
num_rand_rows = 5
main(num_rand_rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment