瓦雀.py| 使用python腳本更新維護語雀文檔 - 图1
© getcodify.com

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

瓦雀.py

自己寫肯定是不可能的, 瓦雀那麼好用, 爲什麼要自己寫呢???
ummmm, 爲什麼我的代碼都變了???

本地明明是

  1. except:
  2. Date= str(grep("b'Date:",lines)).replace("b'",'')
  3. From= Decode(str(grep("b'From:",lines)).replace("b'",''))
  4. To= Decode(str(grep("b'To:",lines)).replace("b'",''))
  5. Subject= Decode(str(grep("b'Subject:",lines)).replace("b'",''))
  6. print("",From,To,"\n",Subject,'\n\n',"this mail are purely composed by img or html",sep='\n')
  7. print('\n\n'+Date)

上傳以後,就翻車了。。 github和語雀問原作者,似乎一直沒有回 = =

  1. except:
  2. Date= str(grep("b'Date:",lines)).replace("b'",'')
  3. From= Decode(str(grep("b'From:",lines)).replace("b'",''))
  4. To= Decode(str(grep("b'To:",lines)).replace("b'",''))
  5. Subject= Decode(str(grep("b'Subject:",lines)).replace("b'",''))
  6. print("",From,To,"\n",Subject,'\n\n',"this mail are purely composed by img or html",sep='\n')
  7. print('\n\n'+Date)

好吧, 那我還是自己寫一個把。 反正API都已經公開了。
而且語雀很多語法, 不支持。 正好可以, 個性化一些小東西。 避免一些bug和尷尬。

基礎

查看 repositories

