Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Twitterを開くとデーモンがPCを再起動するスクリプト。python3.6.5, PySimpleGUI4.37.0
import PySimpleGUI as sg
from PIL import Image
import time
import os
import win32com.client
class TwitterTimeCounter:
def __init__(self):
self.time = 0
def tick(self):
"""1秒ごとに呼び出す関数
Twitterを開いている場合は時刻を進める
"""
is_running = self.is_twitter_running()
if is_running:
self.time += 1
def reset_time(self):
self.time = 0
def _get_all_windows(self) -> list:
"""現在開いているプログラム名をすべて返す。
virtual desktop であっても取得できる。
"""
import ctypes
EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool,
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible
titles = []
def foreach_window(hwnd, lParam):
if IsWindowVisible(hwnd):
length = GetWindowTextLength(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
GetWindowText(hwnd, buff, length + 1)
titles.append(buff.value)
return True
EnumWindows(EnumWindowsProc(foreach_window), 0)
titles = set(titles)
# print("起動中プログラム一覧を取得しました")
# print(*titles, sep="\n")
return list(titles)
def is_twitter_running(self) -> bool:
title_list = self._get_all_windows()
# 'twitter'を含むプログラムを検索
deny_list = ["twitter", "Twitter"]
for title in title_list:
for ng_word in deny_list:
if ng_word in title:
return True
return False
def say(text: str):
sapi = win32com.client.Dispatch("SAPI.SpVoice")
cat = win32com.client.Dispatch("SAPI.SpObjectTokenCategory")
cat.SetID(
r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices", False)
v = [t for t in cat.EnumerateTokens() if t.GetAttribute("Name")
== "Microsoft Sayaka"]
if v:
oldv = sapi.Voice
sapi.Voice = v[0]
sapi.Speak(text)
sapi.Voice = oldv
def reboot():
os.system("shutdown /r /t 0")
POPUP_FONT = 'Helvetica 16' # font to use in popup
POPUP_TEXT_COLOR, POPUP_BACKGROUND_COLOR = 'white', 'black'
SNS_TIME_LIMIT = 5 # 30 minutes [second]
def main():
menu_def = ['UNUSED', ['Exit']]
daemon_image = "daemon.png"
tray_image = "dog-100.png"
tray = sg.SystemTray(menu=menu_def, filename=tray_image)
starting_seconds = time.time()
ttc = TwitterTimeCounter()
isLoggingIn = False # 見ているときは True
while True:
event = tray.read(1)
if event == 'Exit':
break
if ttc.time > SNS_TIME_LIMIT:
sg.popup("Twitterやってる場合ちゃうぞ!",
background_color=POPUP_BACKGROUND_COLOR,
text_color=POPUP_TEXT_COLOR,
font=POPUP_FONT,
no_titlebar=True,
image=daemon_image,
keep_on_top=True
)
say("ばーか、ばーか、あばよ。")
reboot()
break
delta_from_last = time.time() - starting_seconds
isLoggingIn = ttc.is_twitter_running()
# 1 秒ごとに Twitter を開いているか確認し状態を変更
if delta_from_last >= 1:
if not isLoggingIn:
continue
ttc.tick()
starting_seconds = time.time()
tray.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment