for i in range(len(tag_list)): if str(tag_list[i].name[0]).isalpha(): index[str(tag_list[i].name[0])] = i # 名称第一位必须是字母,index的key为A-Z!!! for i in range(ord("A"), ord("Z") + 1): # 顺序不是1开始了,而是A开始 if chr(i) in index.keys(): cnt = index[chr(i)] list_temp.append(tag_list[cnt]) tag_finish[tag_list[cnt].guid] = tag_dict.pop( tag_list[cnt].guid) # 在tag_dict中删除已经用过的tag return list_temp # 获取印象笔记数据 # 创建一个印象笔记client对象 client = EvernoteClient(token=auth_token, sandbox=False, china=True) note_store = client.get_note_store() # 通过client对象获取note_store对象 def get_evernote_data(): global tag_dict, tag_list # 获取所有标签 tag_list = note_store.listTags() for tag in tag_list: tag_dict[tag.guid] = tag def get_tags_num(): return str(len(tag_list))
# is installed in the 'evernote-sdk' directory, using this installer script: # https://gist.github.com/5048588 import sys sys.path.append('evernote-sdk') import clipboard from io import BytesIO import hashlib import binascii import evernote.edam.userstore.constants as UserStoreConstants import evernote.edam.type.ttypes as Types from evernote.api.client import EvernoteClient client = EvernoteClient(token=auth_token, sandbox=False) note_store = client.get_note_store() # List all of the notebooks in the user's account notebooks = note_store.listNotebooks() print("Found ", len(notebooks), " notebooks:") for notebook in notebooks: print(" * ", notebook.name) print("Creating a new note in the default notebook") # To create a new note, simply create a new Note object and fill in # attributes such as the note's title. note = Types.Note() note.title = "Test note from Pythonista" # To include an attachment such as an image in a note, first create a Resource
# encoding=utf8 from evernote.api.client import EvernoteClient token_yx = '' token_en = '' client_yx = EvernoteClient(token_yx, sandbox=False, china=True) client_en = EvernoteClient(token_en, sandbox=False, china=False)
print("To get a developer token, visit " \ "https://sandbox.evernote.com/api/DeveloperToken.action") exit(1) # Initial development is performed on our sandbox server. To use the production # service, change sandbox=False and replace your # developer token above with a token from # https://www.evernote.com/api/DeveloperToken.action # To access Sandbox service, set sandbox to True # To access production (International) service, set both sandbox and china to False # To access production (China) service, set sandbox to False and china to True sandbox = True china = False client = EvernoteClient(token=auth_token, sandbox=sandbox, china=china) user_store = client.get_user_store() version_ok = user_store.checkVersion("Evernote EDAMTest (Python)", UserStoreConstants.EDAM_VERSION_MAJOR, UserStoreConstants.EDAM_VERSION_MINOR) print("Is my Evernote API version up to date? ", str(version_ok)) print("") if not version_ok: exit(1) userStore = client.get_user_store() print(str(userStore)) note_store = client.get_note_store()
def client(self): if self._client: return self._client self._client = EvernoteClient(token=self.token, sandbox=self.sandbox) return self._client
def get_client(self): return EvernoteClient( consumer_key=configuration_dict['evernote_consumer_key'], consumer_secret=configuration_dict['evernote_consumer_secret'], sandbox=False)
import evernote.edam.type.ttypes as Types from evernote.api.client import EvernoteClient # https://sandbox.evernote.com/api/DeveloperToken.action # https://app.yinxiang.com/api/DeveloperToken.action auth_token = "your developer token" if auth_token == "your developer token": print "Please fill in your developer token" print "To get a developer token, visit " \ "https://sandbox.evernote.com/api/DeveloperToken.action" exit(1) client = EvernoteClient(service_host='app.yinxiang.com', token=auth_token, sandbox=False) user_store = client.get_user_store() version_ok = user_store.checkVersion("Evernote EDAMTest (Python)", UserStoreConstants.EDAM_VERSION_MAJOR, UserStoreConstants.EDAM_VERSION_MINOR) print "my Evernote API version up to date? ", str(version_ok) print "" if not version_ok: exit(1) note_store = client.get_note_store()
uargs = authorize_url.split('?') vals = {} if len(uargs) == 1: raise Exception('Invalid Authorization URL') for pair in uargs[1].split('&'): key, value = pair.split('=', 1) vals[key] = value return vals ## # Create an instance of EvernoteClient using your API # key (consumer key and consumer secret) ## client = EvernoteClient(consumer_key='your-key', consumer_secret='your-secret', sandbox=True) ## # Provide the URL where the Evernote Cloud API should # redirect the user after the request token has been # generated. In this example, localhost is used; note # that in this example, we're copying the URLs manually # and that, in production, this URL will need to # automatically parse the response and send the user # to the next step in the flow. ## request_token = client.get_request_token('http://localhost') ## # Prompt the user to open the request URL in their browser
] htmlfeed = ("<div>").join(htmlfeed) note_changed.content = htmlfeed noteStore.updateNote(DEV_TOKEN, note_changed) print("%s - note \"%s\": checked todos cleaned" % (datetime.datetime.now(), note["title"])) def run_routine(): global last_updatecount if updated(): print("%s - account updated since last check" % datetime.datetime.now()) apply_changes() last_updatecount += 1 else: print("%s - no updates since last check" % datetime.datetime.now()) TIMESTAMP_BASE = datetime.datetime(1970, 1, 1, 0, 0, 0, 0) last_updatecount = 0 client = EvernoteClient(token=DEV_TOKEN, sandbox=sandbox) noteStore = client.get_note_store() if __name__ == "__main__": while True: run_routine() sleep(POLLING_INTERVAL)
def build_evernote_store(user): token = user.evernote_token client = EvernoteClient(token=token, sandbox=False, china=False) note_store = client.get_note_store() return note_store
def add_to_note(title, newline): # 需输入笔记标题和需要添加的内容 # auth_token申请地址:https://dev.yinxiang.com/doc/articles/dev_tokens.php auth_token = "your token" # 关掉沙盒模式 sandbox = False # True代表使用的国内的印象笔记,而不是Evernote国际版 china = True # 创建一个印象笔记client对象 client = EvernoteClient(token=auth_token, sandbox=sandbox, china=china) # user_store = client.get_user_store() # 通过client对象获取note_store对象 note_store = client.get_note_store() # # 下面代码为了获取所有的笔记本数量、笔记本名和对应的GUID,目前是注释状态,为了找到对应的笔记本GUID # notebooks = note_store.listNotebooks() # print("Found", len(notebooks), " notebooks:") # for notebook in notebooks: # print(notebook.name, notebook.guid) notebookGuid = "笔记本的GUID" # api笔记本 # 生成查找笔记的规则,使用笔记创建排序,指定笔记本GUID为api笔记本,使用标题名搜索 updated_filter = NoteFilter(order=NoteSortOrder.CREATED, notebookGuid=notebookGuid, words=title) # 偏移0 offset = 0 # 只取一条笔记 max_notes = 1 # 查找出符合条件的笔记 result_list = note_store.findNotes(updated_filter, offset, max_notes) # # 如果找到对应笔记则,在这个笔记里加一条,否则创建一条新笔记加进去 if result_list.totalNotes: # 获取找到笔记的GUID note_guid = result_list.notes[0].guid # 获取到对应笔记 note = note_store.getNote(note_guid, 1, 1, 1, 1) # 使用正则匹配出笔记里的内容文本 match_res = re.search(r'<en-note>(.*)<\/en-note>', note.content, re.M | re.I) # 如果能匹配到内容,则获取内容设置变量名为old_content,否则old_content为空 if match_res: old_content = match_res.group(1) else: old_content = "" # 构建待更新的笔记内容 note.content = '<?xml version="1.0" encoding="UTF-8"?>' note.content += '<!DOCTYPE en-note SYSTEM ' \ '"http://xml.evernote.com/pub/enml2.dtd">' note.content += '<en-note>' + newline + '<br/>' + old_content # 将新内容添加在最前 note.content += '</en-note>' res = note_store.updateNote(auth_token, note) print(note.title + "添加成功,GUID: ", note.guid) # 没有找到旧的笔记,则新建一个 else: # 创建note对象 note = Types.Note() # 设置笔记名称 note.title = title # 读取evenote.txt里的内容 # 构建note的内容,把句子加到<en-note>标签中 note.content = '<?xml version="1.0" encoding="UTF-8"?>' note.content += '<!DOCTYPE en-note SYSTEM ' \ '"http://xml.evernote.com/pub/enml2.dtd">' note.content += '<en-note>' + newline note.content += '</en-note>' # 指定笔记本GUID note.notebookGuid = notebookGuid # 创建笔记 created_note = note_store.createNote(note) # 打印创建好的笔记标题和GUID print(note.title + "创建成功,GUID: ", created_note.guid)
def get_notestore(): # Real applications authenticate with Evernote using OAuth, but for the # purpose of exploring the API, you can get a developer token that allows # you to access your own Evernote account. To get a developer token, visit # https://SERVICE_HOST/api/DeveloperToken.action # # There are three Evernote services: # # Sandbox: https://sandbox.evernote.com/ # Production (International): https://www.evernote.com/ # Production (China): https://app.yinxiang.com/ # # For more information about Sandbox and Evernote China services, please # refer to https://dev.evernote.com/doc/articles/testing.php # and https://dev.evernote.com/doc/articles/bootstrap.php # global log # auth_token = token # cfp, inipath = getcfp('everwork') auth_token = cfp.get('evernote', 'token') # 直接提取,唯一使用 if auth_token == "your developer token": print( "Please fill in your developer token\nTo get a developer token, visit " "https://sandbox.evernote.com/api/DeveloperToken.action") log.critical('请填入从evernote官方网站申请的有效token!程序终止并退出!!!') exit(1) # To access Sandbox service, set sandbox to True # To access production (International) service, set both sandbox and china to False # To access production (China) service, set sandbox to False and china to True sandbox = False china = False # Initial development is performed on our sandbox server. To use the production # service, change sandbox=False and replace your # developer token above with a token from # https://www.evernote.com/api/DeveloperToken.action client = EvernoteClient(token=auth_token, sandbox=sandbox, china=china) @trycounttimes2('evernote服务器', maxtimes=10, maxsecs=30) def getnotestore(): global note_store if note_store is not None: # log.info(f'note_store健壮存在:{note_store}') return note_store userstore = client.get_user_store() # evernoteapijiayi() version_ok = userstore.checkVersion("Evernote EDAMTest (Python)", EDAM_VERSION_MAJOR, EDAM_VERSION_MINOR) if not version_ok: log.critical('Evernote API版本过时,请更新之!程序终止并退出!!!') exit(1) # print("Is my Evernote API version up to date? ", str(version_ok)) note_store = client.get_note_store() evernoteapijiayi() log.info(f'成功连接Evernote服务器!构建notestore:{note_store}') return note_store return getnotestore()
def get_unauthorized_evernote_client(): return EvernoteClient(sandbox=settings.EVERNOTE_SANDBOX, consumer_key=settings.EVERNOTE_CONSUMER_KEY, consumer_secret=settings.EVERNOTE_CONSUMER_SECRET)
if config.has_option('everote', 'sandbox'): useSandbox = bool(config.get('evernote', 'sandbox')) else: useSandbox = True # sandbox is the default enconfig['sandbox'] = useSandbox if config.has_option('evernote', 'tags'): enconfig['tags'] = config.get('evernote', 'tags').split(',') if config.has_option('evernote', 'notebook'): enconfig['notebook'] = config.get('evernote', 'notebook') try: logger.debug("About to init EvernoteClient") logger.debug('Sandbox: ' + str(useSandbox)) enclient = EvernoteClient(token=auth_token, sandbox=useSandbox) logger.debug("Init'd EvernoteClient") note_store = enclient.get_note_store() logger.debug("NoteStore instance created") except Exception, e: logger.critical("Error initializing EvernoteClient:") logger.critical(e) raise SystemExit try: enWriter = EvernoteWriter(enconfig, enclient, logger) except Exception, e: logger.critical("Error initializing EvernoteWriter:") logger.critical(e) raise SystemExit
from evernote.api.client import NoteStore import json fname = 'apikey2.json' str_data = open(fname).read() apikey = json.loads(str_data) nbname = raw_input('Enter the Evernote NoteBook: ') if (len(nbname) < 1): nbname = 'logbook_2015' # generate a new dev token: # https://sandbox.evernote.com/api/DeveloperToken.action dev_token = apikey['token'] client = EvernoteClient(token=dev_token, sandbox=False) uStore = client.get_user_store() user = uStore.getUser() print "Evernote User Name:", user.username nStore = client.get_note_store() notebooks = nStore.listNotebooks() nbexists = False for n in notebooks: if (n.name == nbname): nbexists = True nbguid = n.guid print 'Notebook %s found, guid:%s' % (nbname, nbguid) if not (nbexists): print 'Notebook %s has not been found' % nbname
from datetime import datetime, date try: from evernote.api.client import EvernoteClient import evernote.edam.type.ttypes as Types import evernote.edam.notestore.ttypes as NoteTypes except: print('evernote扩展初始化失败...') sys.exit(-1) file_list = [] file_realpath = {} running_path = os.getcwd() dev_token = "" get_client = lambda: EvernoteClient(token=dev_token) get_note_store = lambda: get_client().get_note_store() get_note_books = lambda: get_note_store().listNotebooks() def calc_MD5(conternt): md5 = hashlib.md5() md5.update(conternt) return md5.hexdigest() def file_to_note(title, content, md5, notebook_id): note = Types.Note() note.notebookGuid = notebook_id note.title = title note.content = '''<?xml version="1.0" encoding="UTF-8"?>
def _get_client(): global _client if _client is None: log_progress('login to evernote') _client = EvernoteClient(token=_auth_token, sandbox=False) return _client
def addNewNote(row): global EverNoteErrorCount if auth_token == "your developer token": print "Please fill in your developer token" print "To get a developer token, visit " \ "https://sandbox.evernote.com/api/DeveloperToken.action" exit(1) # Initial development is performed on our sandbox server. To use the production # service, change sandbox=False and replace your # developer token above with a token from # https://www.evernote.com/api/DeveloperToken.action #client = EvernoteClient(token=auth_token, sandbox=True) client = EvernoteClient(token=auth_token, sandbox=False) try: user_store = client.get_user_store() print "Get user store OK" except user_store.Error: print "Get user store error" return -1 try: version_ok = user_store.checkVersion( "Evernote EDAMTest (Python)", UserStoreConstants.EDAM_VERSION_MAJOR, UserStoreConstants.EDAM_VERSION_MINOR) print "Evernote API version up to date: ", str(version_ok) if not version_ok: print "My Evernote API version not up to date. ****" exit(1) except user_store.Error: print "Get Evernote API version error" return -1 try: note_store = client.get_note_store() # List all of the notebooks in the user's account notebooks = note_store.listNotebooks() #print "Found ", len(notebooks), " notebooks:" notebookFound = False for notebook in notebooks: #print " * ", notebook.name if (notebook.name == "S01.MSU.WKLog"): #print "found WKLog Notebook" note = Types.Note() note.notebookGuid = notebook.guid notebookFound = True if (notebookFound != True): print "**** Share notebook not found ****" quit() print "--- Creating a new note in the notebook: S01.MSU.WKLog --" except: print "Get note store error" EverNoteErrorCount = EverNoteErrorCount + 1 return -1 # To create a new note, simply create a new Note object and fill in # attributes such as the note's title. # note = Types.Note() note.title = row.WKRefNo print str(datetime.datetime.now()) # check content of row is null if row.WKAutoNo is None: #error print "*** WKAutoNo Error ***" return if row.WKRefNo is None: #error print "*** WKRefNo Error ***" else: print 'WKRefNo: %s' % row.WKRefNo tweetWKRefNo = row.WKRefNo.replace('2014220', '~') if row.LogDate is None: LogDate = 'NIL' else: LogDate = row.LogDate if row.LogTime is None: LogTime = 'NIL' else: LogTime = row.LogTime if row.RefDate is None: RefDate = 'NIL' else: RefDate = row.RefDate if row.RefTime is None: RefTime = 'NIL' else: RefTime = row.RefTime if row.AttendDate is None: AttendDate = 'NIL' else: AttendDate = row.AttendDate if row.AttendTime is None: AttendTime = 'NIL' else: AttendTime = row.AttendTime if row.ClrDate is None: ClrDate = 'NIL' else: ClrDate = row.ClrDate if row.ClrTime is None: ClrTime = 'NIL' else: ClrTime = row.ClrTime if row.RptBy is None: RptBy = 'NIL' else: RptBy = row.RptBy if row.AckBy is None: AckBy = 'NIL' else: AckBy = row.AckBy if row.Cat is None: Cat = 'NIL' else: Cat = row.Cat print "CAT: " + Cat if row.Site is None: Site = 'NIL' else: Site = row.Site if len(row.Site) < 3: Site = 'NIL' print "Site(<3): " + Site else: print "Site: " + Site if row.SubSys is None: SubSys = 'NIL' else: SubSys = row.SubSys if len(SubSys) < 3: SubSys = 'NIL' print "SubSys(<3): " + SubSys else: print "Subsys: " + SubSys # check special char & and replace if row.Symptoms is None: Symptoms = 'NIL' tweetSymptoms = 'NIL' else: Symptoms = row.Symptoms Symptoms = Symptoms.replace('&', 'and') tweetSymptoms = Symptoms[:125] print "Symptoms: " + Symptoms if (len(Symptoms) > 122): tweetSymList1, tweetSymList2 = Symptoms[:122], Symptoms[122:] tweetSymList2 = tweetSymList2[:130] else: tweetSymList1 = Symptoms tweetSymList2 = 'NIL' if row.Actions is None: Actions = 'NIL' tweetActions = 'NIL' else: Actions = row.Actions Actions = Actions.replace('&', 'and') tweetActions = Actions[:125] print "Actions: " + Actions if (len(Actions) > 130): tweetActList1, tweetActList2 = Actions[:130], Actions[130:] tweetActList2 = tweetActList2[:125] else: tweetActList1 = Actions tweetActList2 = 'NIL' if row.Status is None: Status = 'NIL' else: Status = row.Status if row.RefTo is None: RefTo = 'NIL' else: RefTo = row.RefTo note.content = '<?xml version="1.0" encoding="UTF-8"?>' note.content += '<!DOCTYPE en-note SYSTEM ' \ '"http://xml.evernote.com/pub/enml2.dtd">' note.content += '<en-note>' note.content += '<span style="font-weight:bold;color:black;">' + 'Symptoms: ' + '</span>' + Symptoms + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'Actions: ' + '</span>' + Actions + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'WKAutoNo: ' + '</span>' + str( row.WKAutoNo) + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'WKRefNo: ' + '</span>' + row.WKRefNo + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'LogDateTime: ' + '</span>' + LogDate + ' ' + LogTime + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'RefDateTime: ' + '</span>' + RefDate + ' ' + RefTime + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'AttendDateTime: ' + '</span>' + AttendDate + ' ' + AttendTime + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'ClrDateTime: ' + '</span>' + ClrDate + ' ' + ClrTime + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'RptBy: ' + '</span>' + RptBy + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'AckBy: ' + '</span>' + AckBy + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'Cat: ' + '</span>' + Cat + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'Site: ' + '</span>' + Site + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'SubSys: ' + '</span>' + SubSys + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'Symptoms: ' + '</span>' + Symptoms + '<br/>' #note.content += '<span style="font-weight:bold;color:black;">' + 'Actions: ' + '</span>' + Actions + '<br/>' #note.content += '<span style="font-weight:bold;color:black;">' + 'Status: ' + '</span>' + Status + '<br/>' note.content += '<span style="font-weight:bold;color:black;">' + 'RefTo: ' + '</span>' + RefTo + '<br/>' note.content += '</en-note>' # add tag info note.tagNames = [SubSys, Site, Cat] # Finally, send the new note to Evernote using the createNote method # The new Note object that is returned will contain server-generated # attributes such as the new note's unique GUID. try: created_note = note_store.createNote(note) print "--- Successfully created a new note ---" print "#######################################" postWKtwitter(tweetWKRefNo + ':' + Site + ',' + SubSys + ',SYM>' + tweetSymList1) if (tweetSymList2 != 'NIL'): postWKtwitter(tweetWKRefNo + ':' + 'SYM>' + tweetSymList2) if (tweetActions != 'NIL'): postWKtwitter(tweetWKRefNo + ':ACT>' + tweetActList1) if (tweetActList2 != 'NIL'): postWKtwitter(tweetWKRefNo + ':ACT>' + tweetActList2) print "#######################################" print return 0 except note_store.Error: print "Create note error" EverNoteErrorCount = EverNoteErrorCount + 1 return -1
''' import evernote.edam.userstore.constants as UserStoreConstants from evernote.api.client import EvernoteClient import evernote.edam.notestore.NoteStore as NoteStore from creds import developer_token if developer_token == "": print "Please fill in your developer token" print "To get a developer token, visit " \ "https://sandbox.evernote.com/api/DeveloperToken.action" exit(1) client = EvernoteClient(token=developer_token, sandbox=True) # UserStore是用来获取当前用户的相关信息的对象,用过从EvernoteClient调用get_user_store # 方法来创建UserStore实例。 user_store = client.get_user_store() version_ok = user_store.checkVersion( "Evernote EDAMTest (Python)", UserStoreConstants.EDAM_VERSION_MAJOR, UserStoreConstants.EDAM_VERSION_MINOR ) print "Is my Evernote API version up to date? ", str(version_ok) print "" if not version_ok: exit(1)
def makeNote(authToken, noteStore, noteTitle): client = EvernoteClient(token=authToken, sandbox=False) noteStore = client.get_note_store() Errors = client.get_user_store() # This is the GUID for the "Reading" notebook in my Evernote account. I am hardcoding this because of a bug with the --nbook option that I have not been able to diagnose. Reading_guid = "ea612952-d3a5-4a39-862b-01190ba02e47" # open the image and take its md5_hash image = open('%s.png' % noteTitle, 'rb').read() md5 = hashlib.md5() md5.update(image) image_hash = md5.hexdigest() # Assign the image content, length, and hash to a Data object. data = ttypes.Data() data.size = len(image) data.bodyHash = image_hash data.body = image # Create a new resource to hold the image. resource = ttypes.Resource() resource.mime = 'image/png' resource.data = data # Create a resource list in which to put the resource created above. resource_list = [] resource_list.append(resource) readingNote = ttypes.Note() readingNote.title = noteTitle readingNote.notebookGuid = Reading_guid readingNote.resources = resource_list nBody = '<?xml version="1.0" encoding="UTF-8"?>' nBody += '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' nBody += '<en-note>' nBody += '<pre>' nBody += '<p>' nBody += 'A pretty picture.' nBody += '<en-media type="image/png" hash="%s"/>' % image_hash nBody += '</p>' nBody += '</pre>' nBody += '</en-note>' ## Create note object readingNote.content = nBody try: note = noteStore.createNote(authToken, readingNote) return note except EDAMUserException as edue: print("EDAMUserException:", edue) return None except EDAMNotFoundException as ednfe: ## Parent Notebook GUID doesn't correspond to an actual notebook print("EDAMNotFoundException: Invalid parent notebook GUID", ednfe) return None
def __init__(self, **kwargs): self.client = EvernoteClient(token=self.developer_token, sandbox=True) self.note_store = self.client.get_note_store() self.notebooks = self.note_store.listNotebooks()
def __init__(self, token): self.token = token self.client = EvernoteClient(token=EN_TOKEN, sandbox=False) self.user_store = self.client.get_user_store() self.note_store = self.client.get_note_store()
newNote = getFullNote(source_noteStore, note.guid) newNote.guid = None newNote.notebookGuid = findNotebookByName(dest_notebooksList, notebook.name).guid if newNote.tagGuids != None: for i in range(len(newNote.tagGuids)): tagGuid = newNote.tagGuids[i] newNote.tagGuids[i] = findTagByName( dest_tagsList, findTagByGuid(source_tagsList, tagGuid).name).guid createNote(dest_noteStore, newNote) #源账户初始化 source_client = EvernoteClient(token=source_dev_token, sandbox=False, china=True) source_userStore = source_client.get_user_store() source_user = source_userStore.getUser() source_noteStore = source_client.get_note_store() #目标账户初始化 dest_client = EvernoteClient(token=dest_dev_token, sandbox=False, china=False) dest_userStore = dest_client.get_user_store() dest_user = dest_userStore.getUser() dest_noteStore = dest_client.get_note_store() #读取源账户的笔记本列表,并在目标账户中创建相同的笔记本,再更新笔记本的笔记本组 source_notebooksList = source_noteStore.listNotebooks() createAllNotebooks(dest_noteStore, source_notebooksList) dest_notebooksList = dest_noteStore.listNotebooks() setNotebookStack(source_notebooksList, dest_notebooksList) updateNotebooks(dest_noteStore, dest_notebooksList)
attrs = tag.attrs if 'lang' in attrs: attrs.__delitem__('lang') if 'style' in attrs: attrs['style'] = clean_style(attrs['style']) with open('data/tmp.xml', mode='w', encoding='utf-8') as f: f.write(str(soup)) return str(soup) # 正式账号 with open('data/prod.token', encoding='utf-8') as f: token = f.read() client = EvernoteClient(token=token, service_host='app.yinxiang.com') # 获取笔记本 noteStore = client.get_note_store() # notebooks = noteStore.listNotebooks() guid_notebook = '2d083d6b-b84e-4dea-b6de-e4fa42d8fd72' notebook = noteStore.getNotebook(guid_notebook) # OneNote迁移 笔记本 guid_notebook_bak = '9a93a8dc-d863-4621-8ab5-c91f4fdf8576' notebook_bak = noteStore.getNotebook(guid_notebook_bak) # 迁移备份 笔记本 # 查找笔记 filter = NoteStore.NoteFilter() filter.notebookGuid = guid_notebook_bak # TODO 之后改回去 spec = NoteStore.NotesMetadataResultSpec() spec.includeTitle = True notes = noteStore.findNotesMetadata(filter, 0, 200, spec).notes
# purpose of exploring the API, you can get a developer token that allows # you to access your own Evernote account. To get a developer token, visit # https://sandbox.evernote.com/api/DeveloperToken.action auth_token = "your developer token" if auth_token == "your developer token": print("Please fill in your developer token") print("To get a developer token, visit " \ "https://sandbox.evernote.com/api/DeveloperToken.action") exit(1) # Initial development is performed on our sandbox server. To use the production # service, change sandbox=False and replace your # developer token above with a token from # https://www.evernote.com/api/DeveloperToken.action client = EvernoteClient(token=auth_token, sandbox=True) user_store = client.get_user_store() version_ok = user_store.checkVersion("Evernote EDAMTest (Python)", UserStoreConstants.EDAM_VERSION_MAJOR, UserStoreConstants.EDAM_VERSION_MINOR) print("Is my Evernote API version up to date? ", str(version_ok)) print("") if not version_ok: exit(1) note_store = client.get_note_store() # List all of the notebooks in the user's account notebooks = note_store.listNotebooks()
def __init__(self, dev_token): client = EvernoteClient(token=dev_token) self.note_store = client.get_note_store()
def lambda_handler(event, context): #共通処理 事前定義 def return200(res_body): return {'statusCode': 200, 'body': json.dumps(res_body)} def return400(message_str): body = {'errorMessage': message_str} return {'statusCode': 400, 'body': json.dumps(body)} global noteobject #共通処理 Evernote認証 access_token = boto3.client('kms').decrypt(CiphertextBlob=b64decode( os.environ['en_access_token']))['Plaintext'].decode() client = EvernoteClient(token=access_token, sandbox=False) try: note_store = client.get_note_store() except Exception as e: return (return400(str(e))) #<ノート検索・複数取得><ノート個別取得>向け処理 nhead_e1 = r'^<\?xml version="1.0" encoding="UTF-8"\?>(\n)?' nhead_e2 = r'^<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">(\n)?' nhead_e3 = r'^<en-note.*?>(\n)?' #API:<ノート検索・複数取得> if event['httpMethod'] == 'GET' and event['resource'] == '/notes': #<ノート検索・複数取得>向け処理 リクエストからパラメータ値を取得してセット req_query = event['queryStringParameters'] if req_query is None: return (return400("パラメータが指定されていません")) req_searchword = req_query.get('q', '') req_notebookguid = req_query.get('notebookguid', '') try: req_searchtype = int(req_query.get('searchtype', 0)) req_includecontent = int(req_query.get('includecontent', 0)) req_maxnotescount = int(req_query.get('maxnotescount', 1)) except: return (return400('不正な型のパラメータ')) filter = NoteFilter(notebookGuid=req_notebookguid) resultSpec = NotesMetadataResultSpec(includeTitle=True, includeNotebookGuid=True) metalist = note_store.findNotesMetadata(filter, 0, 250, resultSpec) notelist = [] for meta in metalist.notes: noteobject = '' if req_searchtype == 0: #タイトル部分一致(既定) if str(req_searchword) in meta.title: if req_includecontent == 0: #コンテンツを含まない noteobject = { 'noteguid': meta.guid, 'title': meta.title, 'notebookguid': meta.notebookGuid } if req_includecontent == 1: #コンテンツを含む content = note_store.getNoteContent( access_token, meta.guid) content = re.sub(nhead_e1, '', content) content = re.sub(nhead_e2, '', content) content = re.sub(nhead_e3, '', content) content = re.sub(r'(\n)?</en-note>$', '', content) noteobject = { 'noteguid': meta.guid, 'title': meta.title, 'notebookguid': meta.notebookGuid, 'content': content, } if req_searchtype == 1: #タイトル完全一致 if req_searchword == meta.title: if req_includecontent == 0: #コンテンツを含まない noteobject = { 'noteguid': meta.guid, 'title': meta.title, 'notebookguid': meta.notebookGuid } if req_includecontent == 1: #コンテンツを含む content = note_store.getNoteContent( access_token, meta.guid) content = re.sub(nhead_e1, '', content) content = re.sub(nhead_e2, '', content) content = re.sub(nhead_e3, '', content) content = re.sub(r'(\n)?</en-note>$', '', content) noteobject = { 'noteguid': meta.guid, 'title': meta.title, 'notebookguid': meta.notebookGuid, 'content': content } if req_searchtype == 2: #タイトル・本文部分一致 pass #作成中 if noteobject != '': notelist.append(noteobject) if len(notelist) == req_maxnotescount: break return (return200(notelist)) #API:<ノート個別取得> if event['httpMethod'] == 'GET' and event['resource'] == '/note/{noteguid}': #リクエストからパラメータ値を取得してセット try: req_noteguid = json.loads(event['pathParameters']).get('noteguid') except: req_noteguid = event['pathParameters'].get('noteguid') if req_noteguid is None: return (return400("{noteguid}パス未指定")) n = note_store.getNote(access_token, req_noteguid, False, False, False, False) content = note_store.getNoteContent(access_token, req_noteguid) content = re.sub(nhead_e1, '', content) content = re.sub(nhead_e2, '', content) content = re.sub(nhead_e3, '', content) content = re.sub(r'(\n)?</en-note>$', '', content) noteobject = { 'noteguid': n.guid, 'title': n.title, 'content': content, 'notebookguid': n.notebookGuid } return (return200(noteobject)) #<ノート作成><ノート更新><ノート削除>向け処理 n = Types.Note() nhead_e = '<?xml version="1.0" encoding="UTF-8"?>' nhead_e += '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' #<ノート作成><ノート更新><ノート削除>向け処理 リクエストボディから値を取得してセット try: req_body_dict = json.loads(event['body']) except: return (return400('不正な形式のデータ')) req_notecontent = req_body_dict.get('notecontent', '') req_resource_ary = req_body_dict.get('resource_ary', []) req_notetitle = req_body_dict.get('notetitle') req_notebookguid = req_body_dict.get('notebookguid', '') if req_notetitle == None: return (return400('notetitleが未指定')) else: n.title = req_notetitle if req_notebookguid != '': n.notebookGuid = req_notebookguid else: pass #API:<ノート作成> if event['httpMethod'] == 'POST' and event['resource'] == '/note': n.content = nhead_e + '<en-note>' + req_notecontent + '</en-note>' if len(req_resource_ary) != 0: resources = [] for index, item in enumerate(req_resource_ary): data = Types.Data() data.body = b64decode(item['databody']) data.size = len(data.body) data.bodyHash = item['bodyhash'] resource = Types.Resource() resource.mime = item['mimetype'] resource.data = data attr = Types.ResourceAttributes() attr.fileName = 'img' + str([index - 1]) + '.jpg' resource.attributes = attr resources.append(resource) if len(resources) != 0: n.resources = resources n = note_store.createNote(n) noteobject = { 'noteguid': n.guid, 'title': n.title, 'notebookguid': n.notebookGuid } return (return200(noteobject)) #<ノート更新><ノート削除>向け処理 リクエストからパラメータ値を取得してセット try: req_noteguid = json.loads(event['pathParameters']).get('noteguid') except: req_noteguid = event['pathParameters'].get('noteguid') if req_noteguid is None: return (return400("{noteguid}パスが未指定")) #API:<ノート更新> if event['httpMethod'] == 'PATCH' and event[ 'resource'] == '/note/{noteguid}': n.guid = req_noteguid if req_notecontent != '': n.content = nhead_e + '<en-note>' + req_notecontent + '</en-note>' if len(req_resource_ary) != 0: pass #作成中 n = note_store.updateNote(access_token, n) noteobject = { 'noteguid': n.guid, 'title': n.title, 'notebookguid': n.notebookGuid } return (return200(noteobject)) #API:<ノート削除> if event['httpMethod'] == 'DELETE': pass #作成中 return (return400('不正なメソッドおよびリソースの指定 %s, %s' % (event['resource'], event['httpMethod'])))
#access_token = client.get_access_token( # request_token['oauth_token'], # request_token['oauth_token_secret'], # request.GET.get('oauth_verifier', '') # ['oauth_verifier', '547E7EFCEBC38A4D966E72CB2AAE0D01&sandbox_lnb=false'] #) #client = EvernoteClient(token=access_token) #note_store = client.get_note_store() #notebooks = note_store.listNotebooks() #=================================================================== #=================================================================== # fill the token here auth_token = "" client = EvernoteClient(token=auth_token) note_store = client.get_note_store() notebooks = note_store.listNotebooks() #print "Found ", len(notebooks), " notebooks:" #for notebook in notebooks: # print " * ", notebook.name # fill the notebook_name notebook_name = "" notebook_guid = "" for notebook in notebooks: if notebook.name == notebook_name: notebook_guid = notebook.guid filter = NoteStore.NoteFilter() filter.notebookGuid = notebook_guid spec = NoteStore.NotesMetadataResultSpec()
#!/usr/bin/python from evernote.api.client import EvernoteClient import evernote.edam.type.ttypes as Types dev_token = "S=s1:U=679e3:E=150952a1f8e:C=1493d78f2a8:P=1cd:A=en-devtoken:V=2:H=af92536299f84db9870ea3e3701f2ce3" client = EvernoteClient(token=dev_token) #userStore = client.get_user_store() #user = userStore.getUser() #print user.username noteStore = client.get_note_store() #notebooks = noteStore.listNotebooks() #for n in notebooks: # print n.name note = Types.Note() note.title = "NEVER MANUALLY TOUCH THIS!!" note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' note.content += '<en-note><ul>' for i in range(0, 5): note.content += '<li>one two</li>' note.content += '</ul></en-note>' note = noteStore.createNote(note) #noteStore = client.get_note_store() #notebook = Types.Notebook() #notebook.name = "My Notebook" #notebook = noteStore.createNotebook(notebook) #print notebook.guid
# How to get started? # # [Home - Evernote Developers](http://dev.evernote.com/) # # [evernote/evernote-sdk-python](https://github.com/evernote/evernote-sdk-python) # # git clone https://github.com/evernote/evernote-sdk-python.git # # get a dev token (that will give you access to your own account) at [Developer Tokens](https://www.evernote.com/api/DeveloperToken.action) and work through [Evernote Cloud API — Python Quick-start Guide - Evernote Developers](http://dev.evernote.com/doc/start/python.php) # # see more [rdhyee/evernote-web-utility](https://github.com/rdhyee/evernote-web-utility) # <codecell> from settings import EVERNOTE_DEV_TOKEN from evernote.api.client import EvernoteClient # <codecell> # https://gist.githubusercontent.com/evernotegists/5313860/raw/example.py # note the sandbox=False client = EvernoteClient(token=EVERNOTE_DEV_TOKEN, sandbox=False) userStore = client.get_user_store() user = userStore.getUser() print user.username # <codecell>