Search code examples
pythonflaskflask-sqlalchemyflask-socketio

Chat messages duplicated when reloading page - Flask chat application


I have created a chat application in flask that has option to dm your friends. The messages save and load from the database. However when you refresh the page it will duplicate all the messages and send them to the other user, note that it does not make entries in the database.

@socketio.on('message')
def handle_message(data):
    username = data.get('username')
    message = data.get('message')
    room = data.get('room')

    # Save the message to the database
    if room in rooms():
        new_message = Message(
            user_id=current_user.id,
            room_id=room,
            message=message
        )
        db.session.add(new_message)
        db.session.commit()

    # Broadcast the message to all participants in the room
    emit("message", {"username": username, "message": message}, to=room)
        
@socketio.on('join')
def on_join(data):
    username = data.get('username')
    room = data.get('room')
    
    # Join the room
    join_room(room)
    
    # Load messages for the room from the database
    messages = Message.query.filter_by(room_id=room).all()
    
    # Emit each message to the user who joined the room
    for message in messages:
        emit("message", {"username": message.user.username, "message": message.message}, to=room)

The problem is that the user is re-joining the room everytime the user refreshes the page. (I believe)

I tried socketio.emit and also socketio.send however it didn't do a diffrence. I'm kinda stuck right not and would appriciate some help.

I'm expecting the messages to load once and when i refresh the page it shouldn't spam the other user. It should work like any other messaging app, discord, skype, etc.

Thanks in advance!


Solution

  • You are sending the messages to the room, so all the people who are in the room will get them. Instead, send the messages to the user that is entering the room:

        for message in messages:
            emit("message", {"username": message.user.username, "message": message.message}, to=request.sid)