yoshiislandblog.net
元営業の駆け出しアラサーSEが、休日にMACと戯れた際の殴り書きメモ。日々勉強。日々進歩。

この記事は3年以上前に書かれた記事で内容が古い可能性があります

outlook予定表とslackの連携

2017-06-04

outlookに[mtg][work]とかタグをつけて予定を入れているので、それを集計してslackにポストするスクリプトを書いてみた。

@bot outlook

とボットに話すと

start_month is 2017-06-01T00:00:00Z
end is 2017-06-10T23:59:59Z
{
    "[fun]": "0:0",
    "[move]": "1:35",
    "[mtg]": "12:30",
    "[other]": "0:0",
    "[study]": "6:0",
    "[work]": "52:30"
}

ひとまずこんな感じに返ってくる。(体裁はおいおい)

以下を使ってとりあえずできた。
python-o365
slackbot

slackの方

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from slackbot.bot import respond_to
from slackbot.bot import listen_to
from slackbot.bot import default_reply

import sys
import re

# 別ディレクトリ呼び込む
sys.path.insert(0, './python-o365')
import test_o365_cal
o365_cal = test_o365_cal


@default_reply()
def default_func(message):

    ## 受け取ったメッセージ
    text = message.body['text']

    ## o365 ##
    # 何も引数なければ、本日と月累計を出力する
    # start,end,start_month,category_all,category_all_month
    if text == "outlook":
      msg = o365_cal.execution()
      start = msg[0]
      end = msg[1]
      start_month = msg[2]
      category_all = msg[3]
      category_all_month = msg[4]
      msg = 'start: ' + start + '    end: ' + end + '\n' + category_all
      msg = str(msg)
      message.reply(msg)
      msg = 'start: ' + start_month + '    end: ' + end + '\n' + category_all_month
      msg = str(msg)
      message.reply(msg)


### o365 ###
# outlookに引数あればその日時を使う
@respond_to(r'^outlook\s+\d\d\d\d\d\d\d\d\s+\d\d\d\d\d\d\d\d\s*$')
def o365_func(message):
    text = str(message.body['text'])
    text = re.split('\s+', text)
    msg = o365_cal.execution(text[1],text[2])
    start = msg[0]
    end = msg[1]
    start_month = msg[2]
    category_all = msg[3]
    category_all_month = msg[4]
    msg = 'start: ' + start + '    end: ' + end + '\n' + category_all
    msg = str(msg)
    message.reply(msg)
    msg = 'start: ' + start_month + '    end: ' + end + '\n' + category_all_month
    msg = str(msg)
    message.reply(msg)

outlookの方

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from O365 import *
import json

# temp: to avoid ssl error
import urllib3
urllib3.disable_warnings()


import password_list
user = password_list.user
password = password_list.password
category_dict = password_list.category_dict # get password from other file

import time
import datetime
import re #find
import math


def get_date(start=None,end=None):

    # get time format
    time_string = '%Y-%m-%dT%H:%M:%SZ'

    # get today start time
    if start == None:
      start = time.strftime(time_string)
      start = start[0:10] + 'T00:00:00Z'

    # get today end time
    if end == None:
      end = time.strftime(time_string)
      end = end[0:10] + 'T23:59:59Z'

    # get month start time
    start_month = time.strftime(time_string)
    start_month = start_month[0:7] + '-01T00:00:00Z'

    return start,end,start_month


def get_calender_format(start=None, end=None, category_dict=None):

    if (start or end) == None:
      print('start or end is not defined')
      exit()

    if (category_dict) == None:
      print('category_dict is not defined')
      exit()

    schedules = []
    json_outs = {}

    e = user
    p = password

    schedule = Schedule((e,p))

    try:
        result = schedule.getCalendars()
        print('Fetched calendars for',e,'was successful:',result)
    except:
        print('Login failed for',e)


    # format category_dict
    category_dict = category_dict
    for key in category_dict.keys():
      category_dict[key] = 0

    bookings = []
    for cal in schedule.calendars:
        print('attempting to fetch events for',e)
        try:
            result = cal.getEvents(start=start,end=end, eventCount=100000) #fixme:eventcount want get all events
            print('Got events',result,'got',len(cal.events))
        except:
            print('failed to fetch events')

        print('attempting for event information')
        time_string_time = '%H:%M:%SZ' #fixme: event cannot be over a day
        time_string_time_sum = '%dT%H:%M:%SZ' #fixme: time sum cannot be over a month
        for event in cal.events:
            event = event.fullcalendarioJson()

            # append event time info
            end_time = time.mktime(time.strptime(event['end'], '%Y-%m-%dT%H:%M:%SZ'))
            start_time = time.mktime(time.strptime(event['start'], '%Y-%m-%dT%H:%M:%SZ'))
            event_time = end_time - start_time
            event_time = time.strftime(time_string_time, time.gmtime(event_time))
            event.update({'event_time': event_time})
            bookings.append(event)

            # update category dict
            for key in category_dict:
               title = event['title']
               if key in title:
                   n = category_dict[key]
                   # format
                   if ':' in str(event_time):
                       event_time = str(event_time)[0:-1].split(':')
                       event_time = int(event_time[0]) * 3600 + int(event_time[1]) * 60 + int(event_time[2])
                   n += event_time
                   category_dict[key] = n

    # format category_dict
    for key in category_dict.keys():
      category_sec = category_dict[key]
      category_hour = int(category_sec/60/60)
      category_min = int(category_sec/60%60)
      category_dict[key] = str(category_hour) + ':' + str(category_min)

    # format json
    events_all = json.dumps(bookings,sort_keys=True,indent=4, ensure_ascii=False)

    category_all = json.dumps(category_dict,sort_keys=True,indent=4, ensure_ascii=False)

    return(events_all, category_all)




def execution(start='YYYYMMDD',end='YYYYMMDD'):

    get_date_result = get_date()

    # set date time info
    start_month = get_date_result[2]
    if start == 'YYYYMMDD':
      start = get_date_result[0]
      end = get_date_result[1]
    else:
      YYYY = start[0:4]
      MM = start[4:6]
      DD = start[6:8]
      start = YYYY + '-' + MM + '-' + DD + 'T00:00:00Z'
      YYYY = end[0:4]
      MM = end[4:6]
      DD = end[6:8]
      end = YYYY + '-' + MM + '-' + DD + 'T23:59:59Z'

    # get todays work
    print('start is', start)
    print('end is', end)
    outputs = get_calender_format(start,end,category_dict)
    events_all = outputs[0]
    category_all = outputs[1]
    print(category_all)

    # reset dict
    for key in category_dict.keys():
      category_dict[key] = ''

    # get monthly work
    print('start_month is', start_month)
    print('end is', end)
    outputs_month = get_calender_format(start_month,end,category_dict)
    events_all_month = outputs_month[0]
    category_all_month = outputs_month[1]
    print(category_all_month)

    return start,end,start_month,category_all,category_all_month