コード例 #1
0
ファイル: importer.py プロジェクト: shadyabhi/notionmdimport
 def _upload_file(self, local_path, basedir):
     with open(local_path, 'r', encoding='utf-8') as mdFile:
         # Remove .md
         title = os.path.split(local_path)[1][:-3]
         new_page = self.notion_folder_pages[basedir].children.add_new(
             block.PageBlock, title=title)
         upload(mdFile, new_page)
コード例 #2
0
def upload_notion_data(Art,data):
    A= get_data(data)
    A.to_markdown("data.md",index = False) 
    with open("data.md","r", encoding="utf-8") as mdfile: 
        newPage = page.children.add_new(PageBlock, title=Art+" discography")
        upload(mdfile, newPage)
        print('Uploading the album data')
コード例 #3
0
def upload_body_with_markdown(row):
    global github_event_json

    body = github_event_json["issue"]["body"]

    # Make markdown file from issue body
    f= open("body.md","w+")
    f.write(body)
    f.close()

    # Upload issue body markdown file to row
    with open("body.md", "r", encoding="utf-8") as mdFile:
        upload(mdFile,row)
コード例 #4
0
def notion_upload(uploadFile):
    notion_title = 'Choose Notion page:> '
    notion_page, index = pick(notion_pages, notion_title)
    file_title = input("Page title:> ")
    client = NotionClient(token_v2="InsertToken")
    page = client.get_block(notion_page)
    with open(uploadFile, 'r', encoding='utf-8') as mdfile:
        newPage = page.children.add_new(PageBlock, title=file_title)
        # appends the converted contents of markdown file to new page
        upload(mdfile, newPage)
    new_upload = input("Upload new file?> ")
    if new_upload == "yes" or new_upload == "y":
        notion_upload()
    if new_upload == "no" or new_upload == "n":
        notes_menu()
コード例 #5
0
 def upload_content(self,
                    page_id: GUID,
                    content: str,
                    name: str,
                    clear: bool = True) -> Block:
     while True:
         try:
             page = self.client.get_block(page_id, force_refresh=True)
             if clear:
                 for child in page.children:
                     child.remove()
             time.sleep(2)
             contentFile = io.StringIO(content)
             contentFile.__dict__["name"] = name
             upload(contentFile,
                    page,
                    notionPyRendererCls=LatexNotionPyRenderer)
             break
         except Exception as e:
             logging.error(f'Error occurred while uploading content: {e}')
             clear = True
             time.sleep(10)
     return page
コード例 #6
0
ファイル: migrate_md.py プロジェクト: AlanDecode/nobelium

# %% 上传所有内容到 Notion
for i, (path, content) in enumerate(contents.items()):
    print(f'\n{i+1}/{len(contents)} {path}')

    # Load metadate and markdown string
    r = re.compile(r'---([\s\S]*?)---')
    m = r.match(content)
    meta = Metadata(yaml.safe_load(m.group(1)))
    text = content[len(m.group(0)):]

    # Write text to a tmp file
    mdFile = io.StringIO(text)
    mdFile.__dict__['name'] = path

    # Add to notion database
    row = cv.collection.add_row()
    row.status = meta['status']
    row.title = meta['title']
    row.slug = meta['slug']
    row.summary = meta['excerpt']
    row.date = meta['date'].date
    tags = set(meta['tags']) | set(meta['categories'])
    tags.add('Migrated')
    tags = [item for item in list(tags) if type(item) is str]
    row.tags = tags
    row.type = meta['layout']

    upload(mdFile, row, imagePathFunc=convertImagePath)
