8000 Standardized app.py and on_error messages in original samples. (#376) · rusty0209/botbuilder-python@5bc70b2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5bc70b2

Browse files
tracyboehreraxelsrz
authored andcommitted
Standardized app.py and on_error messages in original samples. (microsoft#376)
1 parent 793f8e2 commit 5bc70b2

File tree

10 files changed

+239
-168
lines changed
  • 45.state-management
  • 10 files changed

    +239
    -168
    lines changed

    samples/06.using-cards/app.py

    Lines changed: 33 additions & 18 deletions
    Original file line numberDiff line numberDiff line change
    @@ -6,6 +6,8 @@
    66
    """
    77
    import asyncio
    88
    import sys
    9+
    from datetime import datetime
    10+
    from types import MethodType
    911

    1012
    from flask import Flask, request, Response
    1113
    from botbuilder.core import (
    @@ -16,49 +18,65 @@
    1618
    TurnContext,
    1719
    UserState,
    1820
    )
    19-
    from botbuilder.schema import Activity
    21+
    from botbuilder.schema import Activity, ActivityTypes
    2022

    2123
    from dialogs import MainDialog
    2224
    from bots import RichCardsBot
    2325

    26+
    # Create the loop and Flask app
    2427
    LOOP = asyncio.get_event_loop()
    2528
    APP = Flask(__name__, instance_relative_config=True)
    2629
    APP.config.from_object("config.DefaultConfig")
    2730

    28-
    SETTINGS = BotFrameworkAdapterSettings(
    29-
    APP.config["APP_ID"], APP.config["APP_PASSWORD"]
    30-
    )
    31+
    # Create adapter.
    32+
    # See https://aka.ms/about-bot-adapter to learn more about how bots work.
    33+
    SETTINGS = BotFrameworkAdapterSettings(APP.config["APP_ID"], APP.config["APP_PASSWORD"])
    3134
    ADAPTER = BotFrameworkAdapter(SETTINGS)
    3235

    36+
    3337
    # Catch-all for errors.
    34-
    async def on_error(context: TurnContext, error: Exception):
    35-
    # This check writes out errors to console log
    38+
    async def on_error(self, context: TurnContext, error: Exception):
    39+
    # This check writes out errors to console log .vs. app insights.
    3640
    # NOTE: In production environment, you should consider logging this to Azure
    3741
    # application insights.
    38-
    print(f"\n [on_turn_error]: { error }", file=sys.stderr)
    42+
    print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
    43+
    3944
    # Send a message to the user
    40-
    await context.send_activity("Oops. Something went wrong!")
    45+
    await context.send_activity("The bot encountered an error or bug.")
    46+
    await context.send_activity("To continue to run this bot, please fix the bot source code.")
    47+
    # Send a trace activity if we're talking to the Bot Framework Emulator
    48+
    if context.activity.channel_id == 'emulator':
    49+
    # Create a trace activity that contains the error object
    50+
    trace_activity = Activity(
    51+
    label="TurnError",
    52+
    name="on_turn_error Trace",
    53+
    timestamp=datetime.utcnow(),
    54+
    type=ActivityTypes.trace,
    55+
    value=f"{error}",
    56+
    value_type="https://www.botframework.com/schemas/error"
    57+
    )
    58+
    # Send a trace activity, which will be displayed in Bot Framework Emulator
    59+
    await context.send_activity(trace_activity)
    60+
    4161
    # Clear out state
    4262
    await CONVERSATION_STATE.delete(context)
    4363

    44-
    45-
    ADAPTER.on_turn_error = on_error
    64+
    ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)
    4665

    4766
    # Create MemoryStorage, UserState and ConversationState
    4867
    MEMORY = MemoryStorage()
    49-
    50-
    # Commented out user_state because it's not being used.
    5168
    USER_STATE = UserState(MEMORY)
    5269
    CONVERSATION_STATE = ConversationState(MEMORY)
    5370

    54-
    71+
    # Create dialog and Bot
    5572
    DIALOG = MainDialog()
    5673
    BOT = RichCardsBot(CONVERSATION_STATE, USER_STATE, DIALOG)
    5774

    5875

    76+
    # Listen for incoming requests on /api/messages.
    5977
    @APP.route("/api/messages", methods=["POST"])
    6078
    def messages():
    61-
    """Main bot message handler."""
    79+
    # Main bot message handler.s
    6280
    if "application/json" in request.headers["Content-Type"]:
    6381
    body = request.json
    6482
    else:
    @@ -69,12 +87,9 @@ def messages():
    6987
    request.headers["Authorization"] if "Authorization" in request.headers else ""
    7088
    )
    7189

    72-
    async def aux_func(turn_context):
    73-
    await BOT.on_turn(turn_context)
    74-
    7590
    try:
    7691
    task = LOOP.create_task(
    77-
    ADAPTER.process_activity(activity, auth_header, aux_func)
    92+
    ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
    7893
    )
    7994
    LOOP.run_until_complete(task)
    8095
    return Response(status=201)

    samples/06.using-cards/config.py

    Lines changed: 0 additions & 4 deletions
    Original file line numberDiff line numberDiff line change
    @@ -13,7 +13,3 @@ class DefaultConfig:
    1313
    PORT = 3978
    1414
    APP_ID = os.environ.get("MicrosoftAppId", "")
    1515
    APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
    16-
    LUIS_APP_ID = os.environ.get("LuisAppId", "")
    17-
    LUIS_API_KEY = os.environ.get("LuisAPIKey", "")
    18-
    # LUIS endpoint host name, ie "westus.api.cognitive.microsoft.com"
    19-
    LUIS_API_HOST_NAME = os.environ.get("LuisAPIHostName", "")
    Lines changed: 2 additions & 1 deletion
    Original file line numberDiff line numberDiff line change
    @@ -1,2 +1,3 @@
    11
    botbuilder-core>=4.4.0b1
    2-
    botbuilder-dialogs>=4.4.0b1
    2+
    botbuilder-dialogs>=4.4.0b1
    3+
    flask>=1.0.3

    samples/13.core-bot/adapter_with_error_handler.py

    Lines changed: 20 additions & 8 deletions
    Original file line numberDiff line numberDiff line change
    @@ -1,14 +1,15 @@
    11
    # Copyright (c) Microsoft Corporation. All rights reserved.
    22
    # Licensed under the MIT License.
    33
    import sys
    4+
    from datetime import datetime
    5+
    46
    from botbuilder.core import (
    57
    BotFrameworkAdapter,
    68
    BotFrameworkAdapterSettings,
    79
    ConversationState,
    8-
    MessageFactory,
    910
    TurnContext,
    1011
    )
    11-
    from botbuilder.schema import InputHints
    12+
    from botbuilder.schema import InputHints, ActivityTypes, Activity
    1213

    1314

    1415
    class AdapterWithErrorHandler(BotFrameworkAdapter):
    @@ -25,14 +26,25 @@ async def on_error(context: TurnContext, error: Exception):
    2526
    # This check writes out errors to console log
    2627
    # NOTE: In production environment, you should consider logging this to Azure
    2728
    # application insights.
    28-
    print(f"\n [on_turn_error]: {error}", file=sys.stderr)
    29+
    print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
    2930

    3031
    # Send a message to the user
    31-
    error_message_text = "Sorry, it looks like something went wrong."
    32-
    error_message = MessageFactory.text(
    33-
    error_message_text, error_message_text, InputHints.expecting_input
    34-
    )
    35-
    await context.send_activity(error_message)
    32+
    await context.send_activity("The bot encountered an error or bug.")
    33+
    await context.send_activity("To continue to run this bot, please fix the bot source code.")
    34+
    # Send a trace activity if we're talking to the Bot Framework Emulator
    35+
    if context.activity.channel_id == 'emulator':
    36+
    # Create a trace activity that contains the error object
    37+
    trace_activity = Activity(
    38+
    label="TurnError",
    39+
    name="on_turn_error Trace",
    40+
    timestamp=datetime.utcnow(),
    41+
    type=ActivityTypes.trace,
    42+
    value=f"{error}",
    43+
    value_type="https://www.botframework.com/schemas/error"
    44+
    )
    45+
    # Send a trace activity, which will be displayed in Bot Framework Emulator
    46+
    await context.send_activity(trace_activity)
    47+
    3648
    # Clear out state
    3749
    nonlocal self
    3850
    await self._conversation_state.delete(context)

    samples/13.core-bot/app.py

    Lines changed: 9 additions & 6 deletions
    Original file line numberDiff line numberDiff line change
    @@ -25,6 +25,7 @@
    2525
    from adapter_with_error_handler import AdapterWithErrorHandler
    2626
    from flight_booking_recognizer import FlightBookingRecognizer
    2727

    28+
    # Create the loop and Flask app
    2829
    LOOP = asyncio.get_event_loop()
    2930
    APP = Flask(__name__, instance_relative_config=True)
    3031
    APP.config.from_object("config.DefaultConfig")
    @@ -35,17 +36,22 @@
    3536
    MEMORY = MemoryStorage()
    3637
    USER_STATE = UserState(MEMORY)
    3738
    CONVERSATION_STATE = ConversationState(MEMORY)
    39+
    40+
    # Create adapter.
    41+
    # See https://aka.ms/about-bot-adapter to learn more about how bots work.
    3842
    ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE)
    43+
    44+
    # Create dialogs and Bot
    3945
    RECOGNIZER = FlightBookingRecognizer(APP.config)
    4046
    BOOKING_DIALOG = BookingDialog()
    41-
    4247
    DIALOG = MainDialog(RECOGNIZER, BOOKING_DIALOG)
    4348
    BOT = DialogAndWelcomeBot(CONVERSATION_STATE, USER_STATE, DIALOG)
    4449

    4550

    51+
    # Listen for incoming requests on /api/messages.
    4652
    @APP.route("/api/messages", methods=["POST"])
    4753
    def messages():
    48-
    """Main bot message handler."""
    54+
    # Main bot message handler.
    4955
    if "application/json" in request.headers["Content-Type"]:
    5056
    body = request.json
    5157
    else:
    @@ -56,12 +62,9 @@ def messages():
    5662
    request.headers["Authorization"] if "Authorization" in request.headers else ""
    5763
    )
    5864

    59-
    async def aux_func(turn_context):
    60-
    await BOT.on_turn(turn_context)
    61-
    6265
    try:
    6366
    task = LOOP.create_task(
    64-
    ADAPTER.process_activity(activity, auth_header, aux_func)
    67+
    ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
    6568
    )
    6669
    LOOP.run_until_complete(task)
    6770
    return Response(status=201)

    samples/21.corebot-app-insights/README.md

    Lines changed: 18 additions & 10 deletions
    Original file line numberDiff line numberDiff line change
    @@ -1,4 +1,4 @@
    1-
    # CoreBot
    1+
    # CoreBot with Application Insights
    22

    33
    Bot Framework v4 core bot sample.
    44

    @@ -12,21 +12,29 @@ This bot has been created using [Bot Framework](https://dev.botframework.com), i
    1212

    1313
    ## Prerequisites
    1414

    15-
    This sample **requires** prerequisites in order to run.
    15+
    ### Install Python 3.6
    1616

    1717
    ### Overview
    1818

    19-
    This bot uses [LUIS](https://www.luis.ai), an AI based cognitive service, to implement language understanding.
    20-
    21-
    ### Install Python 3.6
    22-
    19+
    This bot uses [LUIS](https://www.luis.ai), an AI based cognitive service, to implement language understanding
    20+
    and [Application Insights](https://docs.microsoft.com/azure/azure-monitor/app/cloudservices), an extensible Application Performance Management (APM) service for web developers on multiple platforms.
    2321

    2422
    ### Create a LUIS Application to enable language understanding
    2523

    2624
    LUIS language model setup, training, and application configuration steps can be found [here](https://docs.microsoft.com/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=cs).
    2725

    2826
    If you wish to create a LUIS application via the CLI, these steps can be found in the [README-LUIS.md](README-LUIS.md).
    2927

    28+
    ### Add Application Insights service to enable the bot monitoring
    29+
    Application Insights resource creation steps can be found [here](https://docs.microsoft.com/azure/azure-monitor/app/create-new-resource).
    30+
    31+
    ## Running the sample
    32+
    - Run `pip install -r requirements.txt` to install all dependencies
    33+
    - Update LuisAppId, LuisAPIKey and LuisAPIHostName in `config.py` with the information retrieved from the [LUIS portal](https://www.luis.ai)
    34+
    - Update AppInsightsInstrumentationKey in `config.py`
    35+
    - Run `python app.py`
    36+
    - Alternatively to the last command, you can set the file in an environment variable with `set FLASK_APP=app.py` in windows (`export FLASK_APP=app.py` in mac/linux) and then run `flask run --host=127.0.0.1 --port=3978`
    37+
    3038

    3139
    ## Testing the bot using Bot Framework Emulator
    3240

    @@ -50,8 +58,8 @@ If you wish to create a LUIS application via the CLI, these steps can be found i
    5058
    - [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
    5159
    - [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
    5260
    - [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
    53-
    - [.NET Core CLI tools](https://docs.microsoft.com/dotnet/core/tools/?tabs=netcore2x)
    54-
    - [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
    55-
    - [Azure Portal](https://portal.azure.com)
    5661
    - [Language Understanding using LUIS](https://docs.microsoft.com/azure/cognitive-services/luis/)
    57-
    - [Channels and Bot Connector Service](https://docs.microsoft.com/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
    62+
    - [Channels and Bot Connector Service](https://docs.microsoft.com/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
    63+
    - [Application insights Overview](https://docs.microsoft.com/azure/azure-monitor/app/app-insights-overview)
    64+
    - [Getting Started with Application Insights](https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Getting-Started-with-Application-Insights-for-ASP.NET-Core)
    65+
    - [Filtering and preprocessing telemetry in the Application Insights SDK](https://docs.microsoft.com/azure/azure-monitor/app/api-filtering-sampling)

    0 commit comments

    Comments
     (0)
    0