LoginSignup
3
4

More than 3 years have passed since last update.

Pythonでメール配信 + togglで残りの勤務時間を自動送信する

Last updated at Posted at 2018-07-09

はじめに

月の最後に勤怠時間を一気に記述するというスタイルの私は日頃からtogglで勤怠の時間管理をしています(会社はコアフレックスです)。
よくtogglのボタンを押すのを忘れるので、押せてなかったりそもそも働いてなかったら教えてくれる機能を作ろうと思ったというのが背景。
あとPython書きたかったお。

前提条件

  • Python3の実行環境
  • gmailアドレス(メールサーバがあればローカルでもレンタルサーバとかでも良い)
  • requests, json等のモジュール

ソースコード

send_mail.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import json
import smtplib
import datetime
import os
import sys
from email.mime.text import MIMEText
from email.utils import formatdate

API_KEY = "togglのApiKeyを記述"
MY_ADDRESS = "gmailアドレス"
MY_PASSWORD = "gmailパスワード"
TO_ADDRESS = "mail送信先"
DATE = datetime.datetime.today().strftime("%Y-%m-%d")
NOW_TIME = datetime.datetime.today().strftime("%H:%M")
PATH = "ログディレクトリまでのパス" + DATE
LOG_PATH = PATH + "_send.log"
TIME_LOG_PATH = PATH + "_send_time.log"
ERROR_LOG_PATH = PATH + "_send_error.log"
PARAMS = {
    "user_agent": TO_ADDRESS,
    "workspace_id": "2519279",
    "since": DATE,
    "until": DATE}

def send_mail():
    try:
        total_time = json.loads(requests.get("https://toggl.com/reports/api/v2/summary", auth=(API_KEY, 'api_token'), params=PARAMS).text)["total_grand"]
        total_time = total_time * 1.5 if total_time is not None else 0
        if total_time > 28800000:
            SUBJECT = "帰宅時間になりました。"
            BODY = "あなたはもう8時間働きました、帰りましょう。"
        else:
            SUBJECT = "現在" + str(round(total_time / 3600000, 2)) + "時間働いています。"
            BODY = "残りは" + str(round(8 - total_time / 3600000, 2)) + "時間です。"
        msg = MIMEText(BODY)
        msg['Subject'] = SUBJECT
        msg['From'] = MY_ADDRESS
        msg['To'] = TO_ADDRESS
        msg['Date'] = formatdate()

        smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
        smtpobj.ehlo()
        smtpobj.starttls()
        smtpobj.ehlo()
        smtpobj.login(MY_ADDRESS, MY_PASSWORD)
        smtpobj.sendmail(MY_ADDRESS, TO_ADDRESS, msg.as_string())
        smtpobj.close()
    except:
        with open(ERROR_LOG_PATH, 'a') as f_w:
            f_w.write("Unexpected error:\n" + str(sys.exc_info()))
if not os.path.exists(LOG_PATH):
    with open(LOG_PATH, 'w') as f_w:
        f_w.write("log,start")
    with open(TIME_LOG_PATH, 'w') as f_w:
        f_w.write("log start!!!")
with open(LOG_PATH, 'r') as f_r:
    file_data = f_r.read().split(',')

if NOW_TIME >= "12:00" and NOW_TIME < "14:00" and "noon" not in file_data:
    with open(LOG_PATH, 'a') as f_w:
        f_w.write(",noon")
    with open(TIME_LOG_PATH, 'a') as f_w:
        f_w.write("\nnoon " + datetime.datetime.today().strftime("%H-%M"))
        send_mail()
elif NOW_TIME >= "14:00" and NOW_TIME < "16:00" and "afternoon" not in file_data:
    with open(LOG_PATH, 'a') as f_w:
        f_w.write(",afternoon")
    with open(TIME_LOG_PATH, 'a') as f_w:
        f_w.write("\nafternoon " + datetime.datetime.today().strftime("%H-%M"))
        send_mail()
elif NOW_TIME >= "16:00" and NOW_TIME < "18:00" and "evening" not in file_data:
    with open(LOG_PATH, 'a') as f_w:
        f_w.write(",evening")
    with open(TIME_LOG_PATH, 'a') as f_w:
        f_w.write("\nevening " + datetime.datetime.today().strftime("%H-%M"))
        send_mail()
elif NOW_TIME >= "18:30" and "ordinary" not in file_data:
    with open(LOG_PATH, 'a') as f_w:
        f_w.write(",ordinary")
    with open(TIME_LOG_PATH, 'a') as f_w:
        f_w.write("\nordinary " + datetime.datetime.today().strftime("%H-%M"))
        send_mail()

解説

TO_ADDRESS, MY_ADDRESS, MY_PASSWORD...

続きはこちらへ移転しました!

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4