8000 echo with tornado · snifhex/botbuilder-python@6449ad8 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6449ad8

Browse files
committed
echo with tornado
1 parent 73ff35a commit 6449ad8

File tree

2 files changed

+79
-81
lines changed

2 files changed

+79
-81
lines changed

samples/02.echo-bot/app.py

Lines changed: 79 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,95 @@
11
# Copyright (c) Microsoft Corporation. All rights reserved.
22
# Licensed under the MIT License.
33

4-
import asyncio
4+
import os
55
import sys
66
from datetime import datetime
77

8-
from flask import Flask, request, Response
8+
import tornado.ioloop
9+
import tornado.web
10+
import tornado.escape
11+
from tornado.options import define, parse_command_line, options
912
from botbuilder.core import BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter
1013
from botbuilder.schema import Activity, ActivityTypes
1114

15+
1216
from bots import EchoBot
1317

14-
# Create the loop and Flask app
15-
LOOP = asyncio.get_event_loop()
16-
app = Flask(__name__, instance_relative_config=True)
17-
app.config.from_object("config.DefaultConfig")
18-
19-
# Create adapter.
20-
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
21-
SETTINGS = BotFrameworkAdapterSettings(app.config["APP_ID"], app.config["APP_PASSWORD"])
22-
ADAPTER = BotFrameworkAdapter(SETTINGS)
23-
24-
25-
# Catch-all for errors.
26-
async def on_error(context: TurnContext, error: Exception):
27-
# This check writes out errors to console log .vs. app insights.
28-
# NOTE: In production environment, you should consider logging this to Azure
29-
# application insights.
30-
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
31-
32-
# Send a message to the user
33-
await context.send_activity("The bot encountered an error or bug.")
34-
await context.send_activity("To continue to run this bot, please fix the bot source code.")
35-
# Send a trace activity if we're talking to the Bot Framework Emulator
36-
if context.activity.channel_id == 'emulator':
37-
# Create a trace activity that contains the error object
38-
trace_activity = Activity(
39-
label="TurnError",
40-
name="on_turn_error Trace",
41-
timestamp=datetime.utcnow(),
42-
type=ActivityTypes.trace,
43-
value=f"{error}",
44-
value_type="https://www.botframework.com/schemas/error"
45-
)
46-
# Send a trace activity, which will be displayed in Bot Framework Emulator
47-
await context.send_activity(trace_activity)
48-
49-
ADAPTER.on_turn_error = on_error
50-
51-
# Create the Bot
52-
BOT = EchoBot()
53-
54-
# Listen for incoming requests on /api/messages
55-
@app.route("/api/messages", methods=["POST"])
56-
def messages():
57-
# Main bot message handler.
58-
if "application/json" in request.headers["Content-Type"]:
59-
body = request.json
60-
else:
61-
return Response(status=415)
62-
63-
activity = Activity().deserialize(body)
64-
auth_header = (
65-
request.headers["Authorization"] if "Authorization" in request.headers else ""
66-
)
18+
define("port", default=3978, help="Application port")
19+
define("app_id", default=os.environ.get("MicrosoftAppId", ""), help="Application id from Azure")
20+
define("app_password", default=os.environ.get("MicrosoftAppPassword", ""), help="Application password from Azure")
21+
define("debug", default=True, help="run in debug mode")
22+
23+
class MessageHandler(tornado.web.RequestHandler):
24+
def initialize(self, adapter: BotFrameworkAdapter, bot: EchoBot):
25+
self.adapter = adapter
26+
self.bot = bot
6727

68-
try:
69-
task = LOOP.create_task(
70-
ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
28+
async def post(self):
29+
# Main bot message handler.
30+
if "application/json" in self.request.headers["Content-Type"]:
31+
body = tornado.escape.json_decode(self.request.body)
32+
else:
33+
self.set_status(415)
34+
return
35+
36+
activity = Activity().from_dict(body)
37+
auth_header = (
38+
self.request.headers["Authorization"] if "Authorization" in self.request.headers else ""
7139
)
72-
LOOP.run_until_complete(task)
73-
return Response(status=201)
74-
except Exception as exception:
75-
raise exception
40+
41+
try:
42+
await self.adapter.process_activity(activity, auth_header, self.bot.on_turn)
43+
self.set_status(201)
44+
return
45+
except Exception as exception:
46+
raise exception
47+
48+
49+
def main():
50+
parse_command_line()
51+
52+
# Create adapter.
53+
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
54+
settings = BotFrameworkAdapterSettings(options.app_id, options.app_password)
55+
adapter = BotFrameworkAdapter(settings)
56+
57+
# Catch-all for errors.
58+
async d 9E88 ef on_error(context: TurnContext, error: Exception):
59+
# This check writes out errors to console log .vs. app insights.
60+
# NOTE: In production environment, you should consider logging this to Azure
61+
# application insights.
62+
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
63+
64+
# Send a message to the user
65+
await context.send_activity("The bot encountered an error or bug.")
66+
await context.send_activity("To continue to run this bot, please fix the bot source code.")
67+
# Send a trace activity if we're talking to the Bot Framework Emulator
68+
if context.activity.channel_id == 'emulator':
69+
# Create a trace activity that contains the error object
70+
trace_activity = Activity(
71+
label="TurnError",
72+
name="on_turn_error Trace",
73+
timestamp=datetime.utcnow(),
74+
type=ActivityTypes.trace,
75+
value=f"{error}",
76+
value_type="https://www.botframework.com/schemas/error"
77+
)
78+
# Send a trace activity, which will be displayed in Bot Framework Emulator
79+
await context.send_activity(trace_activity)
80+
81+
adapter.on_turn_error = on_error
82+
bot = EchoBot()
83+
84+
app = tornado.web.Application(
85+
[
86+
(r"/api/messages", MessageHandler, dict(adapter=adapter, bot=bot)),
87+
],
88+
debug=options.debug,
89+
)
90+
app.listen(options.port)
91+
tornado.ioloop.IOLoop.current().start()
7692

7793

7894
if __name__ == "__main__":
79-
try:
80-
app.run(debug=False, port=app.config["PORT"]) # nosec debug
81-
except Exception as exception:
82-
raise exception
95+
main()

samples/02.echo-bot/config.py

Lines changed: 0 additions & 15 deletions
This file was deleted.

0 commit comments

Comments
 (0)
0