Example #1
0
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", "历史")
Example #2
0
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 create_ticket_collection(title, views: [Collection_Type],
                             tickets: [Ticket]):

    # Get notion config settings
    notion_config = Notion_config()

    # Set up client and get page to work on
    client = NotionClient(token_v2=notion_config.token)
    page = client.get_block(notion_config.base_page)

    # Add a new collection
    collection = page.children.add_new(CollectionViewBlock)

    collection.collection = client.get_collection(
        client.create_record("collection",
                             parent=collection,
                             schema=ticket_collection_scheme(tickets)))

    now = datetime.now()
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    collection.title = title + ' ' + dt_string

    # Add desired Views
    for view in views:
        collection.views.add_new(view_type=view.value)

    return collection
Example #4
0
class ExpenseTableClient:
    def __init__(self, token, page_url, table_url):
        self.client = NotionClient(token_v2=token)
        self.page = self.client.get_block(page_url)
        self.table = self.client.get_collection_view(table_url)
        self.categories = EXPENSE_CATEGORIES

    def add_expense(self,
                    categories,
                    amt,
                    payment_type,
                    transaction_date,
                    expense='Default Expense',
                    additional=None):
        row = self.table.collection.add_row()
        row.Expense = expense
        row.Categories = categories
        row.Amount = amt
        row.Date = transaction_date
        row.Type = payment_type
        row.Additional = additional

    # NOT WORKING
    def add_month_view(self, page, table_id):
        collection = self.client.get_collection(
            table_id)  # get an existing collection
        cvb = page.children.add_new(CollectionViewBlock, collection=collection)
        view = cvb.views.add_new(view_type="table")
Example #5
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
Example #6
0
def plot():
    client = NotionClient(token_v2=TOKEN)

    for page in PAGES:
        blocks = client.get_block(page)
        thing = get_empty_object()

        for i in range(len(blocks.children)):
            block = blocks.children[i]
            print(block.type)

            if block.type != "image":
                title = block.title

                if BASE_KEY in title:
                    thing["database"] = clear_text(title).split("](")[0].replace("[", "")

                elif X_AXIS_KEY in title:
                    thing["x"] = clear_text(title)

                elif Y_AXIS_KEY in title:
                    thing["y"] = clear_text(title)

                    if check_for_completeness(thing):
                        # not last block
                        if i != len(blocks.children) - 1:
                            next_block = blocks.children[i + 1]

                            # if next block is picture, then it is previous
                            # version of the plot, then we should remove it
                            if blocks.children[i + 1].type == "image":
                                next_block.remove()

                        draw_plot(client, thing, block, blocks)
                        thing = get_empty_object()
Example #7
0
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)
Example #8
0
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)
Example #9
0
 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 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)
Example #11
0
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')
Example #12
0
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
Example #13
0
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"
Example #14
0
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))
Example #15
0
class Interpreter():
    def __init__(self, site):
        self.token_v2 = raise(AttributeError("You need to supply your own auth token for notion"))
        self.site = site
        self.client = NotionClient(token_v2=self.token_v2)
        self.page = self.client.get_block(self.site)

    def render(self, page=None, depth=1):
        product = ""
        if page is None:
            page = self.page
        try:
            product += page.title + '<br>'
        except AttributeError:
            try:
                if page.source is not None:
                    product += f"\n<iframe src='{page.source}' frameborder='0' allow='autoplay; encrypted-media'" \
                               f" allowfullscreen title='video'></iframe>"
            except TypeError:
                pass
            except AttributeError:
                pass
        for p in page.children:
            product += self.render(p, depth=depth+1)
        return product
Example #16
0
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
Example #17
0
    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
Example #18
0
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})
class Underhood:
    def __init__(self, token_v2: str, cf_token: str, name: str,
                 archive_slug: str, cf_id: str):
        self.client = NotionClient(token_v2=token_v2)
        self.name = name
        self.local = LocalConfig()
        self.archive = self.client.get_block(
            f"https://www.notion.so/{archive_slug}")
        self.cf_url = f"https://api.cloudflare.com/client/v4/accounts/{cf_id}/workers/scripts/{name}"
        self.cf_headers = {
            "Authorization": f"Bearer {cf_token}",
            "Content-Type": "application/javascript",
        }

    def add_author(self, author: Author) -> None:
        author_page = AuthorPage(author=author,
                                 page=self.archive.collection.add_row(),
                                 local=self.local)
        author_page.write_page()
        self.update_urls(author.username, author_page.url.split("/")[-1])

    def update_urls(self, url: str, slug: str) -> None:
        text = requests.get(self.cf_url, headers=self.cf_headers).text
        lines = text.split("\n")
        lines[10] = f"{lines[10][:-2]}, '{url}':'{slug}'}};"
        text = "\n".join(lines)
        requests.put(self.cf_url,
                     headers=self.cf_headers,
                     data=text.encode("utf8"))
Example #20
0
class Tester:
    def __init__(self, config):
        if "notion" in config:
            if "token" not in config["notion"]:
                print("token for notion is not present!")
                exit()
            if "page" not in config["notion"]:
                print("page for notion is not present!")
                exit()
        else:
            print("notion is missing in config.json")
            exit()

        self.config = config

        self.client = NotionClient(token_v2=config["notion"]["token"])
        self.page = self.client.get_block(config["notion"]["page"])

        for child in self.page.children:
            try:
                print(child.title)
            except Exception as e:
                print(e)

        print("Parent of {} is {}".format(self.page.id, self.page.parent.id))
