11# Copyright (c) Microsoft Corporation. All rights reserved.
22# Licensed under the MIT License.
33
4- import asyncio
54import sys
65from datetime import datetime
76
8- from flask import Flask , request , Response
7+ from aiohttp import web
8+ from aiohttp .web import Request , Response
99from botbuilder .core import BotFrameworkAdapterSettings , TurnContext , BotFrameworkAdapter
1010from botbuilder .schema import Activity , ActivityTypes
1111
1212from bots import EchoBot
13+ from config import DefaultConfig
1314
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" )
15+ CONFIG = DefaultConfig ()
1816
1917# Create adapter.
2018# 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" ] )
19+ SETTINGS = BotFrameworkAdapterSettings (CONFIG . APP_ID , CONFIG . APP_PASSWORD )
2220ADAPTER = BotFrameworkAdapter (SETTINGS )
2321
2422
@@ -52,31 +50,41 @@ async def on_error(context: TurnContext, error: Exception):
5250BOT = EchoBot ()
5351
5452# Listen for incoming requests on /api/messages
55- @app .route ("/api/messages" , methods = ["POST" ])
56- def messages ():
53+ async def messages (req : Request ) -> Response :
5754 # Main bot message handler.
58- if "application/json" in request .headers ["Content-Type" ]:
59- body = request .json
55+ if "application/json" in req .headers ["Content-Type" ]:
56+ body = await req .json ()
6057 else :
6158 return Response (status = 415 )
6259
6360 activity = Activity ().deserialize (body )
6461 auth_header = (
65- request .headers ["Authorization" ] if "Authorization" in request .headers else ""
62+ req .headers ["Authorization" ] if "Authorization" in req .headers else ""
6663 )
6764
6865 try :
69- task = LOOP .create_task (
70- ADAPTER .process_activity (activity , auth_header , BOT .on_turn )
71- )
72- LOOP .run_until_complete (task )
66+ await ADAPTER .process_activity (activity , auth_header , BOT .on_turn )
7367 return Response (status = 201 )
7468 except Exception as exception :
7569 raise exception
7670
71+ def app ():
72+ APP = web .Application ()
73+ APP .router .add_post ("/api/messages" , messages )
74+ return APP
75+
76+ #this is the code needed for the deployment template startup command
77+ def init_func (argv ):
78+ try :
79+ APP = app ()
80+ except Exception as error :
81+ raise error
82+
83+ return APP
7784
85+ #this part is needed if you start your bot with 'py app.py' instead of the deployed command.
7886if __name__ == "__main__" :
7987 try :
80- app . run ( debug = False , port = app . config [ " PORT" ]) # nosec debug
81- except Exception as exception :
82- raise exception
88+ web . run_app ( app (), host = "localhost" , port = CONFIG . PORT )
89+ except Exception as error :
90+ raise error
0 commit comments