Skip to content

Instantly share code, notes, and snippets.

@okusama27
Last active December 23, 2017 09:22
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 okusama27/08582d8c203883844c96ce7c0e28b38d to your computer and use it in GitHub Desktop.
Save okusama27/08582d8c203883844c96ce7c0e28b38d to your computer and use it in GitHub Desktop.
"""Togglの作業をslackに書き込む."""
import requests
import json
# Slack hooks
SLACK_HOOKS_URL = '[slack hook url]'
TOGGL_API_TOKEN = '[toggle token]'
file_name = './toggl_history.txt'
def get_toggl():
headers = {'content-type': 'application/json'}
auth = requests.auth.HTTPBasicAuth(TOGGL_API_TOKEN, 'api_token')
current = requests.get('https://www.toggl.com/api/v8/time_entries/current', auth=auth, headers=headers)
if current.status_code != 200:
print("togglの情報取得に失敗しました")
return None, None
current_json = current.json()
if not current_json['data']:
return None, None
return current_json['data']['pid'], current_json['data']['description']
def get_project_name(pid):
headers = {'content-type': 'application/json'}
auth = requests.auth.HTTPBasicAuth(TOGGL_API_TOKEN, 'api_token')
current = requests.get('https://www.toggl.com/api/v8/projects/{}'.format(pid), auth=auth, headers=headers)
if current.status_code != 200:
print("togglの情報取得に失敗しました")
return None
current_json = current.json()
if not current_json['data']:
return None
return current_json['data']['name']
def check_old_toggl(pid, description):
str_history = '{}:{}'.format(pid, description)
with open(file_name, mode='r', encoding='utf-8') as f:
history = f.read()
if history.strip() == str_history:
return True
write_history(str_history)
return False
def write_history(str_history):
with open(file_name, mode='w', encoding='utf-8') as fw:
fw.write(str_history)
def write_slack(pname, description):
text = """Userが仕事を開始したよ
```プロジェクト名: {project}
作業内容: {detail}```
""".format(project=pname, detail=description)
payload = {'channel': '#チャンネル名',
'username': 'Toggl',
'text': text,
'icon_emoji': ':toggl:'}
requests.post(SLACK_HOOKS_URL, data=json.dumps(payload))
if __name__ == '__main__':
# 現在のタスクの取得
pid, description = get_toggl()
if not pid:
write_history('')
exit(1)
if check_old_toggl(pid, description):
# 前回取得したものと同じ場合は終了
exit(1)
# プロジェクト名の取得
p_name = get_project_name(pid)
if not p_name:
exit(1)
# slackへの書き込み
write_slack(p_name, description)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment