Skip to content

Added 03.welcome-user sample #365

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

Merged
merged 8 commits into from
Oct 29, 2019
Merged
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
36 changes: 36 additions & 0 deletions samples/03.welcome-user/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# welcome users


Bot Framework v4 welcome users bot sample

This bot has been created using [Bot Framework](https://dev.botframework.com), is shows how to welcome users when they join the conversation.

## Running the sample
- Clone the repository
```bash
git clone https://github.com/Microsoft/botbuilder-python.git
```
- Activate your desired virtual environment
- Bring up a terminal, navigate to `botbuilder-python\samples\03.welcome-user` folder
- In the terminal, type `pip install -r requirements.txt`
- In the terminal, type `python app.py`

## Testing the bot using Bot Framework Emulator
[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.

- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)

### Connect to bot using Bot Framework Emulator
- Launch Bot Framework Emulator
- Paste this URL in the emulator window - http://localhost:3978/api/messages


## Welcoming Users

The primary goal when creating any bot is to engage your user in a meaningful conversation. One of the best ways to achieve this goal is to ensure that from the moment a user first connects, they understand your bot’s main purpose and capabilities, the reason your bot was created. See [Send welcome message to users](https://aka.ms/botframework-welcome-instructions) for additional information on how a bot can welcome users to a conversation.

## Further reading

- [Bot Framework Documentation](https://docs.botframework.com)
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
93 changes: 93 additions & 0 deletions samples/03.welcome-user/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import asyncio
import sys
from datetime import datetime
from types import MethodType

from flask import Flask, request, Response
from botbuilder.core import (
BotFrameworkAdapter,
BotFrameworkAdapterSettings,
MemoryStorage,
TurnContext,
UserState,
)
from botbuilder.schema import Activity, ActivityTypes

from bots import WelcomeUserBot

# Create the loop and Flask app
LOOP = asyncio.get_event_loop()
APP = Flask(__name__, instance_relative_config=True)
APP.config.from_object("config.DefaultConfig")

# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
ADAPTER = BotFrameworkAdapter(SETTINGS)


# Catch-all for errors.
async def on_error(self, context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)

# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity("To continue to run this bot, please fix the bot source code.")
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == 'emulator':
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error"
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)

ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)

# Create MemoryStorage, UserState
MEMORY = MemoryStorage()
USER_STATE = UserState(MEMORY)

# Create the Bot
BOT = WelcomeUserBot(USER_STATE)

# Listen for incoming requests on /api/messages.
@APP.route("/api/messages", methods=["POST"])
def messages():
# Main bot message handler.
if "application/json" in request.headers["Content-Type"]:
body = request.json
else:
return Response(status=415)

activity = Activity().deserialize(body)
auth_header = (
request.headers["Authorization"] if "Authorization" in request.headers else ""
)

try:
task = LOOP.create_task(
ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
)
LOOP.run_until_complete(task)
return Response(status=201)
except Exception as exception:
raise exception


if __name__ == "__main__":
try:
APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
except Exception as exception:
raise exception
6 changes: 6 additions & 0 deletions samples/03.welcome-user/bots/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from .welcome_user_bot import WelcomeUserBot

__all__ = ["WelcomeUserBot"]
133 changes: 133 additions & 0 deletions samples/03.welcome-user/bots/welcome_user_bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from botbuilder.core import ActivityHandler, TurnContext, UserState, CardFactory, MessageFactory
from botbuilder.schema import ChannelAccount, HeroCard, CardImage, CardAction, ActionTypes

from data_models import WelcomeUserState


class WelcomeUserBot(ActivityHandler):
def __init__(self, user_state: UserState):
if user_state is None:
raise TypeError(
"[WelcomeUserBot]: Missing parameter. user_state is required but None was given"
)

self.user_state = user_state

self.user_state_accessor = self.user_state.create_property("WelcomeUserState")

self.WELCOME_MESSAGE = """This is a simple Welcome Bot sample. This bot will introduce you
to welcoming and greeting users. You can say 'intro' to see the
introduction card. If you are running this bot in the Bot Framework
Emulator, press the 'Restart Conversation' button to simulate user joining
a bot or a channel"""

async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)

