LoginSignup
0
0

Pythonに自分のサボりを監視させる

Last updated at Posted at 2024-05-14

■背景

最近電子工作に興味を持ち、「キーボードの振動がn秒停止したらヤクザ(の音声)に罵倒される」という装置をArduino、振動センサ等で作った。
電子工作は初めてであり、とにかくArduinoと仲良くなりたいという目的の方が大きかったので、実装自体は有意義だった。しかし、実運用においては、物理的・視覚的に邪魔なので、Pythonに代役をさせることにした。

■目的

自分を在宅勤務でもさぼらせずに追い込んで働かせるシステムをPythonで実装する

■実装

①準備

pip install keyboard plyer

import threading
import keyboard
import time
from plyer import notification

②本編

キーボードからの入力が15秒停止するとポップアップ通知が表示される仕組み。
「マウスを操作して何かを読んでいるがキーボードは使っていない」時も容赦なく怒られる。
アラートを鳴らした回数も容赦なくカウントされる。

class InputMonitor:
    def __init__(self, timeout=15):
        self.timeout = timeout
        self.last_input_time = time.time()
        self.running = True
        self.alert_thread = threading.Thread(target=self.alert_if_no_input)
        self.alert_thread.start()
        keyboard.hook(self.update_last_input_time)

    def update_last_input_time(self, event):
        self.last_input_time = time.time()

    def alert_if_no_input(self):
        while self.running:
            if time.time() - self.last_input_time >= self.timeout:
                self.show_notification()
                self.last_input_time = time.time()  # アラート後、再度待機開始
            time.sleep(1)

    def show_notification(self):
        notification.notify(
            title='さぼりアラート',
            message='PIPされてェのか?働け お前の役割を全うしろ',
            timeout=10
        )

   def stop(self):
       self.running = False
       self.alert_thread.join()
       print(f"アラートは合計 {self.alert_count} 回作動しました。")  # 作動回数を表示


if __name__ == "__main__":
    monitor = InputMonitor(timeout=15)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        monitor.stop()

■さいごに

若干マゾみがあるが、「アラートが鳴る間隔をどれだけ伸ばせるかのゲーム」と解釈することで、緊張感はありつつ仕事を楽しくできる。

実際に作動することは確認済みですので、自由に転用・活用頂いて構いません。

最後までお読みいただき、ありがとうございました。

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