Example #21
0
def read_page(token_v2, page_url):
    client = NotionClient(token_v2=token_v2)
    base_block = client.get_block(page_url)
    print("Root Page:", base_block.title)
    bfs_block(base_block)
    print("Graph view generated")
    os.system("open graph_view.html")
Example #22
0
def sendCookies():
    client = NotionClient(token_v2="a101688b1a347ab26b980ee4ccde34355620c02f56039bd8d94359cfb8efe54909d58a41f73a4b134c2ca3eb58306e54269b8cabd5232972209a9b72291286b7e02715780b265a6caa3549712e39")
    page = client.get_block("https://www.notion.so/Cookies-efe872d38ff744a5bb99b35803da55e7")
    data = getCookies()
    newchild = page.children.add_new(DividerBlock)
    newchild = page.children.add_new(TextBlock,title=str(datetime.datetime.now()).split(" ")[0])
    for i in range(len(data)):
        newchild = page.children.add_new(TextBlock,title=data[i][0] + "  |  " + data[i][1])
Example #23
0
def main():
    client = NotionClient(token_v2=login_token)
    page = client.get_block(page_url)

    last_block = page.children[-1]
    all_but_last = page.children[:-1]
    for child in all_but_last:
        child.move_to(last_block, 'after')
Example #24
0
class AutomatedClient(object):
    def __init__(self, token_v2: str):
        self.notion_client = NotionClient(token_v2=token_v2)

    def get_page(self, url) -> PageBlock:
        block = self.notion_client.get_block(url)
        if not isinstance(block, PageBlock):
            print("Warning: This block is notPageBlock.")
        return block
def get_page_title(page):

    # Get notion config
    notion_config = Notion_config()

    client = NotionClient(token_v2=notion_config.token)
    page = client.get_block(page)

    return page.title
Example #26
0
def write_quotes(token_v2_in, page_url, quotes):
    #access private account using the token_v2 value
    client = NotionClient(token_v2=token_v2_in)

    #access the page you want
    page = client.get_block(page_url)

    for quote in quotes:
        page.children.add_new(TextBlock, title=quote)
        page.children.add_new(DividerBlock)
Example #27
0
def export_out(url, token):
    client = NotionClient(token_v2=token)
    page = client.get_block(url)
    file, dir = make_file(page)
    md = md_export(page, client, dir)
    md = remove_overlap(page, md)
    md = post_header(page, md)
    file.write(md)
    file.close
    print("Notion page is successfully exported to Jekyll post")
Example #28
0
def _add_book_to_notion(title: str, author: str, highlight_count: int,
                        aggregated_text: str, last_date: str,
                        notion_token: str, notion_table_id: str,
                        enable_book_cover: bool) -> str:
    notion_client = NotionClient(token_v2=notion_token)
    notion_collection_view = notion_client.get_collection_view(notion_table_id)
    notion_collection_view_rows = notion_collection_view.collection.get_rows()

    title_exists = False
    if notion_collection_view_rows:
        for row in notion_collection_view_rows:
            if title == row.title and author == row.author:
                title_exists = True
                row = row

                if row.highlights is None:
                    row.highlights = 0  # to initialize number of highlights as 0
                elif row.highlights == highlight_count:  # if no change in highlights
                    return 'None to add'

    title_and_author = title + ' (' + str(author) + ')'
    print(title_and_author)
    print('-' * len(title_and_author))

    if not title_exists:
        row = notion_collection_view.collection.add_row()
        row.title = title
        row.author = author
        row.highlights = 0

        if enable_book_cover:
            if row.cover is None:
                result = _get_book_cover_uri(row.title, row.author)
            if result is not None:
                row.cover = result
                print('✓ Added book cover')
            else:
                row.cover = NO_COVER_IMG
                print(
                    '× Book cover couldn\'t be found. '
                    'Please replace the placeholder image with the original book cover manually.'
                )

    parent_page = notion_client.get_block(row.id)

    # For existing books with new highlights to add
    for all_blocks in parent_page.children:
        all_blocks.remove()
    parent_page.children.add_new(TextBlock, title=aggregated_text)
    diff_count = highlight_count - row.highlights
    row.highlights = highlight_count
    row.last_highlighted = NotionDate(parse(last_date))
    row.last_synced = NotionDate(datetime.now())
    message = str(diff_count) + ' notes / highlights added successfully\n'
    return message
Example #29
0
def get_title():
    # Obtain the `token_v2` value by inspecting your browser cookies on a logged-in (non-guest) session on Notion.so

    client = NotionClient(token_v2=args.token)

    # Replace this URL with the URL of the page you want to edit
    page = client.get_block(
        "https://www.notion.so/liguoqinjim/3f253e90fea2424aa1d7224b526b04a5?v=6cb47ebcd12a4982bd89c04762c04e05"
    )

    print("The old title is:", page.title)
Example #30
0
def export_out(url,token):
    print("--- Start Exporting ---")
    client = NotionClient(token_v2=token)
    page = client.get_block(url)
    file,dir = make_file(page)
    md = md_export(page,client,dir)
    md = remove_overlap(page,md)
    md = post_header(page,md)
    file.write(md)
    file.close
    print("\n--- Jekyll Exporter successfully exported notion page ---")