|
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +import asyncio |
| 5 | +import sys |
| 6 | +import uuid |
| 7 | +from datetime import datetime |
| 8 | +from types import MethodType |
| 9 | +from typing import Dict |
| 10 | + |
| 11 | +from flask import Flask, request, Response |
| 12 | +from botbuilder.core import BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter |
| 13 | +from botbuilder.schema import Activity, ActivityTypes, ConversationReference |
| 14 | + |
| 15 | +from bots import ProactiveBot |
| 16 | + |
| 17 | +# Create the loop and Flask app |
| 18 | +LOOP = asyncio.get_event_loop() |
| 19 | +APP = Flask(__name__, instance_relative_config=True) |
| 20 | +APP.config.from_object("config.DefaultConfig") |
| 21 | + |
| 22 | +# Create adapter. |
| 23 | +# See https://aka.ms/about-bot-adapter to learn more about how bots work. |
| 24 | +SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"]) |
| 25 | +ADAPTER = BotFrameworkAdapter(SETTINGS) |
| 26 | + |
| 27 | + |
| 28 | +# Catch-all for errors. |
| 29 | +async def on_error(self, context: TurnContext, error: Exception): |
| 30 | + # This check writes out errors to console log .vs. app insights. |
| 31 | + # NOTE: In production environment, you should consider logging this to Azure |
| 32 | + # application insights. |
| 33 | + print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) |
| 34 | + |
| 35 | + # Send a message to the user |
| 36 | + await context.send_activity("The bot encountered an error or bug.") |
| 37 | + await context.send_activity("To continue to run this bot, please fix the bot source code.") |
| 38 | + # Send a trace activity if we're talking to the Bot Framework Emulator |
| 39 | + if context.activity.channel_id == 'emulator': |
| 40 | + # Create a trace activity that contains the error object |
| 41 | + trace_activity = Activity( |
| 42 | + label="TurnError", |
| 43 | + name="on_turn_error Trace", |
| 44 | + timestamp=datetime.utcnow(), |
| 45 | + type=ActivityTypes.trace, |
| 46 | + value=f"{error}", |
| 47 | + value_type="https://www.botframework.com/schemas/error" |
| 48 | + ) |
| 49 | + # Send a trace activity, which will be displayed in Bot Framework Emulator |
| 50 | + await context.send_activity(trace_activity) |
| 51 | + |
| 52 | +ADAPTER.on_turn_error = MethodType(on_error, ADAPTER) |
| 53 | + |
| 54 | +# Create a shared dictionary. The Bot will add conversation references when users |
| 55 | +# join the conversation and send messages. |
| 56 | +CONVERSATION_REFERENCES: Dict[str, ConversationReference] = dict() |
| 57 | + |
| 58 | +# If the channel is the Emulator, and authentication is not in use, the AppId will be null. |
| 59 | +# We generate a random AppId for this case only. This is not required for production, since |
| 60 | +# the AppId will have a value. |
| 61 | +APP_ID = SETTINGS.app_id if SETTINGS.app_id else uuid.uuid4() |
| 62 | + |
| 63 | +# Create the Bot |
| 64 | +BOT = ProactiveBot(CONVERSATION_REFERENCES) |
| 65 | + |
| 66 | +# Listen for incoming requests on /api/messages. |
| 67 | +@APP.route("/api/messages", methods=["POST"]) |
| 68 | +def messages(): |
| 69 | + # Main bot message handler. |
| 70 | + if "application/json" in request.headers["Content-Type"]: |
| 71 | + body = request.json |
| 72 | + else: |
| 73 | + return Response(status=415) |
| 74 | + |
| 75 | + activity = Activity().deserialize(body) |
| 76 | + auth_header = ( |
| 77 | + request.headers["Authorization"] if "Authorization" in request.headers else "" |
| 78 | + ) |
| 79 | + |
| 80 | + try: |
| 81 | + task = LOOP.create_task( |
| 82 | + ADAPTER.process_activity(activity, auth_header, BOT.on_turn) |
| 83 | + ) |
| 84 | + LOOP.run_until_complete(task) |
| 85 | + return Response(status=201) |
| 86 | + except Exception as exception: |
| 87 | + raise exception |
| 88 | + |
| 89 | + |
| 90 | +# Listen for requests on /api/notify, and send a messages to all conversation members. |
| 91 | +@APP.route("/api/notify") |
| 92 | +def notify(): |
| 93 | + try: |
| 94 | + task = LOOP.create_task( |
| 95 | + _send_proactive_message() |
| 96 | + ) |
| 97 | + LOOP.run_until_complete(task) |
| 98 | + |
| 99 | + return Response(status=201, response="Proactive messages have been sent") |
| 100 | + except Exception as exception: |
| 101 | + raise exception |
| 102 | + |
| 103 | + |
| 104 | +# Send a message to all conversation members. |
| 105 | +# This uses the shared Dictionary that the Bot adds conversation references to. |
| 106 | +async def _send_proactive_message(): |
| 107 | + for conversation_reference in CONVERSATION_REFERENCES.values(): |
| 108 | + return await ADAPTER.continue_conversation( |
| 109 | + APP_ID, |
| 110 | + conversation_reference, |
| 111 | + lambda turn_context: turn_context.send_activity("proactive hello") |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +if __name__ == "__main__": |
| 116 | + try: |
| 117 | + APP.run(debug=False, port=APP.config["PORT"]) # nosec debug |
| 118 | + except Exception as exception: |
| 119 | + raise exception |
0 commit comments