Skip to content

Instantly share code, notes, and snippets.

@ternbusty
Last active February 19, 2018 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ternbusty/e938d0c7959e4e018c46774f1e38be39 to your computer and use it in GitHub Desktop.
Save ternbusty/e938d0c7959e4e018c46774f1e38be39 to your computer and use it in GitHub Desktop.
大学の授業時間割を読み込みGoogle Calendarに自動で登録するスクリプト
# -*- coding: utf-8 -*-
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import datetime
import csv
import re
scheduled_times = (("08:45", "10:15"),
("10:30", "12:00"),
("13:00", "14:30"),
("14:45", "16:15"),
("16:30", "18:00"))
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly',] #読み込み・書き出しを行うためにはこの両方が必要
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Calendar API Python Quickstart'
def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
f = open('H293rdAutumn.csv', 'rt')
dataReader = csv.reader(f)
today = datetime.date.today()
year = 2018
count = 0
c = 1
for row in dataReader:
if count == 0:
previousRow = row
for a in range(1,8):
if row[a] == '':
row[a] = previousRow[a]
tsukihi = re.split('[月日]', row[1])
month = int(tsukihi[0])
day = int(tsukihi[1])
date = today.replace(year=year, month=month, day=day)
stime = scheduled_times[int(row[2]) - 1][0]
etime = scheduled_times[int(row[2]) - 1][1]
stimestr = tstr(date, stime)
etimestr = tstr(date, etime)
s = row[0]
d = row[3] + '(' + row[4] + ' ' + row[5] + ' ' + row[6] + ')'
l = row[7]
if row[0] != previousRow[0]: #教科名が変わったらcoloridを変更する
if c == 11:
c = 1
elif c == 7:
c = 9
else:
c += 1
if '試験' in row[3]: #授業内容に「試験」を含む時はカラーを灰色にする
prevc = c
c = 8
previousRow = row
count += 1
citem = {
"start":{"dateTime": stimestr},
"end": {"dateTime": etimestr},
"summary": s,
"location": l,
"description": d,
"colorId": c,
"transparency": "transparent",
"reminders":{
"useDefault": False,
"overrides": [] #通知を無効にするにはこのようにする
}
}
if '試験' in row[3]:
c = prevc
try:
events = service.events().insert(calendarId='primary',
body=citem).execute()
except client.AccessTokenRefreshError:
print ("The credentials have been revoked or expired, "
"please re-run the application to re-authorize")
print("Following events are created.", events)
f.close()
def tstr(date, time):
hour, minute = map(int, time.split(':'))
t1 = datetime.time(hour, minute)
dt = datetime.datetime.combine(date, t1)
return dt.strftime('%Y-%m-%dT%H:%M:00+09:00')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment