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

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

Office365のOutlook APIをpythonで叩いてSlackに本日と翌営業日の予定をPostしようとしてみる(3)Azure appからカレンダー一覧を取得する

2019-06-09

Office365のOutlook APIをpythonで叩いてSlackに本日と翌営業日の予定をPostしようとしてみる
しようとしてみるという理由は、slack botの申請がまだ降りていないので、実際にslackのポストまでは試せていないせいということ、、、

フルコードはこちら
https://github.com/yoshi-island/o365_slack_work

前回の記事はこちら

Python環境整備

Pythonは3.5.0でやる

% python -V
Python 3.5.0

python-o365をインストール

% git clone https://github.com/O365/python-o365

python必要モジュールをインストール
python-o365にrequirements.txtが入っているのでそれらをダウンロードすれば良い

% pip install -r python-o365/requirements.txt

これで無事にモジュールが入った

% pip freeze
beautifulsoup4==4.7.1
certifi==2019.3.9
chardet==3.0.4
idna==2.8
oauthlib==3.0.1
python-dateutil==2.8.0
pytz==2019.1
requests==2.22.0
requests-oauthlib==1.2.0
six==1.12.0
soupsieve==1.9.1
stringcase==1.2.0
tzlocal==1.5.1
urllib3==1.25.3

Azureとの接続確認(Azure appからカレンダー一覧を取得する)

同じ階層にパスワードファイルを作成する
先ほど控えておいた、client idとclient secretを記載する

% cat password_list.py
client_id = 'azure app client id'
client_secret = 'azure app client secret'

同じ階層に、このようなファイルを作成する

% cat login_test.py
# avoid ssl error
import urllib3
urllib3.disable_warnings()

# import python-o365
import sys
sys.path.insert(0, './python-o365')

import datetime as dt
from O365 import Account
import password_list

# outlook
client_id = password_list.client_id
client_secret = password_list.client_secret
account = Account((client_id, client_secret))

if not account.is_authenticated:
    account.authenticate(scopes=['basic', 'calendar_all'])

schedule = account.schedule()
calendar = schedule.list_calendars()

print(calendar)

実行するとカレンダー一覧が取得できる

初回(o365_token.txtが無いと)は、Paste the authenticated url here: と聞かれるので
Visit the following url to give consent: の後ろにあるURLにアクセスし、返ってきたURLを貼り付けると実行できる

% python login_test.py
...
Visit the following url to give consent:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?......&access_type=offline
Paste the authenticated url here: https://login.microsoftonline.com/common/oauth2/nativeclient?......
Authentication Flow Completed. Oauth Access Token Stored. You can now use the API.
[Calendar: Calendar from yoshi (outlook_hoge@outlook.com), Calendar: Birthdays from yoshi (outlook_hoge@outlook.com), Calendar: Tasks from yoshi (outlook_hoge@outlook.com)]

ここまでくればAzure(Office365)側はOK

Trouble Shooting

以下のようなエラーが出たら、Azure Appを作る際に、Supported account typesに”Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com)”を選択していない可能性があるので見直すべし

unauthorized_client: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908.

続きはこちら