LoginSignup
1
0

SlackとExcelを用いた簡易出勤管理表

Last updated at Posted at 2023-12-09

はじめに

SlackとExcelを利用して簡単な出勤管理表を作りました。
Slackに出勤と退勤と入力するだけでエクセル上に出勤・退勤時間を表示させることができます。

環境

M1 MacBook
python3
SlackAPI

プログラム

import os
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from datetime import datetime
import openpyxl

load_dotenv()
slack_app_token = os.environ['SLACK_APP_TOKEN']
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))

excel_file_path = '<使用するエクセルのファイルパス>'
earnings_per_hour = 1000  

def record_attendance(action, timestamp):
    workbook = openpyxl.load_workbook(excel_file_path)
    sheet = workbook.active
    row = 2
    while sheet.cell(row, 1).value is not None:
        row += 1

    if action == "punch_in":
        sheet.cell(row, 1, timestamp.strftime('%Y-%m-%d')) 
        sheet.cell(row, 2, timestamp.strftime('%H:%M'))  
    elif action == "punch_out":
        sheet.cell(row - 1, 3, timestamp.strftime('%H:%M')) 
        punch_in_time = sheet.cell(row - 1, 2).value
        punch_out_time = sheet.cell(row - 1, 3).value
        if punch_in_time and punch_out_time:
            punch_in_datetime = datetime.strptime(punch_in_time, '%H:%M')
            punch_out_datetime = datetime.strptime(punch_out_time, '%H:%M')
            work_duration = punch_out_datetime - punch_in_datetime
            sheet.cell(row - 1, 4, str(work_duration))
            work_hours = work_duration.total_seconds() / 3600
            estimated_earnings = work_hours * earnings_per_hour
            sheet.cell(row - 1, 5, round(estimated_earnings, 2))

    workbook.save(excel_file_path)

@app.message("出勤")
def message_punch_in(message, say):
    timestamp = datetime.now()
    say(f"出勤しました。あなたの出勤時間は {timestamp.strftime('%H:%M')} です。")

    record_attendance("punch_in", timestamp)

@app.message("退勤")
def message_punch_out(message, say):
    timestamp = datetime.now()
    say(f"退勤しました。あなたの退勤時間は {timestamp.strftime('%H:%M')} です。")

    record_attendance("punch_out", timestamp)

if __name__ == "__main__":
    SocketModeHandler(app, slack_app_token).start()

注意:ファイルパスのコピー方法はFinder→optionキーを押ししながら使用するExcelを右クリック→「"<ファイル名>"のパス名をコピー」を左クリックする

まとめ

このプログラムによって日時、出勤時間、退勤時間、労働時間、推定給料などを表示させることができました。ぜひ何かの参考にしていただけると幸いです。

1
0
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
1
0