コード例 #7
0
if __name__ == "__main__":

    #   dotenv_path = join(dirname(__file__), '.env')
    #   load_dotenv(dotenv_path)

    # token_v2 value obtained by insepcting the browser's cookies on a logged in session on Notion.so
    client = NotionClient(token_v2=os.getenv('TOKEN_V2'))

    # URL of the page to edit
    page = client.get_block(os.getenv('PAGE_URL'))

    # Access a database using the URL of the database page or the inline block
    cv = client.get_collection_view(
        "https://www.notion.so/imonsieur/40223918171644b3bdeb7848f61132e6?v=db28b0ff77654e44801debef6938c9fd"
    )

    #row = cv.collection.add_row()

    #print("The old title is:", page.title)

    #page.title = "Aujourd'hui " + "[" + get_current_date() + "]"

    with open("quoti.md", "r", encoding="utf-8") as mdFile:
        row = cv.collection.add_row()
        row.name = "Aujourd'hui " + "[" + get_current_date() + "]"
        #newPage = cv.children.add_new(
        #    PageBlock, title="Aujourd'hui " + "[" + get_current_date() + "]")
        # Appends the converted contents of TestMarkdown.md to newPage
        upload(mdFile, row)
コード例 #8
0
root_dir = "root_dir"
from notion.client import NotionClient
from md2notion.upload import upload
from notion.block import PageBlock
import io
from pathlib import Path
import glob
from tqdm import tqdm

client = NotionClient(token_v2=token_v2)
page = client.get_block(notion_url)

for fname in tqdm(glob.glob("{root_dir}/**/*.md", recursive=True)):
    with open(fname, "r", encoding="utf-8") as mdFile:

        md_txt = mdFile.read().split("\n")
        page_title = md_txt[0].replace("#", "").strip()
        md_txt = "\n".join(md_txt[1:-1])

        mdFile = io.StringIO(md_txt)
        mdFile.__dict__[
            "name"] = fname  #Set this so we can resolve images later
        newPage = page.children.add_new(PageBlock, title=page_title)

        def convertImagePath(imagePath, mdFilePath):
            ret = Path(mdFilePath).parent / Path(mdFilePath).stem / Path(
                imagePath).name
            return ret

        upload(mdFile, newPage, imagePathFunc=convertImagePath)
コード例 #9
0
ファイル: app.py プロジェクト: brocoders/webhook2notion
def createNotionMeetingNote(token, collectionURL, data):
    # notion
    client = NotionClient(token)
    cv = client.get_collection_view(collectionURL)
    row = cv.collection.add_row()

    row.title = data.get('title')

    person_str = data.get('person')
    if person_str:
        people_cv = client.get_collection_view(
            'https://www.notion.so/brocoders/b4fee3350c234fa8a5a4a89677fb21c3?v=d6b07641b1f84e37863ad1ddde29d5f6'
        )
        filter_params = {
            "operator":
            "and",
            "filters": [{
                "property": "title",
                "filter": {
                    "operator": "string_is",
                    "value": {
                        "type": "exact",
                        "value": person_str
                    }
                }
            }]
        }
        result = people_cv.build_query(filter=filter_params).execute()

        row.person = client.get_block(result[0].id)

    str_date = data.get('date')  #6/25/2020 22:35:33
    if str_date:
        row.date = datetime.datetime.strptime(str_date, '%m/%d/%Y').date()
    row.mood = data.get('mood').split(", ")
    row.tags = data.get('tags').split(", ")
    row.type = data.get('type')

    interviewer_str = data.get('interviewer')
    if interviewer_str:
        subscriptionData = client.post(
            "getSubscriptionData", {
                "spaceId": "9f910372-8d4d-469e-a834-81199f575be7"
            }).json()

        req = {
            "recordVersionMap": {
                "notion_user":
                functools.reduce(lambda a, b: {
                    **a,
                    **{
                        b['userId']: -1
                    }
                }, subscriptionData['members'], {})
            }
        }
        users = client.post("syncRecordValues", req).json()

        for id, val in users['recordMap']['notion_user'].items():
            if val['value']['email'] == interviewer_str:
                row.interviewer = client.get_user(id)

    about_str = data.get('about')
    if about_str:
        row.children.add_new(SubsubheaderBlock, title="About")
        lines = io.StringIO(about_str)
        lines.name = '/'
        upload(lines, row)
        #row.children.add_new(TextBlock, title=about_str)

    summary_str = data.get('summary')
    if summary_str:
        row.children.add_new(SubsubheaderBlock, title="Summary")
        lines = io.StringIO(summary_str)
        lines.name = '/'
        upload(lines, row)
        #row.children.add_new(TextBlock, title=summary_str)

    action_points_str = data.get('action_points')
    if action_points_str:
        row.children.add_new(SubsubheaderBlock, title="Action points")
        lines = io.StringIO(action_points_str)
        lines.name = '/'
        upload(lines, row)
