def cli(argv): parser = argparse.ArgumentParser(description='Uploads Markdown files to Notion.so') parser.add_argument('token_v2', type=str, help='the token for your Notion.so session') parser.add_argument('page_url', type=str, help='the url of the Notion.so page you want to upload your Markdown files to') parser.add_argument('md_path_url', type=str, nargs='+', help='A path, glob, or url to the Markdown file you want to upload') parser.add_argument('--create', action='store_const', dest='mode', const='create', help='Create a new child page (default)') parser.add_argument('--append', action='store_const', dest='mode', const='append', help='Append to page instead of creating a child page') parser.add_argument('--clear-previous', action='store_const', dest='mode', const='clear', help='Clear a previous child page with the same name if it exists') parser.set_defaults(mode='create') args = parser.parse_args(argv) print("Initializing Notion.so client...") client = NotionClient(token_v2=args.token_v2) print("Getting target PageBlock...") page = client.get_block(args.page_url) uploadPage = page for mdPath, mdFileName, mdFile in filesFromPathsUrls(args.md_path_url): if args.mode == 'create' or args.mode == 'clear': # Clear any old pages if it's a PageBlock that has the same name if args.mode == 'clear': for child in [c for c in page.children if isinstance(c, PageBlock) and c.title == mdFileName]: print(f"Removing previous {child.title}...") child.remove() # Make the new page in Notion.so uploadPage = page.children.add_new(PageBlock, title=mdFileName) print(f"Uploading {mdPath} to Notion.so at page {uploadPage.title}...") upload(mdFile, uploadPage)
def import_keep_row(json_name): co = None try: # noinspection PyUnresolvedReferences co = threading.current_thread().co except: pass if not co: client = NotionClient(token_v2=token, client_specified_retry=retry) co = client.get_block(block).collection threading.current_thread().co = co json_content = open(os.path.join(folder, json_name), 'rb').read() sha256 = hashlib.sha256(json_content).hexdigest() logger('import note from', repr(json_name), 'sha256', repr(sha256)) jmap = json.loads(str(json_content, encoding='utf-8')) exists_rows = co.get_rows(search=sha256) if len(exists_rows): logger('exists row') row = exists_rows[0] else: logger('create row') row = co.add_row() util.import_keep_row(co, row, jmap, sha256) util.import_text_content(row, jmap) util.import_attachments(row, folder, jmap) util.import_list_content(row, jmap) logger('ok', repr(json_name), 'sha256', repr(sha256))
def export(url, token): client = NotionClient(token_v2=token) page = client.get_block(url) blocks = [] recursive_getblocks(page, blocks, client) md = block2md(blocks, './') return md
def add_visit(token, clients_url, visits_url, telefon, fio, chto_budem_delat, stoimost, datetime_start, datetime_end): client = NotionClient(token) clients_collection = client.get_collection_view(clients_url) # filter_params = [{ # "property": "telefon", # "comparator": "enum_contains", # "value": telefon # }] # results = clients_collection.build_query(filter=filter_params).execute() # if results: # customer = results[0] # else: # customer = clients_collection.collection.add_row() # customer.telefon = telefon # customer.fio = fio visits_collection = client.get_collection_view(visits_url) visit = visits_collection.collection.add_row() # visit.klient = customer try: visit.stoimost = int(stoimost) except: pass visit.chto_budem_delat = chto_budem_delat visit.data = NotionDate(start=datetime_start, end=datetime_end)
def organize(): client = NotionClient(token_v2=TOKEN_V2) page = client.get_collection_view(TASK_LIST_URL) for row in page.collection.get_rows(): property = row.name.split("@")[-1] row.property = property
def hello(): client = NotionClient(token_v2=os.environ.get("NOTION_TOKEN")) cv = client.get_collection_view( "https://www.notion.so/larskarbo/7aa8bbb6129241dbb03f9460e6270113?v=5ebb4bee12c34ef09408c8c0cbb0df45" ) rows = cv.collection.get_rows() bar = Bar('Processing', max=len(rows)) for row in rows: bar.next() # if row.name == "2 brødskiver med kaviar og egg": for child in row.children: if child.type == "collection_view": # child cv2 = client.get_collection_view(child.views[0].id, collection=child.collection) macros = macroCalcTable(cv2, row.name, row.antall_porsjoner) row.protein = macros["protein"] row.fett = macros["fett"] row.karbohydrat = macros["karbohydrat"] row.kcal = "🔥 " + str(macros["kcal"]) + " kcal" row.kroner = "💰 " + str(macros["kroner"]) + " kr" if cv2 is None: print("cv2 is none") return bar.finish()
def hello(): client = NotionClient( token_v2="738991375dbb49e1050ead92da668fb277c43c6df82f1dd49b6e667a3d83a8da738051a0a7d489d04dccaa043b81e6d196beaa11f7e6a4e233a96491391d13337a9fbc7a2911f6a9f9a4452f1192") cv = client.get_collection_view( "https://www.notion.so/larskarbo/534d0728c32d474c9d23315d8afc82d5?v=f8eed84cbef6437ca18f9506f8469fe4") rows = cv.collection.get_rows() for i in range(5): nums = [] rand = rows[randint(-1, len(rows)-1)] p = rand.person nums.append(rand.name) rand = rows[randint(-1, len(rows)-1)] h = rand.handling nums.append(rand.name) rand = rows[randint(-1, len(rows)-1)] o = rand.objekt nums.append(rand.name) print("{} {} på {}".format(p, h.lower(), o.lower())) val = input("Enter your value: ") if val[0:2] == nums[0] and val[2:4] == nums[1] and val[4:6] == nums[2]: print("hurray!!") else: print("wrong") print(val) print(nums)
def test_todo_desk(): TOKEN = '12828fc2a49d4301f495c09c4532089219a1d48db6bcffb301b1b308d895ce70e98197c5b1d4e0da6b2bb5d497da10241140a47f959ffe484941472dfda2719c35a8804fb68e35f2b36689ae47be' NOTION = "https://www.notion.so/f8e9e4d17e7d4e7696595a8d56948f3b?v=d938f8f324374cf9a41ae129ebfe0301" today = datetime.datetime.now().date() client = NotionClient(TOKEN) cv = client.get_collection_view(NOTION) filter_params = { "filters": [{ "filter": { "value": { "type": "exact", "value": "DONE" }, "operator": "enum_is" }, "property": "Status", }] } current_rows = cv.collection.get_rows(filter=filter_params) for row in current_rows: if row.set_date.start > today: continue if row.set_date.start < today: calculate_due_day(row) elif row.set_date.start == today: row.status = "TO DO" return 'ok'
def create_entry(): token = request.args.get("token") content = request.get_json(silent=True) print(content) ## [{ value, slug, type }] client = NotionClient(token) url = request.args.get('url') cv = client.get_collection_view(url) row = cv.collection.add_row() ## Types: ## date => NotionDate ✅ ## relation => ???? ## title => string ✅ ## select => string ✅ for prop in content: val = prop['value'] if (prop['type'] == 'date'): datet = datetime.fromtimestamp(prop['value']) val = NotionDate(datet) row.set_property(prop['slug'], val) response = app.response_class(status=200, mimetype='application/json') return response
def meeting_overview(request): html = '' client = NotionClient(token_v2=settings.NOTION_COOKIE) page = client.get_block(settings.NOTION_URL) meeting_block = None for block in page.children: if block.id == '383b2866-a0ae-4f4e-b246-4131117721c0': meeting_block = block.collection break sort_dict = {} for meeting in meeting_block.get_rows(): month = meeting.title.split(' ')[0].lower() if month in sort_dict: sort_dict[month].append(meeting) else: sort_dict[month] = [meeting] # html = f'<h4 class="meeting"><a href="/notes/meeting/{meeting.id}">{meeting.title}</a></h4>' + html for month in sort_dict.keys(): string = '<div class="wrapper">{}{}</div>' button = f'<div class="button" id="button_{month}" onclick="dropdown(this, \'{month}\');"><p>{month}</p></div>' tmp = '</ul></div>' for meeting in sort_dict[month]: tmp = f'<li class="meeting_{month}"><a href="/notes/meeting/{meeting.id}">{meeting.title}</a></li>' + tmp tmp = f'<div class="dropdown1" id="dropdown_{month}"><ul class="content" id="content_{month}">' + tmp + '<br><br>' html = string.format(button, tmp) + html return render(request, 'notes/notes.html', {'html': html})
def notion_temp(self): token_v2 = '' #notion 사용자 고유의 토큰 주소 client = NotionClient(token_v2=token_v2) url = '' #자동으로 입력할 noiton 페이지 page = client.get_block(url) # 표 새로 만들고 저장 child = page.children.add_new(CollectionViewBlock) child.collection = client.get_collection( client.create_record( "collection", parent=child, schema={ "title": {"name": "내용", "type": "title"}, "date": {"name": "날짜", "type": "date"} }) ) child.title = '2020년도 회의록' child.views.add_new(view_type="table") row = child.collection.add_row() row.set_property('title', self.title) row.set_property('date', datetime.strptime(self.date, '%Y-%m-%d')) text = row.children.add_new(TextBlock) text.title = self.summary_result return url
def __init__(self, token_v2, public_dir='./public', build_dir='./temp', cache_dir='./cache', init_dir='./www', template_dir='./templates'): self.client = NotionClient(token_v2=token_v2) self.public_dir = public_dir # public directory for final static website self.build_dir = build_dir # temporary build directory, deleted after use self.cache_dir = cache_dir # store cached files here self.init_dir = init_dir # directly copied over to initialize public directory self.template_dir = template_dir # html templates along with associated css and svg os.makedirs(cache_dir, exist_ok=True) os.makedirs(os.path.join(cache_dir, 'images'), exist_ok=True) #os.makedirs(build_dir, exist_ok=True) # initialize jinja2 template environment templateLoader = jinja2.FileSystemLoader(searchpath="./templates") self.env = jinja2.Environment(loader=templateLoader, extensions=['jinja2_highlight.HighlightExtension']) # add specific functionality to jinja2 environment self.env.extend(jinja2_highlight_cssclass = 'highlight') # code highlighting self.env.filters['commafy'] = lambda v: "{:,}".format(v) # format number with commas 1200 -> "1,200" self.env.filters['flatten'] = lambda A: [y for x in A for y in x] # flatten array? I'm not sure where I'm using this # initialize and load cache self.loadCache() # keep copy of templates for flexibility self.templates = templates.copy()
def createNotionTask(token, collectionURL, content): # notion client = NotionClient(token) cv = client.get_collection_view(collectionURL) row = cv.collection.add_row() row.title = content row.categories = "d8b32dac-7d11-4879-813f-5acdb040fd33"
def addTodoEntry(name, dueDate=False, desc=False): if "TG2N_NOTION_TOKEN" not in os.environ: return client = NotionClient(token_v2=os.environ['TG2N_NOTION_TOKEN'], start_monitoring=False) if "TG2N_NOTION_CV_LINK" not in os.environ: return cv = client.get_collection_view(os.environ['TG2N_NOTION_CV_LINK']) row = cv.collection.add_row() row.todo = name if dueDate: if " " in dueDate: dueDate = datetime.datetime.strptime(dueDate, '%Y%m%d %H%M') else: dueDate = datetime.datetime.strptime(dueDate, '%Y%m%d') tz = "Europe/Berlin" if "TG2N_TIMEZONE" in os.environ: tz = os.environ['TG2N_TIMEZONE'] row.reminder = NotionDate(dueDate, None, timezone(os.environ['TG2N_TIMEZONE'])) if desc: todoEntryPageId = row.id todoEntryPage = client.get_block(todoEntryPageId) child = todoEntryPage.children.add_new(TextBlock, title=desc)
def insertIntoInbox(token, collectionURL, header, body): # notion client = NotionClient(token) cv = client.get_collection_view(url_inbox) newInbox = cv.collection.add_row() newInbox.name = header newInbox.children.add_new(TextBlock, title=body)
def createCalendarEvent(TOKEN, collectionURL, description, event_begins, event_ends, location, summary, duration_mins, event_begins_pretty, id): # notion print("Entered createCalendarEvent for " + summary) client = NotionClient(TOKEN) cv = client.get_collection_view(collectionURL) row = cv.collection.add_row() row.Action_Item = summary row.Status = "Active" row.Priority = "Scheduled" row.Note = ( ("Location: " + location) if (location != None) else "") + "Description: " + str(description) #handle start time: print("Received event with timestamp of " + str(event_begins) + '\n') event_start_params = re.split('[-T:+]', event_begins) event_start_params = [int(i) for i in event_start_params] esp = event_start_params if len(esp) == 8: #In case a time was given and not only date event_start = datetime( esp[0], esp[1], esp[2], esp[3], esp[4], esp[5]).replace( tzinfo=gettz("Israel")) #- timedelta(hours = int(esp[6])) else: #In case only a date was provided event_start = datetime(esp[0], esp[1], esp[2]) row.Do_Date = event_start print("Finished createCalendarEvent for " + summary)
def __init__(self, todoist_token, notion_token, notion_settings_url): self.api = TodoistAPI(todoist_token) self.client = NotionClient(token_v2=notion_token) self.settings = self.client.get_collection_view(notion_settings_url) # extract and parse settings self.config = {} self.use_groups = False self.sync_completed_tasks = False self.sync_config() self.tasks = self.client.get_collection_view( "https://www.notion.so/" + self.config["Link to task database"]) self.projects = self.client.get_collection_view( "https://www.notion.so/" + self.config["Link to project database"]) self.labels = self.client.get_collection_view( "https://www.notion.so/" + self.config["Link to label database"]) # initialize todoist api jsons self.old_sync = None self.new_sync = None self.old_commit = None self.new_commit = None self.last_notion_sync_time = helper.add_local_tz( datetime(2020, 1, 1, 0, 0, 0, 0))
def w2n(url, id): # Setting up Notion client # Put in your token here token = "" client = NotionClient(token_v2=token) # Setting up Write.as client c = writeas.client() # Get Notion page url page = client.get_block(url) # Get Write.as post post = c.retrievePost(id) body = post['body'] title = post['title'] # Adds the Write.as post title to Notion page if title != '': page.children.add_new(SubheaderBlock, title=title) # Add the Write.as post body to the Notion page by adding a new block new = page.children.add_new(TextBlock, title=body) return new
def main(config): # Obtain the `token_v2` value by inspecting your browser cookies on a logged-in session on Notion.so client = NotionClient(token_v2=config["notion"]["token"]) # Replace this URL with the URL of the page you want to edit page = client.get_block(config["notion"]["database"]) print("The old title is:", page.title) # Access a database using the URL of the database page or the inline block cv = client.get_collection_view(config["notion"]["database"]) for row in cv.collection.get_rows(): print(row) # Add a new record row = cv.collection.add_row() row.name = "Just some data" row.is_confirmed = True row.estimated_value = 399 row.files = [ "https://www.birdlife.org/sites/default/files/styles/1600/public/slide.jpg" ] row.person = client.current_user row.tags = ["A", "C"] row.where_to = "https://learningequality.org"
def __init__(self, token_v2, notes_collection_url, tags_colleciton_url): client = NotionClient(token_v2=token_v2) self.notes_collection = client.get_collection_view( notes_collection_url) self.tags_collection = client.get_collection_view(tags_colleciton_url)
def access_database(): client = NotionClient(token_v2=args.token) # Access a database using the URL of the database page or the inline block cv = client.get_collection_view( "https://www.notion.so/liguoqinjim/3f253e90fea2424aa1d7224b526b04a5?v=c26bee77d48e4a3fade236ff1ae49498" ) print(cv) # List all the records with "Bob" in them for row in cv.collection.get_rows(): print("id={}".format(row.id)) print("name={}".format(row.title)) block = client.get_block(row.id) print(block) props = block.get_all_properties() print(props) print(type(props)) break # Add a new record row = cv.collection.add_row() row.title = "Just some data2" print(row) block = client.get_block(row.id) props = block.get_all_properties() print("props:{}".format(props)) # 设置row的值 block.set_property("fen_lei", "历史")
def sync(self): highlights = self.highlights print("Starting highlights sync") client = NotionClient(token_v2=env['TOKEN_V2']) page = client.get_block(env["PAGE"]) new_page_title = f"{highlights['title']} - {highlights['authors']}" try: for child in page.children: if child.title == new_page_title: child.remove() new_notebook_page = page.children.add_new(PageBlock, title=new_page_title) saved_section_count = 0 saved_highlight_count = 0 for section in highlights["sections"]: new_notebook_page.children.add_new( SubheaderBlock, title=section["section_title"]) for highlight in section["highlights"]: new_highlight_block = new_notebook_page.children.add_new( ToggleBlock, title=highlight["text"]) new_highlight_block.children.add_new( TextBlock, title=highlight["heading"]) saved_highlight_count += 1 print( f"Saved highlight {saved_highlight_count} of {highlights['highlight_count']}" ) saved_section_count += 1 print( f"Saved section {saved_section_count} of {highlights['section_count']}" ) print("Synced highlights") except Exception as e: print(e) print("An error occured while syncing!")
def login(cfg=None): # returns client ''' cfg: configuration path or dictionary of config. uses default path './config.yml' if None given ''' if isinstance(cfg, str): with open(cfg, 'r') as yml: config = yaml.load(yml) elif isinstance(cfg, dict): config = cfg elif cfg is None: with open('./config.yml', 'r') as yml: config = yaml.load(yml) else: print("Please give .yml path or dictionary") return token_v2 = config['token_v2'] client = NotionClient(token_v2=token_v2) root = client.get_block(config['url'], force_refresh=True) return root, client
def add_to_notion(data): token = "d276369250b9a9a9ceb447d36fc46007ed1978ce733e41dca6875c9aa7e67dd16225e9f1bb41aad3b2695b96e24e993462093b1d628ad16ad5db8058eeec27f2b062eae980ffa0e8a02f0778604a" client = NotionClient(token_v2=token) url = "https://www.notion.so/e053742a9c8443dbb03d1f12a38d5a30?v=7c30bcec1be64c3584c6e593fa4ed31e" collection_view = client.get_collection(url) for entry in data: print(entry)
def step_three(): token = os.environ.get('DO_NOT_COMMIT_NOTION_TOKEN') if not token: print( "Can't find token in environment. Did you do step 2 correctly or ran source .config?" ) return client = NotionClient(token_v2=token) parent_page = client.get_block(os.environ.get('NOTION_PAGE_URL')) for block in parent_page.children: try: if block.title == EXPENSE_TABLE_TITLE: print('Expenses Table already exists!') return except: continue cvb = parent_page.children.add_new(CollectionViewBlock) cvb.collection = client.get_collection( client.create_record("collection", parent=cvb, schema=get_collection_schema())) cvb.title = EXPENSE_TABLE_TITLE view = cvb.views.add_new(view_type="table") print('Success! Go back to the README for the last step')
def createNotionRowGeneric(token, collectionURL, request): # notion client = NotionClient(token) print('notion-url- {}'.format(collectionURL)) cv = client.get_collection_view(collectionURL) request_dict = dict(request.headers) request_keys = set(request_dict.keys()) uid = request.headers.get('uid') match_rows = [] for r in cv.collection.get_rows(): if uid == r.UID: match_rows.append(r) dd = cv.collection.query() ## hack to initialize the view if not match_rows: row = cv.collection.add_row() else: ## Ignore all other matched rows row = match_rows[0] notion_keys = set( [i.capitalize() for i in list(row.get_all_properties().keys())]) for key in (request_keys & notion_keys): print('key - {} -'.format(key)) setattr(row, key, request.headers.get(key)) data = dict(request.get_json()) for key in data: row.children.add_new(TextBlock, title=data[key])
def run(notion_url): client = NotionClient(token_v2=os.getenv('NOTION_MIKAN_TOKEN')) remote_snapshot = snapshot.fetch_remote_snapshot(client) local_snapshot = snapshot.fetch_local_snapshot() to_add, to_replace, to_remove = converter.from_snapshot(local_snapshot, remote_snapshot) def _add_blocks(head_block, terms): for child in head_block.children: if hasattr(child, 'title'): child.title = add_links(child.title, terms) _add_blocks(child, terms) def _replace_blocks(head_block, terms): for child in head_block.children: if hasattr(child, 'title'): child.title = replace_links(child.title, terms) _replace_blocks(child, terms) def _remove_blocks(head_block, terms): for child in head_block.children: if hasattr(child, 'title'): child.title = remove_links(child.title, terms) _remove_blocks(child, terms) base_block = client.get_block(notion_url) # to prevent unnecessary traversing if len(to_replace) > 0: _replace_blocks(base_block, to_replace) if len(to_remove) > 0: _remove_blocks(base_block, to_remove) if len(to_add) > 0: _add_blocks(base_block, to_add) snapshot.save_remote_snapshot(remote_snapshot)
def updateNotionTask(token, collectionURL, externalid): # notion client = NotionClient(token) cv = client.get_collection_view(collectionURL) for row in cv.collection.get_rows(search=externalid): if row.externalid == externalid: row.done = True
def go(): # driver = webdriver.Chrome(DRIVER) client = NotionClient(token_v2=os.environ["NOTION_TOKEN"]) block = client.get_block( "https://www.notion.so/larskarbo/Culture-Poster-b17e335301694a619d0938ec68257af3" ) targetBlock = client.get_block( "https://www.notion.so/larskarbo/Personal-work-preferences-d6b1cd3bff1f4969a4bf735674dbc2df#dde5cec4948240d5a957fdfcb5705d38" ) # delete all for child in targetBlock.children: child.remove() num = random.randint(1, len(block.children)) selected = block.children[num - 1] page = client.get_block( "https://www.notion.so/larskarbo/Random-976529219dde4b9bb66260b55b3f8a4f" ) newchild = page.children.add_new(TextBlock, title=("**" + selected.title + "**")) if len(selected.children): for child in selected.children: newchild.children.add_new(TextBlock, title=child.title) newchild.children.add_new(TextBlock, title="") newchild.move_to(targetBlock, "last-child")
def getTags(v2, db): from notion.client import NotionClient try: client = NotionClient(token_v2=v2) print("Connected") except: print("Error v2") try: cv = client.get_collection_view(db) print("Connected") except: print("Error db") try: values = [] a = cv.collection.get_schema_properties() s = a[2]['id'] b = cv.collection.get_schema_property(s) for c in b['options']: values.append(c['value']) print("Added {}".format(c['value'])) return values except: return values