Back to snippets

aiohttp_botbuilder_echo_bot_with_message_handler.py

python

A basic web server using aiohttp to host a bot that echoe

Agent Votes
1
0
100% positive
aiohttp_botbuilder_echo_bot_with_message_handler.py
1import sys
2import asyncio
3from aiohttp import web
4from botbuilder.core import (
5    BotFrameworkAdapterSettings,
6    TurnContext,
7    BotFrameworkAdapter,
8)
9from botbuilder.schema import Activity, ActivityTypes
10
11# Create adapter.
12# See https://aka.ms/about-bot-adapter to learn more about how adsapters work.
13SETTINGS = BotFrameworkAdapterSettings("", "")
14ADAPTER = BotFrameworkAdapter(SETTINGS)
15
16
17# Create bot to handle incoming messages.
18async def on_message_activity(turn_context: TurnContext):
19    if turn_context.activity.type == ActivityTypes.message:
20        await turn_context.send_activity(f"You said {turn_context.activity.text}")
21
22
23# Listen for incoming requests on /api/messages
24async def messages(request: web.Request) -> web.Response:
25    # Main bot message handler.
26    if "application/json" in request.headers["Content-Type"]:
27        body = await request.json()
28    else:
29        return web.Response(status=415)
30
31    activity = Activity().from_dict(body)
32    auth_header = request.headers.get("Authorization", "")
33
34    response = await ADAPTER.process_activity(activity, auth_header, on_message_activity)
35    if response:
36        return web.json_response(data=response.body, status=response.status)
37    return web.Response(status=201)
38
39
40APP = web.Application()
41APP.router.add_post("/api/messages", messages)
42
43if __name__ == "__main__":
44    try:
45        web.run_app(APP, host="localhost", port=3978)
46    except Exception as error:
47        raise error