Python Обработка событий Socket.io - PullRequest
0 голосов
/ 04 августа 2020

Я полный новичок, когда дело доходит до сокетов, поэтому, пожалуйста, потерпите меня, если вопрос кажется вам слишком тривиальным. Ниже приведен код, который я нашел в GitLab и пытаюсь понять

import os
import logging
import uuid
import socketio
from aiohttp import web


import sys
sys.path.append('.')



logging.basicConfig(level=logging.WARN,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M')




# Home page
async def index(request):
    index_file = open('examples/rasa_demo/templates/index.html')
    return web.Response(body=index_file.read().encode('utf-8'), headers={'content-type': 'text/html'})


# Action endpoint
async def webhook(request):
    """Webhook to retrieve action calls."""
    action_call = await request.json()
    try:
        response = await executor.run(action_call)
    except ActionExecutionRejection as e:
        logger.error(str(e))
        response = {"error": str(e), "action_name": e.action_name}
        response.status_code = 400
        return response

    return web.json_response(response)


# Web app routing
app = web.Application()
app.add_routes([
    web.get('/', index),
    web.post('/webhook', webhook),
    web.static('/static', 'examples/rasa_demo/static')
])

# Instantiate all bot agents
bots = BotFactory.createAll()

# Websocket through SocketIO with support for regular HTTP endpoints
sio = socketio.AsyncServer(async_mode='aiohttp', cors_allowed_origins='*')
sio.attach(app)


@sio.on('session_request')
async def on_session_request(sid, data):
    if data is None:
        data = {}
    if 'session_id' not in data or data['session_id'] is None:
        data['session_id'] = uuid.uuid4().hex
    await sio.emit('session_confirm', data['session_id'])


@sio.on('user_uttered')
async def on_user_uttered(sid, message):
    custom_data = message.get('customData', {})
    lang = custom_data.get('lang', 'en')
    user_message = message.get('message', '')
    bot_responses = await bots[lang].handle_text(user_message) #await BotFactory.getOrCreate(lang).handle_text(user_message)
    for bot_response in bot_responses:
        json = __parse_bot_response(bot_response)
        await sio.emit('bot_uttered', json, room=sid)

Я пытаюсь понять, как обработчики событий отлавливают такие события, как 'session_request' или'user_uttered ' когда они никогда не испускались. Спасибо.

...