|
1 | 1 | # Copyright (c) Microsoft Corporation. All rights reserved.
|
2 | 2 | # Licensed under the MIT License.
|
3 | 3 |
|
4 |
| -import asyncio |
| 4 | +import os |
5 | 5 | import sys
|
6 | 6 | from datetime import datetime
|
7 | 7 |
|
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 |
9 | 12 | from botbuilder.core import BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter
|
10 | 13 | from botbuilder.schema import Activity, ActivityTypes
|
11 | 14 |
|
| 15 | + |
12 | 16 | from bots import EchoBot
|
13 | 17 |
|
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
8000
span>}", 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 |
67 | 27 |
|
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 "" |
71 | 39 | )
|
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() |
76 | 92 |
|
77 | 93 |
|
78 | 94 | 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() |
0 commit comments