概要
Confluence API があるということでPython で書いてみました。
背景としては毎週議事録をConfluence に記載するのですが、その枠を過去分からコピーして作成しなくてはならず、まぁちょっとした作業ではあるのですが、毎週勝手に生成されればいいのに、、、と思ったのがきっかけです。
- 参考
コード処理概要
- 特定のparent_id 配下で数字4文字のあるtitle をtitles に格納
- sortして一番新しいpage_title を保存
- そのPage title をキーにしてcontents をAPIでとってきて新規ページとして作成
- なお新しいページタイトルは実行日から三日後とする
本当はhipchat連携もしており、そこらへん無理に省いたのでうまく動かないかもです。
# -*- coding: utf-8 -*- import requests import json import re import datetime BASE_URL="http://confluence.testurl.com/rest/api" with open('credential','r') as file: Auth = tuple(file.read().strip().split(',')) HEADERS = {"content-type":"application/json"} SPACE_KEY="testspace" def main(): copy_page("16505174","議事録") def get_most_new_title(parent_id): response = requests.get( BASE_URL + "/search?cql=parent=" + parent_id, auth=Auth, ) response.raise_for_status() json_search_contents = json.loads(response.content.decode('utf-8')) titles = [] i = 0 for tmp in range(0, len(json_search_contents['results'])): data = json_search_contents['results'][i]['content']['title'] if (re.search('\d{4}', data)): # page title should include 201[89] as timestamp titles.append(data) i = i + 1 return sorted(titles)[-1] def copy_page(parent_id,new_page_title): old_page_title = get_most_new_title(parent_id) # Get Old Page Content response_get = requests.get( BASE_URL+"/content", auth = Auth, params={ "title":old_page_title, "spacekey":SPACE_KEY, "expand":"body.storage.value" } ) response_get.raise_for_status() json_contents = json.loads(response_get.content.decode('utf-8')) old_page_content = json_contents['results'][0]['body']['storage']['value'] # print(old_page_content) # Create new page new_date = datetime.datetime.now()+datetime.timedelta(days=3) # New pages timestamp should be now + 3days new_page_title=new_date.strftime('%Y-%m-%d')+" "+new_page_title payload = { "type": "page", "title": new_page_title, "ancestors": [{"id": parent_id}], "space": {"key": SPACE_KEY}, "body": { "storage": { "value": old_page_content, "representation": "storage" } } } response_create = requests.post( BASE_URL+"/content", auth=Auth, data=json.dumps(payload), headers=HEADERS ) response_create.raise_for_status() json_create_contents = json.loads(response_create.content.decode('utf-8')) # print(json_create_contents) create_id=json_create_contents['id'] return create_id if __name__ == '__main__': main()
所感
どうしてもコードが汚く感じる。。。 もう少しきれいにコードがかけるようになりたい。