コード例 #10
0
        if window.clicked:
            cv = client.get_collection_view(self.databases[sender.title])
            row = cv.collection.add_row()

    def get_page_name(self, link):
        return client.get_block(link).title


if __name__ == "__main__":
    url = 'http://www.cs.toronto.edu/~bonner/courses/2020f/csc311/'

    page = client.get_block(
        "https://www.notion.so/The-Page-0a2a66080879419aa0fa7efeae521a73")

    new_page = page.children.add_new(block.PageBlock,
                                     title="New Markdown Page")

    path = url
    r = requests.get(path)
    if not r.status_code < 300:  # TODO: Make this better..., should only accept success
        raise RuntimeError(f'Could not get file {path}, HTTP {r.status_code}')
    fileName = path.split('?')[0]
    fileName = fileName.split('/')[-1]
    fileLike = io.StringIO(r.text)
    fileLike.name = path

    upload(fileLike, new_page)

    app = NotionMenuBar()
    app.run()
コード例 #11
0
ファイル: test.py プロジェクト: afschowdhury/obsidian_notes
from notion.client import NotionClient
from notion.block import PageBlock
from md2notion.upload import upload

# Follow the instructions at https://github.com/jamalex/notion-py#quickstart to setup Notion.py
client = NotionClient(
    token_v2=
    "0db2df966ecca281888e5771f1b39917aa41be00f0d22d3d9660ad5ad6f08f545c0195686ebf7fbcfa9f9ab46eedf5312f89c524eabbe0a43bf8132c05a590515284b70b426f09177be3298d5d1e"
)
page_link = "https://www.notion.so/afschowdhury/nw-page-fe52227028124dad9e54a506fcf36446"
page = client.get_block(page_link)

with open("Starting_git.md", "r", encoding="utf-8") as mdFile:
    newPage = page.children.add_new(PageBlock, title="Starting_git Upload")
    upload(
        mdFile,
        newPage)  #Appends the converted contents of TestMarkdown.md to newPage
コード例 #12
0
# open the file to retrieve token_v2

with open("v2.txt") as f:
    mylist = f.read().splitlines()

v2=mylist[0]

client = NotionClient(token_v2=v2)

# get user input for destination of upload

UploadDestination = input("Link to page you wish to upload to: \n")

NotePage = client.get_block(UploadDestination)

# get user input for name of file to be uploaded

file_to_upload = input("Name of file to upload (with extension): \n")
title_of_file = file_to_upload[:-3]
current_dir = os.getcwd()
path_to_file = current_dir + "/" + file_to_upload

print(path_to_file)

#upload the file 

with open(path_to_file,"r", encoding="utf-8") as mdFile:
        newPage = NotePage.children.add_new(PageBlock, title=title_of_file)
        upload(mdFile, newPage)
