-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
61 lines (49 loc) · 1.78 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import os
import re
import time
import requests
from watchdog.events import FileSystemEventHandler
from watchdog.observers.polling import PollingObserver
from config.app import TARGET_DIR, TARGET_FILE, WEBHOOK_URL
from utils.log_message_parser import message_creation
class MinecraftLogMonitor:
def __init__(self, target_dir, target_file, webhook_url):
self.target_dir = target_dir
self.target_file = target_file
self.webhook_url = webhook_url
self.log_position = 0
def send_message(self, message: str) -> None:
main_content = {"content": message}
response = requests.post(self.webhook_url, json=main_content)
response.raise_for_status()
def get_log(self, filepath: str):
with open(filepath, "r", errors="ignore") as f:
f.seek(self.log_position)
logs = f.readlines()
self.log_position = f.tell()
for log in logs:
text = message_creation(log)
if text:
self.send_message(text)
class ChangeHandler(FileSystemEventHandler):
def __init__(self, monitor: MinecraftLogMonitor):
self.monitor = monitor
def on_modified(self, event):
filepath = event.src_path
if (
os.path.isfile(filepath)
and os.path.basename(filepath) == self.monitor.target_file
):
self.monitor.get_log(filepath)
if __name__ == "__main__":
monitor = MinecraftLogMonitor(TARGET_DIR, TARGET_FILE, WEBHOOK_URL)
event_handler = ChangeHandler(monitor)
observer = PollingObserver()
observer.schedule(event_handler, monitor.target_dir, recursive=True)
observer.start()
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
observer.stop()
observer.join()