LoginSignup
8
2

More than 3 years have passed since last update.

使っていない会議予約を撲滅する

Posted at

はじめに

オプトテクノロジーズの伊藤です。
完全なるアドカレドリブンな投稿。そしてクリスマスを跨ぐというもはやアドカレですらありません。
さて、今回は前回の投稿で試作したIoTデバイスを社内の全会議室に導入するにあたり、使っていない会議予約を撲滅する技術をご紹介します。

前提

弊社には会議室の利用ルールとして「ミーティング開始時間を5分経過した後に在室していなければキャンセル扱いで他の利用者が使って良い」があり、そのルールに則り、15分間隔でこの仕組みによって在室チェックし、不在判定ならGoogleカレンダーをこねくり回します。

準備

1.Google Calendar APIの設定
ここについては私が解説するよりも、Googleさんが用意された各言語に対応したガイドをご参照いただく方が良さげなので割愛します。

2.ライブラリの準備(以降はPythonです)
これだけです。

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

実装

エラーハンドリングや通知系の実装を省いたコードを抜粋します。

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

def main():
    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', ['https://www.googleapis.com/auth/calendar'])
            creds = flow.run_local_server()
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token, protocol=2)

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

    # カレンダー取得日時の範囲を指定
    now = datetime.datetime.today()
    fromDt = now - datetime.timedelta(minutes=5) - datetime.timedelta(hours=9)
    toDt = now - datetime.timedelta(hours=9)

    # カレンダー取得
    resourceId = カレンダーにリソース登録されているID
    events_result = service.events().list(calendarId=resourceId, timeMin=fromDt.isoformat() + 'Z', timeMax=toDt.isoformat() + 'Z', maxResults=1, singleEvents=True).execute()
    events = events_result.get('items', [])

    # カレンダー削除
    deleted_event = service.events().delete(calendarId=resourceId, eventId=events[0]['id']).execute()

if __name__ == '__main__':
    main()

1.で用意した credentials.json と同じディレクトリに配置し、

python qcalendar.py

で実行する(初回実行時のみブラウザが起動するのでカレンダー編集可能なアカウントで諸々の操作を許可する)。

実行した結果、問題なければ15分間隔で起動するようにCron登録して完成。

5,20,35,50 * * * * /usr/bin/python /hoge/qcalendar.py

感想

  • 時刻の取り扱いには注意。全てUTCで扱えばいいのかもしれないが、そうでないと時差やサマータイムでズレが生じる。
  • カレンダーの繰り返し予約全てを削除するのは試していない(singleEvents=True を取り除くとおかしな挙動がある)
8
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
8
2