Document

  1. import requests
  2. USER = ${你的repors前面那段名字}
  3. ## 比如, 你的主頁是 https://www.yuque.com/xiaoming
  4. ## 則, USER = ‘xiaoming’
  5. url = 'https://www.yuque.com/api/v2/users/' + USER
  6. header = {"X-Auth-Token": "Your Token"}
  7. requests.get(url, headers = header).json()
  1. {'data': {'id': 691897, 'type': 'User', 'space_id': 0, 'account_id': 494138, 'login': 'liuwenkan', 'name': 'Karroben',...

這裏可以獲得你自己的ID和一些主頁身份信息。 之後就可以用ID來做請求了。

  1. url = 'https://www.yuque.com/api/v2/users/' + USER + "/repos"
  2. ## or url = 'https://www.yuque.com/api/v2/users/' + ID + "/repos"
  3. Repo_Result = requests.get(url, headers = header).json()['data']

現在, 你可以查看Repo的信息了。 這裏包括了所有倉庫及其統計信息。 如果不想查看, 請直接忽略。
重要的是, 我們需要 倉庫 所對應的 ID

比如, 我需要blog倉庫的ID

  1. for i in Repo_Result:
  2. if 'blog' == i['slug']:
  3. print(i['id'])
  1. 646554

有了ID, 就可以查看倉庫內的文章了。 同樣的, 我們更新文章,也需要獲得ID

發表一篇新文章

Document
data 格式

  1. Doc_ID = '646554'
  2. url = 'https://www.yuque.com/api/v2/repos/'+Doc_ID+'/docs'
  3. data = {
  4. #'id': 我不想指定, 還是隨機吧
  5. 'slug': 'test3' , # 這個還是最好要一個。 這個是網址
  6. 'title': '又來測試了', # 這就不用多說了吧。
  7. 'format': 'markdown', # 這必須markdown 呀
  8. 'body': "# 這是第一個小標題<br>這是正文\n這個看看有效沒,換行符號",
  9. 'status': "1" # 0 是草稿, 直接發佈把
  10. }
  11. BACK = requests.post(url, data= data, headers = header).json()['data']
  12. print(Doc_Result[0])

這就, 成功啦~!
瓦雀.py| 使用python腳本更新維護語雀文檔 - 图2

註: slug 必須是唯一的, 所以最好先檢查slug是否存在

  1. def Slug_check(slug):
  2. try:
  3. requests.get(url+'/'+slug, headers = header).json()['status']
  4. print('slug is unique')
  5. return True
  6. except:
  7. print('Please check the slug. It may be occupied already.')
  8. return False

查看倉庫中的文章

  1. Repos_ID = '646554'
  2. url = 'https://www.yuque.com/api/v2/repos/'+Repos_ID+'/docs'
  3. Doc_Result = requests.get(url, headers = header).json()['data']
  4. print(Doc_Result[0])
  1. {'id': 32290390, 'slug': 'test3', 'title': '又來測試了', 'description': None, 'user_id': 691897, 'book_id': 646554, 'format': 'markdown', 'public': 1, 'status': 1, 'view_status': 0, 'read_status': 1, 'likes_count': 0, 'comments_count': 0, 'content_updated_at': '2021-03-03T14:33:25.000Z', 'created_at': '2021-03-03T14:33:25.000Z', 'updated_at': '2021-03-03T14:33:43.000Z', 'published_at': '2021-03-03T14:33:25.000Z', 'first_published_at': '2021-03-03T14:33:25.000Z', 'draft_version': 0, 'last_editor_id': 691897, 'word_count': 24, 'cover': None, 'custom_description': None, 'last_editor': {'id': 691897, 'type': 'User', 'login': 'liuwenkan', 'name': 'Karroben', 'description': '博客:https://karobben.github.io\n若不兼容情况, 请移步gitpage浏览(看地址)', 'avatar_url': 'https://cdn.nlark.com/yuque/0/2019/jpeg/anonymous/1576914522864-5dabd37e-9a90-4ee4-96b4-a1973dbcede4.jpeg', 'followers_count': 21, 'following_count': 2, 'created_at': '2019-12-21T07:49:03.000Z', 'updated_at': '2021-03-03T11:29:54.000Z', '_serializer': 'v2.user'}, 'book': None, '_serializer': 'v2.doc'}

可以看見, 第一篇文章, 是最新發的。 更新這篇文章把, 已知id32290390

  1. Doc_ID = '32290390'
  2. url = 'https://www.yuque.com/api/v2/repos/'+Repos_ID+'/docs/'+Doc_ID
  3. data = {
  4. #'id': 我不想指定, 還是隨機吧
  5. 'slug': 'test3' , # 這個還是最好要一個。 這個是網址
  6. 'title': '標題也改一下把', # 這就不用多說了吧。
  7. 'format': 'markdown', # 這必須markdown 呀
  8. 'body': "# 這是第一個小標題\n\n這是正文\n換行符號.`來看看代碼框把'\n'`",
  9. 'status': "1" # 0 是草稿, 直接發佈把
  10. }
  11. Doc_Result = requests.put(url, data = data, headers = header).json()['data']
  12. print(Doc_Result[0])

瓦雀.py| 使用python腳本更新維護語雀文檔 - 图3
完美~

腳本化

配置文件準備

準備yuque.yml文件

  1. repo: 'xiaoming/blog'

Markdown 標題格式

  1. ---
  2. title: ""
  3. url: ''
  4. date: ''
  5. ---

爲了安全起見, 我選擇單獨把Token保存在一個文件裏面, 給路徑來讀取

  1. echo $Token > ~/.yuqueToken
  1. import yaml
  2. import requests
  3. import os
  4. def Yml_json(yml):
  5. f = open(yml, 'r')
  6. ystr = f.read()
  7. aa = yaml.load(ystr, Loader=yaml.FullLoader)
  8. return aa
  9. def ReporsID_get(Identity):
  10. url = 'https://www.yuque.com/api/v2/users/' + Identity['repo'].split('/')[0]+"/repos"
  11. header = {"X-Auth-Token": Identity['Token']}
  12. List = requests.get(url, headers = header).json()['data']
  13. for i in List:
  14. if Identity['repo'].split('/')[1] == i['slug']:
  15. Repos_ID = i['id']
  16. return Repos_ID
  17. def DocList_get(Repos_ID):
  18. header = {"X-Auth-Token": Identity['Token']}
  19. url = 'https://www.yuque.com/api/v2/repos/'+str(Repos_ID)+'/docs'
  20. Doc_Result = requests.get(url, headers = header).json()['data']
  21. return Doc_Result
  22. def MDbody_clean(MD_body):
  23. MD_body = MD_body[MD_body.find('---',1)+3:]
  24. # 語雀不支持```text標籤
  25. MD_body = MD_body.replace("```text", '```text')
  26. MD_body = MD_body.replace("```", '```')
  27. # 添加封面圖片
  28. F = open(MD,'r').read()
  29. Data_header = yaml.load(F.split('---')[1], Loader=yaml.FullLoader)
  30. try:
  31. CP = Data_header['covercopy']
  32. except:
  33. CP = ""
  34. MD_body = "|![](" + Data_header['cover']+")|\n" + "|:--:|\n" + "|"+CP+"|\n" + MD_body
  35. # 加個尾巴
  36. MD_body += '''
  37. ---
  38. * Enjoy~
  39. 本文由<span style='color:salmon'>Python腳本</span>[GitHub](https://karobben.github.io/2021/03/02/Python/yuqueAPI)/[語雀](https://www.yuque.com/liuwenkan/python/yuque_api)自動更新
  40. <span style='color:salmon'>由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~</span>
  41. GitHub: [Karobben](https://github.com/Karobben)
  42. Blog:[Karobben](https://karobben.github.io/)
  43. BiliBili:[史上最不正經的生物狗](https://space.bilibili.com/393056819)
  44. '''
  45. return MD_body
  46. def MDupDate(MD, Repos_ID, Doc_list):
  47. # read MD file
  48. F = open(MD,'r').read()
  49. Data_header = yaml.load(F.split('---')[1], Loader=yaml.FullLoader)
  50. # find the ID by slug/url
  51. for i in Doc_list:
  52. if Data_header['url'] == i['slug']:
  53. data = {
  54. #'id': 我不想指定, 還是隨機吧
  55. 'slug': i['slug'], # 這個還是最好要一個。 這個是網址
  56. 'title': Data_header['title'], # 這就不用多說了吧。
  57. 'format': 'markdown', # 這必須markdown 呀
  58. 'body': MDbody_clean(F),
  59. 'status': "1" # 0 是草稿, 直接發佈把
  60. }
  61. Doc_ID = i['id']
  62. header = {"X-Auth-Token": Identity['Token']}
  63. url = 'https://www.yuque.com/api/v2/repos/'+str(Repos_ID)+'/docs/'+ str(Doc_ID)
  64. Doc_Result = requests.put(url, data = data, headers = header).json()['data']
  65. print(MD,"is updated")
  66. Token = open('/home/ken/.yuqueToken','r').read().strip()
  67. Identity = Yml_json('yuque.yml')
  68. Identity.update({'Token':Token})
  69. Repos_ID = ReporsID_get(Identity)
  70. Doc_list = DocList_get(Repos_ID)
  71. for MD in os.listdir():
  72. if ".md" == MD[-3:]:
  73. print("updating for:", MD)
  74. try:
  75. MDupDate(MD, Repos_ID, Doc_list)
  76. except:
  77. print( '\033[91m' + "UPDAT FAILED!!!" + '\033[0m')

最後, 我麼把他寫成腳本吧

功能:

  • 更新markdown文件
  • 獨立語雀標題
  • 填上icarus的封面圖
  • 添加尾墜
  • 添加Gitpage本文鏈接
  • 修改語雀不支持的```text標籤
    不能:
  • 創建新文件(請使用瓦雀, 我怕太多太混亂了)
  • 目錄編輯(瓦雀即可實現)
  1. #!/usr/bin/env python3
  2. import argparse
  3. parser = argparse.ArgumentParser()
  4. parser.add_argument('-i','-I','--input',nargs='+') #输入文件
  5. parser.add_argument('-t','-T','--token') #输入文件
  6. parser.add_argument('-c','-C','--category', default= "summary.md") #输入文件
  7. args = parser.parse_args()
  8. INPUT = args.input
  9. Token = args.token
  10. Category = args.category
  11. import threading
  12. import concurrent.futures
  13. import yaml
  14. import requests
  15. import os, re
  16. def Yml_json(yml):
  17. f = open(yml, 'r')
  18. ystr = f.read()
  19. aa = yaml.load(ystr, Loader=yaml.FullLoader)
  20. return aa
  21. def ReporsID_get(Identity):
  22. url = 'https://www.yuque.com/api/v2/users/' + Identity['repo'].split('/')[0]+"/repos"
  23. header = {"X-Auth-Token": Identity['Token']}
  24. List = requests.get(url, headers = header).json()['data']
  25. for i in List:
  26. if Identity['repo'].split('/')[1] == i['slug']:
  27. Repos_ID = i['id']
  28. return Repos_ID
  29. def DocList_get(Repos_ID):
  30. header = {"X-Auth-Token": Identity['Token']}
  31. url = 'https://www.yuque.com/api/v2/repos/'+str(Repos_ID)+'/docs'
  32. Doc_Result = requests.get(url, headers = header).json()['data']
  33. return Doc_Result
  34. def MDbody_clean(MD_body):
  35. MD_body = MD_body[MD_body.find('---',1)+3:]
  36. # 語雀不支持```text標籤
  37. try:
  38. AA = re.findall("```text]+>", MD_body)
  39. for PRE in AA:
  40. MD_body = MD_body.replace(PRE, '```text')
  41. except:
  42. PRE = "```text"
  43. print(PRE, "IAMHERE")
  44. print(MD_body)
  45. MD_body = MD_body.replace("```text", '```text')
  46. MD_body = MD_body.replace("```", '```')
  47. # 添加封面圖片
  48. F = open(MD,'r').read()
  49. Data_header = yaml.load(F.split('---')[1], Loader=yaml.FullLoader)
  50. try:
  51. CP = Data_header['covercopy']
  52. CP = "|![](" + Data_header['cover']+")|\n" + "|:--:|\n" + "|"+CP+"|\n"
  53. except:
  54. CP = ""
  55. # 添加本文github鏈接
  56. try:
  57. git_url = "".join([ "\n<span style='color:salmon'>由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~</span>",
  58. "\n[本文GitPage地址]",
  59. "(https://karobben.github.io/",
  60. str(Data_header['date']).split(' ')[0].replace("-","/"), "/",
  61. os.getcwd().split("/")[-1],"/",
  62. MD[:-3],
  63. ")\n"])
  64. except:
  65. git_url = ""
  66. # 合併前面的所有
  67. MD_body = CP+ git_url + MD_body
  68. # 加個尾巴
  69. MD_body += '''
  70. ---
  71. **Enjoy~**
  72. 本文由<span style='color:salmon'>Python腳本</span>[GitHub](https://karobben.github.io/2021/03/02/Python/yuqueAPI)/[語雀](https://www.yuque.com/liuwenkan/python/yuque_api)自動更新
  73. %%%
  74. GitHub: [Karobben](https://github.com/Karobben)
  75. Blog:[Karobben](https://karobben.github.io/)
  76. BiliBili:[史上最不正經的生物狗](https://space.bilibili.com/393056819)
  77. '''.replace("%%%",git_url)
  78. return MD_body
  79. def MDupDate(MD, Repos_ID, Doc_list):
  80. # read MD file
  81. F = open(MD,'r').read()
  82. Data_header = yaml.load(F.split('---')[1], Loader=yaml.FullLoader)
  83. # find the ID by slug/url
  84. if Data_header['url'] in [x['slug'] for x in Doc_list]:
  85. # 如果有單獨指定語雀標題:
  86. try:
  87. if Data_header['ytitle'] == "" :
  88. Title = Data_header['title']
  89. else:
  90. Title = Data_header['ytitle']
  91. except:
  92. Title = Data_header['title']
  93. data = {
  94. #'id': 我不想指定, 還是隨機吧
  95. 'slug': Data_header['url'], # 這個還是最好要一個。 這個是網址
  96. 'title': Title, # 這就不用多說了吧。
  97. 'format': 'markdown', # 這必須markdown 呀
  98. 'body': MDbody_clean(F),
  99. 'status': "1" # 0 是草稿, 直接發佈把
  100. }
  101. Doc_ID = [x['id'] for x in Doc_list][[x['slug'] for x in Doc_list].index(Data_header['url'])]
  102. header = {"X-Auth-Token": Identity['Token']}
  103. url = 'https://www.yuque.com/api/v2/repos/'+str(Repos_ID)+'/docs/'+ str(Doc_ID)
  104. Doc_Result = requests.put(url, data = data, headers = header).json()['data']
  105. print(MD,"is updated")
  106. else:
  107. print(MD,' \033[91m', "這個文件還沒有被創建。我懶得寫一個新建接口了(防止太混亂)\n所以請覈對以後, 先上新建這個文件,再來更新把= =推薦用瓦雀直接創建", '\033[0m')
  108. def Categ(Category):
  109. try:
  110. List = open(Category,'r').read().replace(" ",'').split("](")
  111. Cate_list = [A.split(")")[0] for A in List][1:]
  112. return "導入成功", Cate_list
  113. except:
  114. return "導入失敗", []
  115. def run(MD):
  116. print("updating for:", MD)
  117. Cate_state , Cate_reuslt = Categ(Category)
  118. print("目錄:", Cate_state)
  119. try:
  120. Data_header = yaml.load(open(MD,'r').read().split('---')[1], Loader=yaml.FullLoader)
  121. if Data_header['url'] not in Cate_reuslt and Cate_state == "導入成功" :
  122. print(MD +' \033[91m', "該文檔未加入目錄", '\033[0m')
  123. MDupDate(MD, Repos_ID, Doc_list)
  124. except:
  125. print( MD + ' \033[91m' + "UPDAT FAILED!!!" + '\033[0m')
  126. # 線程等待
  127. Token = open(Token,'r').read().strip()
  128. # Token = open('/home/ken/.yuqueToken','r').read().strip()
  129. Identity = Yml_json('yuque.yml')
  130. Identity.update({'Token':Token})
  131. Repos_ID = ReporsID_get(Identity)
  132. Doc_list = DocList_get(Repos_ID)
  133. for MD in INPUT:
  134. run(MD)
  135. '''
  136. if __name__ == "__main__":
  137. with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
  138. executor.map(run, INPUT)
  139. '''

Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