Skip to content

Commit

Permalink
Merge pull request #45 from iKonoTelecomunicaciones/44-improve-chatbo…
Browse files Browse the repository at this point in the history
…t-flow-load

refactor(flow): ♻️ Improved chatbot flow load
  • Loading branch information
egalvis39 committed Nov 14, 2023
2 parents d7b2c32 + 5ce58f3 commit 24a19c0
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 19 deletions.
6 changes: 2 additions & 4 deletions menuflow/flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,8 @@ class Flow:
nodes: Dict[str, Dict]
middlewares: Dict[str, Dict]

def __init__(self, flow_data: FlowModel, flow_utils: Optional[FlowUtils] = None) -> None:
self.data: FlowModel = (
flow_data.serialize() if isinstance(flow_data, SerializableAttrs) else flow_data
)
def __init__(self, flow_mxid: str, flow_utils: Optional[FlowUtils] = None) -> None:
self.data = FlowModel.load_flow(flow_mxid=flow_mxid)
self.nodes = self.data.get("nodes", [])
self.middlewares = self.data.get("middlewares", [])
self.nodes_by_id: Dict[str, Dict] = {}
Expand Down
16 changes: 1 addition & 15 deletions menuflow/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,8 @@ def __init__(
super().__init__(*args, **kwargs)
self.config = config
self.flow_utils = flow_utils
path = f"/data/flows/{self.mxid}.yaml"
flow = Config(path=path, base_path="")
try:
flow.load()
except FileNotFoundError as e:
self.log.warning(e)
with open(path, "a") as yaml_file:
yaml.dump(Util.flow_example(), yaml_file)

self.log.warning(
f"Please configure your {self.mxid}.yaml file and restart the service"
)
flow.load()

self.util = Util(self.config)
self.flow = Flow(flow_data=FlowModel.deserialize(flow["menu"]), flow_utils=self.flow_utils)
self.flow = Flow(flow_utils=flow_utils, flow_mxid=self.mxid)
Base.init_cls(
config=self.config,
session=self.api.session,
Expand Down
26 changes: 26 additions & 0 deletions menuflow/repository/flow.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,42 @@
from __future__ import annotations

import logging
from pathlib import Path
from typing import Any, Dict, List

import yaml
from attr import dataclass, ib
from mautrix.types import SerializableAttrs
from mautrix.util.logging import TraceLogger

from ..utils import Util
from .middlewares import HTTPMiddleware
from .nodes import CheckTime, HTTPRequest, Input, Message, Switch

log: TraceLogger = logging.getLogger("menuflow.repository.flow")


@dataclass
class Flow(SerializableAttrs):
nodes: List[Message, Input, HTTPRequest, Switch, CheckTime] = ib(factory=list)
middlewares: List[HTTPMiddleware] = ib(default=[])
flow_variables: Dict[str, Any] = ib(default={})

@classmethod
def load_flow(cls, flow_mxid: str) -> Flow:
path = Path("/data/flows") / f"{flow_mxid}.yaml"
if not path.exists():
log.warning(f"File {flow_mxid}.yaml not found")
path.write_text(yaml.dump(Util.flow_example()))
log.warning(
f"Example flow {flow_mxid}.yaml file was generated. "
"Configure it and restart the service."
)

try:
flow: Dict = yaml.safe_load(path.read_text())
except Exception as e:
log.exception(f"Error loading flow {flow_mxid}.yaml: {e}")
raise

return cls(**flow["menu"])

0 comments on commit 24a19c0

Please sign in to comment.