From 806f46b22259067322fae6789be4536bd303ef62 Mon Sep 17 00:00:00 2001 From: juk0de Date: Thu, 24 Aug 2023 16:49:54 +0200 Subject: [PATCH] added new module 'chat.py' --- chatmastermind/chat.py | 44 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 chatmastermind/chat.py diff --git a/chatmastermind/chat.py b/chatmastermind/chat.py new file mode 100644 index 0000000..b08bc7a --- /dev/null +++ b/chatmastermind/chat.py @@ -0,0 +1,44 @@ +""" +Module implementing the 'Chat' class and functions for managing a chat history. +""" +import pathlib +from dataclasses import dataclass +from typing import TypeVar, Type, Optional +from .message import Message, MessageFilter, MessageError + +ChatInst = TypeVar('ChatInst', bound='Chat') + + +class ChatError(Exception): + pass + + +@dataclass +class Chat: + """ + Class containing a complete chat history. + """ + messages: list[Message] + + @classmethod + def from_dir(cls: Type[ChatInst], + path: pathlib.Path, + glob: Optional[str] = None, + mfilter: Optional[MessageFilter] = None) -> ChatInst: + """ + Create a Chat instance from the message in the given directory. + If glob is specified, files will be filtered using path.glob(), + otherwise it uses path.iterdir(). Messages are created using + Message.from_file() and the optional MessageFilter. + """ + messages: list[Message] = [] + file_iter = path.glob(glob) if glob else path.iterdir() + for file_path in file_iter: + if file_path.is_file(): + try: + message = Message.from_file(file_path, mfilter) + if message: + messages.append(message) + except MessageError as e: + print(f"Error processing message in file {file_path}: {str(e)}") + return cls(messages)