【画像で説明】AlfredからGoogleTasks(ToDo)にタスクを追加するWorkflowをPythonで作る
やりたいこと
こうしたら
⇣
こうっ
こうしたら
⇣
こうっ
前提条件
- Mac OS
- Alfredのインストール (https://www.alfredapp.com/)
- Alfred Powerpack購入済 (https://www.alfredapp.com/shop/)
- Googleアカウント作成済
今回説明するworkflowは無料版では使えない機能のため、Powerpackの購入が必要となります。
Powerpackの料金は2020-11-15現在のレートで約¥6,770でした。
GCPアカウントの作成
Google Tasks APIを使うためにGCPアカウントが必要になります。
認証準備
Quickstartをつかう方法
こちらのクイックスタートを利用すると、
- GCPプロジェクトの作成
- Tasks APIの有効化
- OAuth2.0クライアントIDの作成
- 認証キー(credentials.json)のダウンロード
をまとめて行うことができます。
とりあえずDesktop appで問題ありませんでした。
通常のプロジェクト作成 ~ 認証キー取得まで
プロジェクト作成
Tasks APIの有効化
OAuth2.0クライアントIDの作成
こんな画面が出てきますが、この情報は今回は不要です。
認証キー(credentials.json)のダウンロード
AlfredのWorkflowを作る
ここからはAlfredの設定画面をさわっていきます。
⇣ ひとまずNameだけあれば大丈夫です。
/Users/ユーザー名/Library/Application Support/Alfred/Alfred.alfredpreferences/workflows/
の中に user.workflow.xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/
みたいなディレクトリが作られます。
このディレクトリがAlfredからPythonファイルを実行するさいのカレントディレクトリになります。
Pythonファイルの作成
先程のuser.workflow.xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/
ディレクトリの中に好きな名前でファイルを作ります。
今回はadd_task.py
というファイルで。
$ cd /Users/ユーザー名/Library/Application Support/Alfred/Alfred.alfredpreferences/workflows/user.workflow.xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
$ touch add_task.py
さきほどダウンロードした credentials.json
も add_task.py
と同じディレクトリに置きます。
ライブラリのインストール
google-api-python-client
google-auth-httplib2
google-auth-oauthlib
の3つが必要。
$ pip install --target=. google-api-python-client google-auth-httplib2 google-auth-oauthlib
user.workflow.xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/
ディレクトリの中で、pip installします。
--target
オプションで.(カレントディレクトリ)
を指定することで、ディレクトリ内に依存ライブラリを含む一式をインストールできます。
このやり方でないと、not found的なエラーで一生前に進めませんでした。
仮想環境を使うやり方などありましたら教えて下さい🙇
コード
クイックスタートのコードをベースにしています。
from __future__ import print_function
import pickle
import os.path
import sys
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/tasks']
def main():
"""Shows basic usage of the Tasks API.
Prints the title and ID of the first 10 task lists.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
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)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('tasks', 'v1', credentials=creds)
# Call the Tasks API
results = service.tasklists().list(maxResults=10).execute()
items = results.get('items', [])
title = sys.argv[1]
if items:
task = {
'title': title,
}
result = service.tasks().insert(tasklist='@default', body=task).execute()
if __name__ == '__main__':
main()
以下、主な変更点です。
タスク追加用にスコープを変更しています。
...
SCOPES = ['https://www.googleapis.com/auth/tasks.readonly']
⇣
SCOPES = ['https://www.googleapis.com/auth/tasks']
...
コマンドライン引数でタスク名を渡し、タスクに追加するように改変しています。
title = sys.argv[1]
if items:
task = {
'title': title,
}
result = service.tasks().insert(tasklist='@default', body=task).execute(
Workflowの中身
Keywordを指定
KeywordはAlfredの先頭に打ち込む文字列。
ここではtask hoge
でhogeがタスクとして追加されるようになる。
次は、Action > Run Script
実行するPythonファイルを指定する。
ドラッグして繋げば完成
動作確認
試してみる。
初回は認証が必要。
許可で。
許可で。
こんな画面になったら認証完了。
閉じる。
改めまして
成功。
Oauth認証は2回目以降は不要です。
初回認証時に token.pickle
というファイルが生成され、認証情報が保存されているようです。
参照
ありがとうございました。