Skip to content

Commit

Permalink
Merge pull request #22 from chatbot-smooth/bug-with-diferents-bot-cli…
Browse files Browse the repository at this point in the history
…ents

Bug with different bot clients
  • Loading branch information
bramenn committed Apr 3, 2023
2 parents 9a14068 + 8579b12 commit 29eb9f2
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 34 deletions.
15 changes: 14 additions & 1 deletion flows/@example:example.com.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,12 @@ menu:
flow_variables:
cat_fatc_url: 'https://catfact.ninja/fact'
nodes:

- id: start
type: message
text: 'Hello, this a flow sample. {{foo}}'
o_connection: input-1

- id: input-1
type: input
text: 'Do you have 1 or more cats?, please enter (y/n)'
Expand All @@ -130,6 +132,7 @@ menu:
no_cats: 'You are a user without cats, without life, without happiness ...'
- id: timeout
o_connection: last-message

- id: input-2
type: input
text: 'Enter your cat''s name:'
Expand All @@ -138,6 +141,7 @@ menu:
cases:
- id: default
o_connection: input-3

- id: input-3
type: input
text: 'Enter your cat''s age in months:'
Expand All @@ -150,6 +154,7 @@ menu:
o_connection: switch-1
- id: default
o_connection: input-3

- id: switch-1
type: switch
validation: >-
Expand All @@ -164,38 +169,44 @@ menu:
o_connection: request-1
variables:
cat_message: Your cat is an adult

- id: request-1
type: http_request
method: GET
url: '{{cat_fatc_url}}'
variables:
cat_fact: fact
cases:
- id: '200'
- id: 200
o_connection: message-2
- id: default
o_connection: error-message-1

- id: message-2
type: message
text: >-
{{cat_message}}, also let me give you an interesting fact about cats.
Did you know that cats: **{{ cat_fact }}**
o_connection: message-3

- id: message-3
type: message
text: I'm going to share with you a picture of a kitten
o_connection: media-1

- id: media-1
type: media
message_type: m.image
text: A cat
url: 'https://cataas.com/cat'
o_connection: location-1

- id: location-1
type: location
latitude: 132.4877572355567
longitude: 33.73677405847739
o_connection: input-4

- id: input-4
type: input
text: 'Now you enter the image of your cat:'
Expand All @@ -206,9 +217,11 @@ menu:
o_connection: last-message
- id: false
o_connection: input-3

- id: last-message
type: message
text: 'Bye bye! ... {{no_cats}}'

- id: error-message-1
type: message
text: 'Something has gone wrong, bye'
6 changes: 4 additions & 2 deletions menuflow/flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@
class Flow:
log: TraceLogger = logging.getLogger("menuflow.flow")

nodes: Dict[str, (Message, Input, Switch, HTTPRequest, CheckTime)] = {}
middlewares: Dict[str, HTTPMiddleware] = {}
nodes: Dict[str, (Message, Input, Switch, HTTPRequest, CheckTime)]
middlewares: Dict[str, HTTPMiddleware]

def __init__(self, flow_data: FlowModel) -> None:
self.data: FlowModel = (
flow_data.serialize() if isinstance(flow_data, SerializableAttrs) else flow_data
)
self.nodes = {}
self.middlewares = {}

@property
def flow_variables(self) -> Dict:
Expand Down
10 changes: 7 additions & 3 deletions menuflow/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import asyncio
from copy import deepcopy
from typing import Any, Dict, Optional
from typing import Dict, Optional

import yaml
from mautrix.client import Client as MatrixClient
Expand All @@ -20,7 +20,7 @@
from .config import Config
from .db.room import RoomState
from .flow import Flow
from .nodes import Base, CheckTime, Email, HTTPRequest, Input, Media, Message, Switch
from .nodes import Base, Input
from .repository import Flow as FlowModel
from .room import Room
from .user import User
Expand Down Expand Up @@ -51,7 +51,9 @@ def __init__(self, config: Config, *args, **kwargs) -> None:
self.util = Util(self.config)
self.flow = Flow(flow_data=FlowModel.deserialize(flow["menu"]))
Base.init_cls(
config=self.config, matrix_client=self, default_variables=self.flow.flow_variables
config=self.config,
session=self.api.session,
default_variables=self.flow.flow_variables,
)
self.flow.load()

Expand Down Expand Up @@ -121,6 +123,7 @@ async def handle_join(self, evt: StrippedStateEvent):
try:
room = await Room.get_by_room_id(room_id=evt.room_id)
room.config = self.config
room.matrix_client = self
if not await room.get_variable("bot_mxid"):
await room.set_variable("bot_mxid", self.mxid)
await room.set_variable("customer_room_id", evt.room_id)
Expand Down Expand Up @@ -164,6 +167,7 @@ async def handle_message(self, message: MessageEvent) -> None:
user: User = await User.get_by_mxid(mxid=message.sender)
room = await Room.get_by_room_id(room_id=message.room_id)
room.config = user.config = self.config
room.matrix_client = self

if not await room.get_variable("customer_phone") and user.phone:
await room.set_variable("customer_phone", user.phone)
Expand Down
47 changes: 37 additions & 10 deletions menuflow/nodes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from json import JSONDecodeError, dumps, loads
from logging import getLogger
from random import randrange
from typing import Dict, List
from typing import Any, Dict, List

from aiohttp import ClientSession
from mautrix.client import Client as MatrixClient
Expand Down Expand Up @@ -35,6 +35,29 @@ def convert_to_bool(item) -> Dict | List | str:
return item


