Quinn Favo
Quinn Favo

Reputation: 86

Azure ChatBot Running With Python on an Azure WebApp Not Working

I am trying to run this: https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/python/02.echo-bot

This runs perfectly fine locally

I changed the default port to 8000 and set the necessary variables in the WebApp: enter image description here

I also added the app registration ID/Password into the WebApp variables and config.py file.

This allows the app to (seemingly) run fine on the webapp, however the chatbot cannot connect and gets the below errors:

enter image description here

Going to the site https://quinntest.azurewebsites.net/ gives a 500

enter image description here

enter image description here

Here is the webapp config:

enter image description here

enter image description here

Has anyone experienced this or have any suggestions?

Upvotes: 0

Views: 807

Answers (1)

Pravallika KV
Pravallika KV

Reputation: 8694

Follow below steps to connect and test Azure Bot:

app.py:

I have added init_func() in the app.py code.

import sys
import traceback
from datetime import datetime

from aiohttp import web
from aiohttp.web import Request, Response, json_response
from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings,
                             TurnContext)
from botbuilder.core.integration import aiohttp_error_middleware
from botbuilder.schema import Activity, ActivityTypes

from bot import MyBot
from config import DefaultConfig

CONFIG = DefaultConfig()

SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
ADAPTER = BotFrameworkAdapter(SETTINGS)


async def on_error(context: TurnContext, error: Exception):

    print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
    traceback.print_exc()

    await context.send_activity("The bot encountered an error or bug.")
    await context.send_activity(
        "To continue to run this bot, please fix the bot source code."
    )

    if context.activity.channel_id == "emulator":

        trace_activity = Activity(
            label="TurnError",
            name="on_turn_error Trace",
            timestamp=datetime.utcnow(),
            type=ActivityTypes.trace,
            value=f"{error}",
            value_type="https://www.botframework.com/schemas/error",
        )
        
        await context.send_activity(trace_activity)

ADAPTER.on_turn_error = on_error

BOT = MyBot()

async def messages(req: Request) -> Response:

    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
    if response:
        return json_response(data=response.body, status=response.status)
    return Response(status=201)

# Modifying the below code

def init_func(argv):
    APP = web.Application(middlewares=[aiohttp_error_middleware])
    APP.router.add_post("/api/messages", messages)
    return APP
if __name__ == "__main__":
    APP = init_func(None)

    try:
        web.run_app(APP, host="0.0.0.0", port=CONFIG.PORT)
    except Exception as error:
        raise error
  • Navigate to Config.py code in your Echo Bot project and paste App_ID_ and App_Password which were copied from Azure Bot.
import os
class DefaultConfig:
    """ Bot Configuration """

    PORT = 3978
    APP_ID = os.environ.get("MicrosoftAppId", "<Your_App_ID>")
    APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "<Your_App-Password>")

requirements.txt:

botbuilder-integration-aiohttp>=4.14.0
aiohttp
botbuilder-core
botbuilder-schema
  • Deploy the application to Azure App Service.
  • Open your Azure Bot, add the Azure App Service's URL by adding /api/messages(https://<webapp>.azurewebsites.net/api/messages) in the Settings=>Configuration=>Messaging Endpoint.

enter image description here

  • Navigate to Azure App Service=>Configuration=>General Settings=>Startup Command, use the command python3 -m aiohttp.web -H 0.0.0.0 -P 8000 app:init_func to run the application.

enter image description here

  • Go to Azure Bot=>Test in Web chat to test the connection:

https://i.imgur.com/2Yymb0y.png

Upvotes: 1

Related Questions