build from logs command

This commit is contained in:
Corban-Lee Jones 2024-12-11 17:39:00 +00:00
parent fc752d6a84
commit 6816eb68e8
2 changed files with 30 additions and 7 deletions

View File

@ -8,7 +8,7 @@ from os import getenv
from pathlib import Path
from datetime import datetime
from discord import Colour
from discord import Colour, Interaction, Permissions, app_commands
from discord.ext import commands, tasks
from utils.reader import LogFileReader
@ -32,6 +32,28 @@ class PlayersCog(commands.Cog):
self.file_handler = LogFileReader(USER_LOG_FILE_PATH)
self.listen_for_changes.start()
@app_commands.command(name="build-from-logs")
@app_commands.default_permissions(Permissions.all())
async def build_from_logs(self, inter: Interaction):
"""
Build player data from existing and older log files.
"""
await inter.response.defer()
log.info("Building player data from logs.")
# Delete the existing data, as we will reconstruct it.
await Player.all().delete()
for log_file in LOGS_FOLDER_PATH.glob("**/*.txt"):
log.debug("building from log file: %s", str(log_file))
file_handler = LogFileReader(log_file, track_from_start=True)
for line in await file_handler.read():
await self.process_log_line(line, alert=False)
await inter.followup.send("Completed")
@tasks.loop(seconds=3)
async def listen_for_changes(self):
"""
@ -40,15 +62,15 @@ class PlayersCog(commands.Cog):
for line in await self.file_handler.read():
await self.process_log_line(line)
async def process_log_line(self, line: str):
async def process_log_line(self, line: str, alert: bool = True):
log.debug("processing log line")
if "died" in line:
await self.process_player_death(line)
await self.process_player_death(line, alert)
elif "fully connected" in line:
await self.process_connected_player(line)
await self.process_connected_player(line, alert)
elif "disconnected player" in line:
await self.process_disconnected_player(line)
await self.process_disconnected_player(line, alert)
async def process_player_death(self, line: str, alert: bool = False):
log.debug("processing player death")

View File

@ -13,11 +13,12 @@ log = logging.getLogger(__name__)
class LogFileReader:
"""
"""
def __init__(self, file_path: Path):
def __init__(self, file_path: Path, track_from_start: bool=False):
if not isinstance(file_path, Path):
raise TypeError(f"file_path must be type Path, not {type(file_path)}")
self.file_path = file_path
self.track_from_start = track_from_start
self._last_line_number = 0
log.debug("%s created with path %s", self.__class__.__name__, str(file_path))
@ -27,7 +28,7 @@ class LogFileReader:
raise FileNotFoundError(self.file_path)
async with aiofiles.open(self.file_path, "r", encoding="utf-8") as file:
if self._last_line_number == 0:
if self._last_line_number == 0 and not self.track_from_start:
await file.seek(0, 2)
self._last_line_number = await file.tell()
return []