# save changes to WelcomeUserState after each turn
await self.user_state.save_changes(turn_context)

"""
Greet when users are added to the conversation.
Note that all channels do not send the conversation update activity.
If you find that this bot works in the emulator, but does not in
another channel the reason is most likely that the channel does not
send this activity.
"""

async def on_members_added_activity(
self, members_added: [ChannelAccount], turn_context: TurnContext
):
for member in members_added:
if member.id != turn_context.activity.recipient.id:
await turn_context.send_activity(
f"Hi there { member.name }. " + self.WELCOME_MESSAGE
)

await turn_context.send_activity("""You are seeing this message because the bot received at least one
'ConversationUpdate' event, indicating you (and possibly others)
joined the conversation. If you are using the emulator, pressing
the 'Start Over' button to trigger this event again. The specifics
of the 'ConversationUpdate' event depends on the channel. You can
read more information at: https://aka.ms/about-botframework-welcome-user"""
)

await turn_context.send_activity("""It is a good pattern to use this event to send general greeting
to user, explaining what your bot can do. In this example, the bot
handles 'hello', 'hi', 'help' and 'intro'. Try it now, type 'hi'"""
)

"""
Respond to messages sent from the user.
"""

async def on_message_activity(self, turn_context: TurnContext):
# Get the state properties from the turn context.
welcome_user_state = await self.user_state_accessor.get(turn_context, WelcomeUserState)

if not welcome_user_state.did_welcome_user:
welcome_user_state.did_welcome_user = True

await turn_context.send_activity(
"You are seeing this message because this was your first message ever to this bot."
)

name = turn_context.activity.from_property.name
await turn_context.send_activity(
f"It is a good practice to welcome the user and provide personal greeting. For example: Welcome { name }"
)

else:
# This example hardcodes specific utterances. You should use LUIS or QnA for more advance language
# understanding.
text = turn_context.activity.text.lower()
if text in ("hello", "hi"):
await turn_context.send_activity(
f"You said { text }"
)
elif text in ("intro", "help"):
await self.__send_intro_card(turn_context)
else:
await turn_context.send_activity(self.WELCOME_MESSAGE)

async def __send_intro_card(self, turn_context: TurnContext):
card = HeroCard(
title="Welcome to Bot Framework!",
text="Welcome to Welcome Users bot sample! This Introduction card "
"is a great way to introduce your Bot to the user and suggest "
"some things to get them started. We use this opportunity to "
"recommend a few next steps for learning more creating and deploying bots.",
images=[
CardImage(
url="https://aka.ms/bf-welcome-card-image"
)
],
buttons=[
CardAction(
type=ActionTypes.open_url,
title="Get an overview",
text="Get an overview",
display_text="Get an overview",
value="https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"
),
CardAction(
type=ActionTypes.open_url,
title="Ask a question",
text="Ask a question",
display_text="Ask a question",
value="https://stackoverflow.com/questions/tagged/botframework"
),
CardAction(
type=ActionTypes.open_url,
title="Learn how to deploy",
text="Learn how to deploy",
display_text="Learn how to deploy",
value="https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
)
]
)

return await turn_context.send_activity(MessageFactory.attachment(CardFactory.hero_card(card)))
15 changes: 15 additions & 0 deletions samples/03.welcome-user/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import os

""" Bot Configuration """


class DefaultConfig:
""" Bot Configuration """

PORT = 3978
APP_ID = os.environ.get("MicrosoftAppId", "")
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
6 changes: 6 additions & 0 deletions samples/03.welcome-user/data_models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from .welcome_user_state import WelcomeUserState

__all__ = ["WelcomeUserState"]
7 changes: 7 additions & 0 deletions samples/03.welcome-user/data_models/welcome_user_state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.


class WelcomeUserState:
def __init__(self, did_welcome: bool = False):
self.did_welcome_user = did_welcome
2 changes: 2 additions & 0 deletions samples/03.welcome-user/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
botbuilder-core>=4.4.0b1
flask>=1.0.3