|
| 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 botbuilder.core.inspection import InspectionMiddleware, InspectionState |
| 10 | +from botframework.connector.auth import MicrosoftAppCredentials |
| 11 | +from flask import Flask, request, Response |
| 12 | +from botbuilder.core import ( |
| 13 | + BotFrameworkAdapter, |
| 14 | + BotFrameworkAdapterSettings, |
| 15 | + ConversationState, |
| 16 | + MemoryStorage, |
| 17 | + TurnContext, |
| 18 | + UserState, |
| 19 | +) |
| 20 | +from botbuilder.schema import Activity, ActivityTypes |
| 21 | + |
| 22 | +from bots import EchoBot |
| 23 | + |
| 24 | +# Create the loop and Flask app |
| 25 | +LOOP = asyncio.get_event_loop() |
| 26 | +APP = Flask(__name__, instance_relative_config=True) |
| 27 | +APP.config.from_object("config.DefaultConfig") |
| 28 | + |
| 29 | +# Create adapter. |
| 30 | +# See https://aka.ms/about-bot-adapter to learn more about how bots work. |
| 31 | +SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"]) |
| 32 | +ADAPTER = BotFrameworkAdapter(SETTINGS) |
| 33 | + |
| 34 | + |
| 35 | +# Catch-all for errors. |
| 36 | +async def on_error(context: TurnContext, error: Exception): |
| 37 | + # This check writes out errors to console log .vs. app insights. |
| 38 | + # NOTE: In production environment, you should consider logging this to Azure |
| 39 | + # application insights. |
| 40 | + print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) |
| 41 | + |
| 42 | + # Send a message to the user |
| 43 | + await context.send_activity("The bot encountered an error or bug.") |
| 44 | + await context.send_activity("To continue to run this bot, please fix the bot source code.") |
| 45 | + # Send a trace activity if we're talking to the Bot Framework Emulator |
| 46 | + if context.activity.channel_id == 'emulator': |
| 47 | + # Create a trace activity that contains the error object |
| 48 | + trace_activity = Activity( |
| 49 | + label="TurnError", |
| 50 | + name="on_turn_error Trace", |
| 51 | + timestamp=datetime.utcnow(), |
| 52 | + type=ActivityTypes.trace, |
| 53 | + value=f"{error}", |
| 54 | + value_type="https://www.botframework.com/schemas/error" |
| 55 | + ) |
| 56 | + # Send a trace activity, which will be displayed in Bot Framework Emulator |
| 57 | + await context.send_activity(trace_activity) |
| 58 | + |
| 59 | + # Clear out state |
| 60 | + await CONVERSATION_STATE.delete(context) |
| 61 | + |
| 62 | +# Set the error handler on the Adapter. |
| 63 | +# In this case, we want an unbound method, so MethodType is not needed. |
| 64 | +ADAPTER.on_turn_error = on_error |
| 65 | + |
| 66 | +# Create MemoryStorage and state |
| 67 | +MEMORY = MemoryStorage() |
| 68 | +USER_STATE = UserState(MEMORY) |
| 69 | +CONVERSATION_STATE = ConversationState(MEMORY) |
| 70 | + |
| 71 | +# Create InspectionMiddleware |
| 72 | +INSPECTION_MIDDLEWARE = InspectionMiddleware( |
| 73 | + inspection_state=InspectionState(MEMORY), |
| 74 | + user_state=USER_STATE, |
| 75 | + conversation_state=CONVERSATION_STATE, |
| 76 | + credentials=MicrosoftAppCredentials( |
| 77 | + app_id=APP.config["APP_ID"], |
| 78 | + password=APP.config["APP_PASSWORD"] |
| 79 | + ) |
| 80 | +) |
| 81 | +ADAPTER.use(INSPECTION_MIDDLEWARE) |
| 82 | + |
| 83 | +# Create Bot |
| 84 | +BOT = EchoBot(CONVERSATION_STATE, USER_STATE) |
| 85 | + |
| 86 | + |
| 87 | +# Listen for incoming requests on /api/messages. |
| 88 | +@APP.route("/api/messages", methods=["POST"]) |
| 89 | +def messages(): |
| 90 | + # Main bot message handler. |
| 91 | + if "application/json" in request.headers["Content-Type"]: |
| 92 | + body = request.json |
| 93 | + else: |
| 94 | + return Response(status=415) |
| 95 | + |
| 96 | + activity = Activity().deserialize(body) |
| 97 | + auth_header = ( |
| 98 | + request.headers["Authorization"] if "Authorization" in request.headers else "" |
| 99 | + ) |
| 100 | + |
| 101 | + try: |
| 102 | + task = LOOP.create_task( |
| 103 | + ADAPTER.process_activity(activity, auth_header, BOT.on_turn) |
| 104 | + ) |
| 105 | + LOOP.run_until_complete(task) |
| 106 | + return Response(status=201) |
| 107 | + except Exception as exception: |
| 108 | + raise exception |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + try: |
| 113 | + APP.run(debug=False, port=APP.config["PORT"]) # nosec debug |
| 114 | + except Exception as exception: |
| 115 | + raise exception |
0 commit comments