diff --git a/chatmastermind/chat.py b/chatmastermind/chat.py new file mode 100644 index 0000000..41d33bc --- /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 we use path.iterdir(). Messages are created using + 'Message.from_file()' with 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)