コード例 #13
0
def doUploadTree(rootPage):
    # key, value for tree of notion pages,
    # {'page' : 'abcdef-12345', ...}
    key_list = {
        
    }
    errorPage = []
    # root page
    key_list['./'] = rootPage

    for root, subdirs, files in os.walk('./'):
        if root == './_resources':
            continue

        # create new blanc parent pages
        for sub in subdirs:
            if sub in key_list:
                print('key exist ', sub)
            else:
                with lock:
                    newSubPage = getExistPage(key_list[root], sub)

                    if newSubPage is None:
                        newSubPage = key_list[root].children.add_new(PageBlock, title=sub)
                    else:
                        print('{} [{}] | '.format(threading.currentThread().getName(), sub), '  validation : parent exist')
                
                if root == './' and (sub != '_resources'):
                    key_list[root + sub] = newSubPage
                    print('{} [{}] | '.format(threading.currentThread().getName(), root + sub), ' create blank page ')
                else:
                    key_list[root + '\\' + sub] = newSubPage
                    print('{} [{}] | '.format(threading.currentThread().getName(), root + '\\' + sub), ' create blank page ')
        
        # create new pages and copy the markdown file
        for file in files:
            filename, file_extension = os.path.splitext(file)
            print('{} [{}] | '.format(threading.currentThread().getName(), filename), '  Create a new file : ', file)

            # critical section
            lock.acquire()
            print('{} [{}] | '.format(threading.currentThread().getName(), filename), '  the critical section has been locked')

            # check the page is already exist
            newSubPage = getExistPage(key_list[root], filename)
            if newSubPage is not None:
                print('{} [{}] | '.format(threading.currentThread().getName(), filename), '  validation : content exist')
                lock.release()
                continue
            if file_extension != '.md':
                print('{} [{}] | '.format(threading.currentThread().getName(), filename), '  validation : content is not markdown')
                lock.release()
                continue

            # go upload page
            try:
                # file open to be copied and create a new notion page
                mdFile = open(root + '\\' + file, "r", encoding="utf-8")
                newPage = key_list[root].children.add_new(PageBlock, title=filename)

                # release critical seciton
                lock.release()

                # upload file contents
                upload(mdFile, newPage)
            except:
                lock.release()
                print('{} [{}] | '.format(threading.currentThread().getName(), filename), '  Exception : ')
                errorPage.append(filename)
                traceback.print_exc()
            finally:
                continue

    print('errorPages = ', errorPage)
コード例 #14
0
def main():
    args = get_args()

    # Load the file passed in through args
    post = frontmatter.load(args.file)
    title = post['title']
    tags = post['tags']
    date = post['date']
    last_edited = post['last_edited']

    # Get everything for notion: CV is the CollectionViewPageBlock "Table Page"
    cv, token_v2, collection_view, client = login_to_notion()
    collection = cv.collection
    dict_of_articles = get_articles(cv)
    print(f"There are {len(dict_of_articles)} articles: \n")
    pprint(dict_of_articles)

    if title in dict_of_articles:
        # Delete then Upload Blog Post
        print(f"\n\n'{title}'\nALREADY IN LIST OF ARTICLES ON NOTION...")
        print(f"\tUPDATING ARTICLE!")

        # Grab the URL_ID from the dict_of_articles
        url_to_blog_page = dict_of_articles[title]

        # Select the page in notion
        blog_page = client.get_block(url_to_blog_page)

        # If it was edited on Notion Don't f**k with the Article:
        if blog_page.edited_on_notion:
            print("\n\n\tBRO WTFF!!!!!!!!!!")
            print("You edited this on Notion, I'm not f*****g with this article")
            print("Here's the URL so you can sync the changes:")
            print(f"{collection_view}&p={blog_page.id}")

            print("\nExiting...\n")
            return

        # Delete Blog Page
        blog_page.remove()

    else:
        # Upload Blog since it's not in the list
        print(f"\n\n'{title}'\nNOT IN NOTION LIST")
        print(f"\tUPLOADING NEW ARTICLE INTO NOTION\n")

    # Upload New Blog Page
    row = cv.collection.add_row()

    # Add Metadata
    try:
        row.title = title
        if tags:
            row.tags = tags
        if date:
            row.date = NotionDate(datetime.strptime(date, "%Y-%m-%d %H:%M:%S"))
        if last_edited:
            row.last_edited_locally = NotionDate(datetime.strptime(last_edited, "%Y-%m-%d %H:%M:%S"))
    except KeyError as e:
        print("\n\tERROR")
        print(e)
        print("Make sure you're formatting your FrontMatter Correctly:")
        print('tags: ["psychology", "productivity", "book review", "self help"]')
        print("title: 'My Title\n'")
        print("date: '2020-06-20 16:21:41'")

    # Re-Generate new List of articles to find the new ID
    dict_of_articles = get_articles(cv)

    url_to_blog_page = dict_of_articles[title]

    # Grab the whole row as a page
    blog_page = client.get_block(url_to_blog_page)

    # Add a text block and dump all the content in
    with open(args.file, "r", encoding="utf-8") as mdFile:
        # Set Blog Page to the actual content of the page
        blog_page = blog_page.children.add_new(TodoBlock)
        upload(mdFile, blog_page)

    # Delete the YAML frontmatter of the md file
    del(blog_page.children[1])