LoginSignup
2
4

More than 3 years have passed since last update.

自動でVtuberの配信予定を更新するカレンダーを作ってみた (Google Calendar編)

Posted at

はじめに

この記事は、下記記事の続きになります。

自動でVtuberの配信予定を更新するカレンダーを作ってみた

前回はYouTubeから動画情報を取得したので、今回は取得した動画情報を元に、Googleカレンダーに予定を登録していきます。

環境

  • Azure VM (Windows Server 2016)
  • Python 3.7

用意するデータ

  • YouTube 動画情報
  • Google カレンダー カレンダーID

方法

今回はGoogleカレンダーに予定を登録していくので、当然登録先のカレンダーが必要になります。
なので、カレンダーの設定からカレンダーIDを予め確認しておきます。

あとは公式のサンプルに従って進めていくだけで簡単にカレンダーへの登録ができました。

1. Google カレンダーAPIの有効化

サンプルページにあるボタンを押すだけです。
合わせて、credentials.jsonを作業中のディレクトリに保存しておきます。

2. 必要なライブラリのインストール

書いてある通りにコマンドを実行します。

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

3. カレンダーへ予定を登録

サンプルコードを元にカレンダーへ予定を登録します。

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/calendar']

def insert_event(event, calendar_id):
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    event = {
        'summary': event.summary,
        'description': event.description,
        'start': {
            'dateTime': event.start_datetime,
            'timeZone': 'Japan',
        },
        'end': {
            'dateTime': event.end_datetime,
            'timeZone': 'Japan',
        }
    }
    event = service.events().insert(calendarId=calendar_id, body=event).execute()
    return event['id']

あとはこの関数に前回取得した動画情報からカレンダーへ登録する情報と、最初に確認したカレンダーIDを渡してあげれば完了です。
カレンダーに登録する情報はeventとして最低限のものだけを渡すことにしました。

  • summary: 動画タイトル
  • description: 動画URL
  • start_datetime: 配信開始時間
    • 基本はactualStartTimeを利用。配信開始前の動画はscheduledStartTimeで代替。
  • end_datetime: 配信終了時間
    • 基本はactualEndTimeを利用。配信開始前や配信中の場合はscheduledStartTimeの1時間後に設定。

戻り値のIDを控えておけば登録した予定の編集が可能なので、配信時間や動画タイトルの変更にも対応できます。

2
4
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
2
4