LoginSignup
1
2

More than 3 years have passed since last update.

Lambda(CloudWatch) + Pythonでシフト勤務の報告ページをConfluenceに自動作成する

Last updated at Posted at 2019-10-04

はじめに

シフトページを自動化するPythonコードを書いてみた。

構造

  • テンプレート構造
    親スペース[SPACE_KEY] ━ 親ページ[oya_page] ━ 月ページ[月テンプレート] ━ 日ページ[日テンプレートA]
                                       ┗ 日ページ[日テンプレートB]

  • 稼働後の構造:月と日のページが出来上がる
    親スペース[SPACE_KEY] ━ 親ページ[oya_page] ━ 月ページ[YYYY/MM] ━ 日ページ[YYYY/MM/DD_A]
                                    ┗ 日ページ[YYYY/MM/DD_B]
    ※ページがYYYY/MM~となっているのはコンフルの一意制約対策

APIキー(AUTH=)取得

コード

変数名はご愛敬

import requests
import json
import re
import datetime

BASE_URL = "https://★コンフルのURL★.atlassian.net/wiki/rest/api"
AUTH = ("★コンフルのID★","★コンフルのPW★")
HEADERS = {"content-type":"application/json"}
SPACE_KEY = "★コンフルのスペースキー★"
NEW_DATE = datetime.datetime.now() + datetime.timedelta(days=7) # 一週間後指定(lambdaでの実行はUTC+7日後)

def lambda_handler(event, context):
    parent_id = monthpage_create()

    shiftpage_create("★日テンプレートAの名前★","★付属したい任意の文字(例:A)★", parent_id)
    shiftpage_create("★日テンプレートBの名前★","★付属したい任意の文字(例:B)★", parent_id)

def monthpage_create():
    template_title_month = "★月テンプレページの名前★"
    new_page_title_month = NEW_DATE.strftime("%Y/%m")
    oya_page = "★親ページのIDを指定"

    # 月初は新規ページ作成
    if NEW_DATE.strftime("%d") == "01":
        # コピー元(月テンプレ)ページ情報取得
        get_result_month = get_page(template_title_month)
        parent_id = post_page(new_page_title_month, get_result_month[1], oya_page)
        print("Create MonthPage : " + new_page_title_month + " PageId : " + parent_id)
    else:
        get_result_month = get_page(new_page_title_month)
        parent_id = get_result_month[0]

    return parent_id

def shiftpage_create(template_title_day, shift, parent_id):
    # シフトのページタイトル作成
    yobi = ["月","火","水","木","金","土","日"]
    dow =  yobi[NEW_DATE.weekday()] # 曜日取得(day of the week)
    new_page_title_day = NEW_DATE.strftime("%Y/%m/%d") + ("(") + dow + (")") + shift

    # コピー元(シフトテンプレ)ページ情報取得
    get_result_day = get_page(template_title_day)
    # シフトページ作成
    shiftpage_id = post_page(new_page_title_day, get_result_day[1], parent_id)
    print("Create DayPage : " + new_page_title_day  + " PageId : " + shiftpage_id)

# ページを取得
# return:
# [0] = id
# [1] = contents
def get_page(title):
    response_get = requests.get(
        BASE_URL+"/content",
        auth=AUTH,
        params={
            "title":title,
            "spacekey":SPACE_KEY,
            "expand":"body.storage.value"
        }
    )
    response_get.raise_for_status()
    json_contents  = json.loads(response_get.content.decode("utf-8"))
    contents = json_contents["results"][0]["body"]["storage"]["value"]
    page_id = json_contents["results"][0]["id"]

    return page_id, contents

# ページを新規作成
# return: id
def post_page(title, contents, parent_id):
    payload = {
        "type": "page",
        "title": title,
        "ancestors": [{"id": parent_id}],
        "space": {"key": SPACE_KEY},
        "body": {
            "storage": {
                "value": contents,
                "representation": "storage" 
                # ↑の部分アトラシアンの仕様上APIでの作成は旧エディタで作成することになるようで、editor2が良いらしい(2020/1時点未実装のようだが)
            }
        }
    }

    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"))
    create_id = json_create_contents["id"]

    return create_id

Lambda + CloudWatchへの登録

以下雑です。
1.以下コマンドをlinux環境で実行して上のソースと一緒にzip化する
pip install requests

2.CloudWatchに時間登録

※CloudFormation使った登録は別で

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2