Skip to content

Commit 84b3a09

Browse files
tracyboehreraxelsrz
authored andcommitted
Added 02.echo-bot (#369)
* Added 02.echo-bot * Removed LUIS keys from settings. * Added new on_error messages, standardized app.py * Corrected 02.echo-bot README * Removed adapter_with_error_handler.py (migrated to app.py)
1 parent 0987404 commit 84b3a09

File tree

6 files changed

+153
-0
lines changed

6 files changed

+153
-0
lines changed

samples/02.echo-bot/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# EchoBot
2+
3+
Bot Framework v4 echo bot sample.
4+
5+
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
6+
7+
## Running the sample
8+
- Clone the repository
9+
```bash
10+
git clone https://github.com/Microsoft/botbuilder-python.git
11+
```
12+
- Activate your desired virtual environment
13+
- Bring up a terminal, navigate to `botbuilder-python\samples\02.echo-bot` folder
14+
- In the terminal, type `pip install -r requirements.txt`
15+
- In the terminal, type `python app.py`
16+
17+
## Testing the bot using Bot Framework Emulator
18+
[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.
19+
20+
- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
21+
22+
### Connect to bot using Bot Framework Emulator
23+
- Launch Bot Framework Emulator
24+
- Paste this URL in the emulator window - http://localhost:3978/api/messages
25+
26+
## Further reading
27+
28+
- [Bot Framework Documentation](https://docs.botframework.com)
29+
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
30+
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)

samples/02.echo-bot/app.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
import asyncio
5+
import sys
6+
from datetime import datetime
7+
from types import MethodType
8+
9+
from flask import Flask, request, Response
10+
from botbuilder.core import BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter
11+
from botbuilder.schema import Activity, ActivityTypes
12+
13+
from bots import EchoBot
14+
15+
# Create the loop and Flask app
16+
LOOP = asyncio.get_event_loop()
17+
APP = Flask(__name__, instance_relative_config=True)
18+
APP.config.from_object("config.DefaultConfig")
19+
20+
# Create adapter.
21+
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
22+
SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
23+
ADAPTER = BotFrameworkAdapter(SETTINGS)
24+
25+
26+
# Catch-all for errors.
27+
async def on_error(self, context: TurnContext, error: Exception):
28+
# This check writes out errors to console log .vs. app insights.
29+
# NOTE: In production environment, you should consider logging this to Azure
30+
# application insights.
31+
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
32+
33+
# Send a message to the user
34+
await context.send_activity("The bot encountered an error or bug.")
35+
await context.send_activity("To continue to run this bot, please fix the bot source code.")
36+
# Send a trace activity if we're talking to the Bot Framework Emulator
37+
if context.activity.channel_id == 'emulator':
38+
# Create a trace activity that contains the error object
39+
trace_activity = Activity(
40+
label="TurnError",
41+
name="on_turn_error Trace",
42+
timestamp=datetime.utcnow(),
43+
type=ActivityTypes.trace,
44+
value=f"{error}",
45+
value_type="https://www.botframework.com/schemas/error"
46+
)
47+
# Send a trace activity, which will be displayed in Bot Framework Emulator
48+
await context.send_activity(trace_activity)
49+
50+
ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
51+
52+
# Create the Bot
53+
BOT = EchoBot()
54+
55+
# Listen for incoming requests on /api/messages.s
56+
@APP.route("/api/messages", methods=["POST"])
57+
def messages():
58+
# Main bot message handler.
59+
if "application/json" in request.headers["Content-Type"]:
60+
body = request.json
61+
else:
62+
return Response(status=415)
63+
64+
activity = Activity().deserialize(body)
65+
auth_header = (
66+
request.headers["Authorization"] if "Authorization" in request.headers else ""
67+
)
68+
69+
try:
70+
task = LOOP.create_task(
71+
ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
72+
)
73+
LOOP.run_until_complete(task)
74+
return Response(status=201)
75+
except Exception as exception:
76+
raise exception
77+
78+
79+
if __name__ == "__main__":
80+
try:
81+
APP.run(debug=False, port=APP.config["PORT"]) # nosec debug
82+
except Exception as exception:
83+
raise exception

samples/02.echo-bot/bots/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
from .echo_bot import EchoBot
5+
6+
__all__ = ["EchoBot"]

samples/02.echo-bot/bots/echo_bot.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
from botbuilder.core import ActivityHandler, MessageFactory, TurnContext
5+
from botbuilder.schema import ChannelAccount
6+
7+
8+
class EchoBot(ActivityHandler):
9+
async def on_members_added_activity(
10+
self, members_added: [ChannelAccount], turn_context: TurnContext
11+
):
12+
for member in members_added:
13+
if member.id != turn_context.activity.recipient.id:
14+
await turn_context.send_activity("Hello and welcome!")
15+
16+
async def on_message_activity(self, turn_context: TurnContext):
17+
return await turn_context.send_activity(MessageFactory.text(f"Echo: {turn_context.activity.text}"))

samples/02.echo-bot/config.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License.
4+
5+
import os
6+
7+
""" Bot Configuration """
8+
9+
10+
class DefaultConfig:
11+
""" Bot Configuration """
12+
13+
PORT = 3978
14+
APP_ID = os.environ.get("MicrosoftAppId", "")
15+
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")

samples/02.echo-bot/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
botbuilder-core>=4.4.0b1
2+
flask>=1.0.3

0 commit comments

Comments
 (0)