はじめに

ABEMAの広告プロダクト開発でサーバーサイドエンジニアをしているimaiです。

今回はCyberAgent PTA Advent Calendar 2020の22日目の記事になります。

きっかけ

部署内でプレゼン資料を自動で作成したい。ってお話があったのでGoogle Slidesを編集するアプリを作成しました。
そこで Golang にて Slides API を実行して実現しておりその中で得た知見を気していこうと思います。

実行してみる

サービスを作る

クイックスタートでは slides.New(client *http.Client) を使用していますがこれは Deprecated となっているので slides.NewService(ctx context.Context, opts …option.ClientOption) を使用します

import (
    "context"
    "log"

    "golang.org/x/oauth2"
    "google.golang.org/api/option"
    "google.golang.org/api/slides/v1"
)

func newSlidesService(ctx context.Context, tokenSource oauth2.TokenSource) *slides.Service {
    srv, err := slides.NewService(ctx, option.WithTokenSource(tokenSource))
    if err != nil {
        log.Panicf("failed to slides new service: %+v", err)
    }
    return srv
}

テキストを挿入する

func setText(requests []*slides.Request, objectID, text string) []*slides.Request {
    return append(requests, &slides.Request{
        InsertText: &slides.InsertTextRequest{
            ObjectId: objectID, // 挿入先のオブジェクトID
            Text:     text,     // 挿入するテキスト
        },
    })
}

ページを削除する

func deleteSlides(requests []*slides.Request, objectID string) []*slides.Request {
    return append(requests, &slides.Request{
        DeleteObject: &slides.DeleteObjectRequest{
            ObjectId: objectID, // 削除するページのオブジェクトID
        },
    })
}

スライドの並び替え

InsertionIndex には先頭ページが0からのページ番号を指定します

func sortSlides(requests []*slides.Request, index int64, objectIDs []string) []*slides.Request {
    return append(requests, &slides.Request{
        UpdateSlidesPosition: &slides.UpdateSlidesPositionRequest{
            InsertionIndex: index,     // 挿入するページ番号
            SlideObjectIds: objectIDs, // 並び替えるスライドのオブジェクトID
        },
    })
}

更新

func update(slidesSrv *slides.Service, requests []*slides.Request, slidID string) {
    _, err := slidesSrv.Presentations.BatchUpdate(slidID, &slides.BatchUpdatePresentationRequest{Requests: requests}).Do()
    if err != nil {
        log.Panicf("failed to batch update: %+v", err)
    }
}

最後に

Slides APIには他にも便利なのがありそうなので色々試す価値はありそうです。
技術的な側面だけではなくビジネス的な側面から必要なの、便利になるのを探るのも良さそうですね。

bannerAds