Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/conversation dialogs #1

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ repos:
- id: debug-statements
language_version: python3

- repo: https://github.com/PyCQA/autoflake
rev: v2.2.1
hooks:
- id: autoflake
args: [--remove-all-unused-imports, --in-place, --ignore-init-module-imports]

- repo: https://github.com/asottile/reorder_python_imports
rev: v2.6.0
hooks:
Expand Down
8 changes: 6 additions & 2 deletions botgen/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from .bot_worker import BotWorker
from .conversation import BotConversation
from .conversation import BotConversationStep
from .conversation_state import BotConvoState
from .core import Bot
from .core import BotMessage
from .core import BotWorker
from .dialog_wrapper import BotDialogWrapper

__version__ = "0.0.1"
__version__ = "0.0.2"
18 changes: 8 additions & 10 deletions botgen/adapters/web_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,21 @@
from botbuilder.core import BotAdapter
from botbuilder.core import TurnContext
from botbuilder.schema import Activity
from botbuilder.schema import ActivityTypes
from botbuilder.schema import ConversationReference
from botbuilder.schema import ResourceResponse
from loguru import logger

from botgen.core import BotMessage
import botgen


class WebAdapter(BotAdapter):
""" Connects PyBot to websocket or webhook """
"""Connects PyBot to websocket or webhook"""

def __init__(self, on_turn_error: Callable[[TurnContext, Exception], Awaitable] = None):
super().__init__(on_turn_error)

def activity_to_message(self, activity: Activity) -> BotMessage:
""" Caste a message to the simple format used by the websocket client """
message = BotMessage(
def activity_to_message(self, activity: Activity) -> botgen.BotMessage:
"""Caste a message to the simple format used by the websocket client"""
message = botgen.BotMessage(
type=activity.type,
text=activity.text,
)
Expand All @@ -36,7 +34,7 @@ def activity_to_message(self, activity: Activity) -> BotMessage:
async def send_activities(
self, context: TurnContext, activities: list[Activity]
) -> ResourceResponse:
""" Standard BotBuilder adapter method to send a message from the bot to the messaging API """
"""Standard BotBuilder adapter method to send a message from the bot to the messaging API"""

responses = list()

Expand All @@ -63,12 +61,12 @@ async def update_activity(self, context: TurnContext, activity: Activity) -> Non
raise NotImplementedError()

async def delete_activity(self, context: TurnContext, reference: ConversationReference) -> None:
""" Accept an incoming webhook request and convert it into a TurnContext which can be processed by the bot's logic """
"""Accept an incoming webhook request and convert it into a TurnContext which can be processed by the bot's logic"""
raise NotImplementedError()

async def process_activity(self, request: Request, logic: callable):
body = await request.json()
message = BotMessage(**body)
message = botgen.BotMessage(**body)

activity = Activity(
timestamp=datetime.now(),
Expand Down
42 changes: 37 additions & 5 deletions botgen/bot_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@ def __init__(self, controller: botgen.Bot, config: dict) -> None:
self._config = config

def get_controller(self):
""" Get a reference to the main Bot controller """
"""Get a reference to the main Bot controller"""
return self._controller

def get_config(self):
""" Get a value from the BotWorker's configuration """
def get_config(self, key: str = None):
"""Get a value from the BotWorker's configuration"""
if key:
return self._config[key]

return self._config

async def say(self, message: botgen.BotMessage | Activity | str):
""" Send a message using whatever context the `bot` was spawned """
"""Send a message using whatever context the `bot` was spawned"""
activity = await self.ensure_message_format(message=message)

return await self._config["context"].send_activity(activity)
Expand All @@ -45,11 +48,40 @@ async def reply(self, message_src: botgen.BotMessage, message_resp: str):
return await self.say(activity)

async def ensure_message_format(self, message: botgen.BotMessage | str) -> Activity:
"""
"""
Take a crudely-formed Bot message with any sort of field (may just be a string, may be a partial message object)
and map it into a beautiful BotFramework Activity
"""
if isinstance(message, str):
return Activity(type="message", text=message, channel_data={})

return Activity(**message.__dict__)

async def begin_dialog(self, id: str, options: dict = {}) -> None:
"""
Begin a pre-defined dialog by specifying its ID. The dialog will be started in the same context
(same user, same channel) in which the original incoming message was received.

Args:
id (str): The ID of the dialog.
options (Any, optional): An object containing options to be passed into the dialog. Defaults to None.

Returns:
None
"""

if not "dialog_context" in self._config:
raise Exception(
"Call to begin_dialog on a bot that did not receive a dialog_context during spawn"
)

await self._config["dialog_context"].begin_dialog(
f"{id}:botgen-wrapper",
{
"user": self._config["context"].activity.id,
"channel": self._config["context"].activity.conversation["id"],
**options,
},
)

await self._controller.save_state(self)
Loading
Loading