def convert_to_int(item: Any) -> Dict | List | int:
if isinstance(item, dict):
for k, v in item.items():
item[k] = convert_to_int(v)
return item
elif isinstance(item, list):
return [convert_to_int(i) for i in item]
elif isinstance(item, str) and item.isdigit():
return int(item)
else:
return item


def safe_data_convertion(item: Any, _bool: bool = True, _int: bool = True) -> Any:
if _bool:
item = convert_to_bool(item)

if _int:
item = convert_to_int(item)

return item


class Base:
log: TraceLogger = getLogger("menuflow.node")

Expand All @@ -54,10 +77,9 @@ def type(self) -> str:
return self.data.get("type", "")

@classmethod
def init_cls(cls, config: Config, matrix_client: MatrixClient, default_variables: Dict):
def init_cls(cls, config: Config, session: ClientSession, default_variables: Dict):
cls.config = config
cls.matrix_client = matrix_client
cls.session = matrix_client.api.session
cls.session = session
cls.variables = default_variables or {}

@abstractmethod
Expand All @@ -76,7 +98,7 @@ async def set_typing(self, room_id: RoomID):
start = self.config["menuflow.typing_notification.start"] or 1
end = self.config["menuflow.typing_notification.end"] or 3
typing_time = randrange(start, end)
await self.matrix_client.set_typing(room_id=room_id, timeout=typing_time)
await self.room.matrix_client.set_typing(room_id=room_id, timeout=typing_time)
await sleep(typing_time)

async def send_message(self, room_id: RoomID, content: MessageEventContent):
Expand All @@ -91,13 +113,18 @@ async def send_message(self, room_id: RoomID, content: MessageEventContent):
"""

async def send():
if self.config["menuflow.typing_notification.enable"]:
await self.set_typing(room_id=room_id)
# async def send():
# if self.config["menuflow.typing_notification.enable"]:
# await self.set_typing(room_id=room_id)

# await self.room.matrix_client.send_message(room_id=room_id, content=content)

if self.config["menuflow.typing_notification.enable"]:
await self.set_typing(room_id=room_id)

await self.matrix_client.send_message(room_id=room_id, content=content)
await self.room.matrix_client.send_message(room_id=room_id, content=content)

create_task(send())
# create_task(send())

def render_data(self, data: Dict | List | str) -> Dict | List | str:
"""It takes a dictionary or list, converts it to a string,
Expand Down
4 changes: 2 additions & 2 deletions menuflow/nodes/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,10 @@ async def timeout_active_chats(self):
self.log.debug(f"INACTIVITY TRIES COMPLETED -> {self.room.room_id}")
o_connection = await self.get_case_by_id("timeout")
await self.room.update_menu(node_id=o_connection, state=None)
await self.matrix_client.algorithm(room=self.room)
await self.room.matrix_client.algorithm(room=self.room)
break

await self.matrix_client.send_text(
await self.room.matrix_client.send_text(
room_id=self.room.room_id, text=self.warning_message
)
await asyncio.sleep(self.time_between_attempts)
Expand Down
2 changes: 1 addition & 1 deletion menuflow/nodes/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ async def load_media(self) -> MediaMessageEventContent:
file_name = f"{self.message_type.value[2:]}{extension}" if self.message_type else None

try:
mxc = await self.matrix_client.upload_media(
mxc = await self.room.matrix_client.upload_media(
data=data, mime_type=media_info.mimetype, filename=file_name
)
except MUnknown as e:
Expand Down
19 changes: 9 additions & 10 deletions menuflow/nodes/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,14 @@ async def run(self):

if not self.text:
self.log.warning(f"The message {self.id} hasn't been send because the text is empty")
return

msg_content = TextMessageEventContent(
msgtype=self.message_type,
body=self.text,
format=Format.HTML,
formatted_body=markdown(self.text),
)

await self.send_message(room_id=self.room.room_id, content=msg_content)
else:
msg_content = TextMessageEventContent(
msgtype=self.message_type,
body=self.text,
format=Format.HTML,
formatted_body=markdown(self.text),
)

await self.send_message(room_id=self.room.room_id, content=msg_content)

await self._update_node()
10 changes: 5 additions & 5 deletions menuflow/nodes/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Dict, List

from ..repository import Switch as SwitchModel
from .base import Base, convert_to_bool
from .base import Base, safe_data_convertion


class Switch(Base):
Expand Down Expand Up @@ -36,7 +36,7 @@ async def load_cases(self) -> Dict[str, str]:
cases_dict = {}

for case in self.cases:
cases_dict[convert_to_bool(case.get("id"))] = {
cases_dict[safe_data_convertion(case.get("id"))] = {
"o_connection": case.get("o_connection"),
"variables": case.get("variables"),
}
Expand Down Expand Up @@ -68,11 +68,11 @@ async def run(self) -> str:
await self.room.update_menu(await self._run())

async def get_case_by_id(self, id: str | int) -> str:
id = safe_data_convertion(id)

try:
cases = await self.load_cases()
case_result: Dict = (
cases[int(id)] if isinstance(id, str) and id.isdigit() else cases[id]
)
case_result: Dict = cases[id]

variables_recorded = []
if case_result.get("variables") and self.room:
Expand Down
3 changes: 3 additions & 0 deletions menuflow/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from logging import getLogger
from typing import Any, Dict, cast

from mautrix.client import Client as MatrixClient
from mautrix.types import RoomID
from mautrix.util.logging import TraceLogger

Expand All @@ -18,6 +19,8 @@ class Room(DBRoom):
config: Config
log: TraceLogger = getLogger("menuflow.room")

matrix_client: MatrixClient

def __init__(
self,
room_id: RoomID,
Expand Down

0 comments on commit 29eb9f2

Please sign in to comment.