Bidirectional chatbot with Flask e socketIO

28 Views Asked by At

I am trying to set up a simple chatbot with a server running Flask and flask_socket and a client made with socketIO python library. The desired flow is as follows:

  1. Alice makes a HTTP request to server endpoint (eg. http://localhost:5000/send)
  2. client (connected to http://localhost:5000) returns bar to the server
  3. server responds to Alice with bar

This is my partial working code, based on Chat-App-Flask-SocketIO project:

app.py

import json
from flask import Flask, render_template, request, redirect, url_for, session
from flask_socketio import SocketIO, join_room, leave_room, emit
from flask_session import Session

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = <SECRET>
app.config['SESSION_TYPE'] = <SESSION_TYPE>

Session(app)

socketio = SocketIO(app, manage_session=False)


@socketio.on('join', namespace='/chat')
def join(message):
    if "room" in message.keys() and "username" in message.keys():
        room = message.get("room")
        username = message.get("username")
    else:
        room = session.get('room')
        username = session.get('username')
    join_room(room)
    emit('status', {'msg':  username + ' has entered the room.'}, room=room)


@socketio.on('text', namespace='/chat')
def text(message):
    if "room" in message.keys() and "username" in message.keys():
        room = message.get("room")
        username = message.get("username")
    else:
        room = session.get('room')
        username = session.get('username')
    emit('message', {'msg': username + ' : ' + message['msg']}, room=room)


@app.route('/send', methods=['GET', 'POST'])
def send():
    if(request.method=='GET'):
        text = request.args.get("text")
        user = request.args.get("username")
        room = request.args.get("room")
        emit('message', {'msg': user + ' : ' + text}, room=room, namespace='/chat')
        # how can I listen for client message and return it via HTTP?
        return json.dumps({'success': True, 'msg':text })


if __name__ == '__main__':
    socketio.run(app, debug=True)

client.py

import socketio

sio = socketio.Client()

@sio.on('message', namespace='/chat')
def receive_custom(msg):
    #print(msg)
    message = msg.get('msg')
    if "foo" in message:
        print("bar")

sio.connect('http://localhost', namespaces=['/chat'])
sio.emit('join', {'room':'test','username':'Bob'}, namespace='/chat')
sio.emit('text', {'room':'test','username':'Bob', 'msg':'Hello!'}, namespace='/chat')
sio.wait()

The code partially works since if I make a GET to http://localhost:5000/send?text=foo&username=Bob&room=test the client prints bar, but I would like to have an HTTP response with bar.

0

There are 0 best solutions below