AWS のサポートケースをテキストファイルに出力するコード

AWS のサポートケースの検索がなんだかめんどくさいので、ケースごとに返信を1つのテキストファイルにまとめるスクリプトを書いた。

前提

  • boto3 が pip install されている
  • AWS_PROFILE 環境変数がセットされている

code

import os
import shutil

import boto3

client = boto3.client("support")

OUTPUT_DIR = "output"


def reset_output():
    if os.path.isdir(OUTPUT_DIR):
        shutil.rmtree(OUTPUT_DIR)
    os.mkdir(OUTPUT_DIR)


def write_comms(case_id, filepath):
    comms = []
    next_token = None
    while True:
        params = {
            "caseId": case_id,
        }
        if next_token:
            params["nextToken"] = next_token
        comm_res = client.describe_communications(**params)
        print(comm_res.get("ResponseMetadata", {}).get("HTTPStatusCode"))
        for comm in comm_res.get("communications"):
            author = comm.get("submittedBy")
            ts = comm.get("timeCreated")
            body = comm.get("body")
            if "お客様の問題解決にお役に立てたでしょうか" in body:
                continue
            comms.append(
                "\n".join(
                    [
                        f"author: {author}",
                        f"timestamp: {ts}",
                        "",
                        body,
                    ]
                )
            )
        # write to file
        with open(filepath, "a") as f:
            f.write("\n\n-------\n\n".join(comms))
        comms = []
        with open("output.json", "w") as f:
            f.write(str(comm_res))
        next_token = comm_res.get("nextToken")
        if next_token is None:
            break


def main():
    reset_output()
    next_token = None
    csv_lines = [["caseId", "displayId", "subject", "serviceCode", "timestamp"]]

    while True:
        params = {
            "includeResolvedCases": True,
            "language": "ja",
            "includeCommunications": False,
        }
        if next_token:
            params["nextToken"] = next_token
        case_res = client.describe_cases(**params)
        for case in case_res.get("cases"):
            caseId = case.get("caseId")
            print(f"processing case {caseId}")
            displayId = case.get("displayId")
            filepath = f"output/{displayId}.txt"

            subject = case.get("subject")
            serviceCode = case.get("serviceCode")
            timestamp = case.get("timeCreated")
            csv_lines.append([caseId, displayId, subject, serviceCode, timestamp])
            with open(filepath, "w") as f:
                f.write(
                    "\n".join(
                        [
                            f"subject: {subject}",
                            f"serviceCode: {serviceCode}",
                            f"timestamp: {timestamp}",
                            "-------\n\n",
                        ]
                    )
                )
            write_comms(caseId, filepath)
        next_token = case_res.get("nextToken")
        if next_token is None:
            break

    with open(f"{OUTPUT_DIR}/files.csv", "w") as f:
        f.write("\n".join([",".join(line) for line in csv_lines]))


if __name__ == "__main__":
    main()
    print("done!")