0

User1 received a message from user2 and user3, but the response message was sent to the user user1 last created chat with and is saving as such in the database. So I can't chat with more than one user at the same time.I am not getting any error. Thank you for your help.

I tried many things from artificial intelligence, but I can't get any results, when I reply to the incoming message, the receiver does not record correctly

#app.py:

@app.route('/messages', methods=['GET', 'POST'])
def messages():
    if request.method == 'POST':
        username = request.form['username']
        recipient = request.form['recipient']
        session['username'] = username
        session['recipient'] = recipient
        return redirect(url_for('chat_with', sender=username))
    else:
        return render_template('messages.html')

@socketio.on('join', namespace='/chat')
def join(message):
    username = session.get('username')
    recipient = session.get('recipient')
    join_room(get_private_room_name(username, recipient))
    if session.get('publish_message', False):
        emit('status', {'msg': username + ' has entered the chat.'}, room=get_private_room_name(username, recipient))


@app.route('/inbox', methods=['GET', 'POST'])
@login_required
def inbox():
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT * FROM users WHERE username = %s", (session["username"],))
    user = cursor.fetchone()
    username = user['username']
    if request.method == 'POST':
        recipient = request.form['recipient']
        session['recipient'] = recipient
        session['username'] = username  
        join_room(get_private_room_name(username, recipient))
        return redirect(url_for('chat_with', sender=username, recipient=recipient))

    cursor.execute("""
        SELECT sender, MAX(date_time) AS max_date_time
        FROM messages
        WHERE recipient = %s
        GROUP BY sender
    """, (username,))
    messages = cursor.fetchall()
    cursor.close()
    return render_template('inbox.html', username=username, messages=messages)

@app.route('/chat', methods=['GET', 'POST'])
@login_required
def chat():
    if request.method == 'POST':
        username = request.form['username']
        recipient = request.form['recipient']
        session['username'] = username
        session['recipient'] = recipient
        messages = get_messages_from_database(username, recipient)
        return render_template('chat.html', session=session, messages=messages)
    else:
        if session.get('username') is not None:
            messages = []
            return render_template('chat.html', session=session, messages=messages)
        else:
            return redirect(url_for('index'))


@app.route('/chat/<sender>', methods=['GET', 'POST'])
@login_required
def chat_with(sender):
    cursor = mysql.connection.cursor()
    sorgu = "SELECT * FROM users WHERE username = %s"
    result = cursor.execute(sorgu, (session["username"],))
    current_user = cursor.fetchone()

    sorgu = "SELECT * FROM profile WHERE author = %s"
    result = cursor.execute(sorgu, (sender,))
    chat_with_user = cursor.fetchone()
    if not chat_with_user:
        flash("Böyle bir kullanıcı bulunamadı...")
        return render_template("index.html", username=current_user["username"])

    if request.method == 'POST':  
        username = session.get('username')
        recipient = session.get('recipient')
        msg = request.form['message']  
        cursor.execute("INSERT INTO messages (sender, recipient, message, username) VALUES (%s, %s, %s, %s)",
                       (username, recipient, msg, get_private_room_name(username, recipient)))
        mysql.connection.commit()

    cursor.execute("""
        SELECT sender, recipient, message, sent_at
        FROM messages
        WHERE (sender=%s AND recipient=%s) OR (sender=%s AND recipient=%s)
        ORDER BY sent_at ASC
    """, (current_user['username'], sender, sender, current_user['username']))
    
    messages = cursor.fetchall()
    cursor.close()

    profile = get_profile_from_session(session)

    return render_template("chat.html", session=session, profile=profile, current_user=current_user,
                           chat_with_user=chat_with_user, messages=messages) 


@socketio.on('text', namespace='/chat')
def text(message):
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT profile_picture FROM profile WHERE author = %s", (session["username"],))
    username = session.get('username')
    recipient = session.get('recipient')
    profile_picture = session.get("profile-picture")
    sent_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # Get the current date and time
    msg = message['msg']
    result = cursor.fetchone()
    if result is not None:
        profile_picture = result['profile_picture']
    cursor.execute("INSERT INTO messages (sender, recipient, message, username, sent_at) VALUES (%s, %s, %s, %s, %s)",
                   (username, recipient, msg, get_private_room_name(username, recipient), sent_at))
    mysql.connection.commit()
    cursor.close()
    emit('message', {'profile_picture': profile_picture, 'username': username, 'msg': msg, 'sent_at': sent_at},
         room=get_private_room_name(username, recipient))

@socketio.on('left', namespace='/chat')
def left(message):
    username = session.get('username')
    recipient = session.get('recipient')
    leave_room(get_private_room_name(username, recipient))
    emit('status', {'msg': username + ' has left the chat.'}, room=get_private_room_name(username, recipient))


def get_private_room_name(username, recipient):
    if username is not None and recipient is not None:
        return f"{min(username, recipient)}_{max(username, recipient)}"
    else:
        pass


def get_messages_from_database(sender, recipient):
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT * FROM messages WHERE (sender=%s AND recipient=%s) OR (sender=%s AND recipient=%s)", (sender, recipient, recipient, sender))
    messages = cursor.fetchall()
    cursor.close()
    return messages

def get_profile_from_session(session):
    username = session.get('username')
    recipient = session.get('recipient')
    profile = {
        'username': username,
        'recipient': recipient,
        'profile_picture': 'default_profile_picture.jpg' 
    }
    return profile


#chat.html:

{% extends "layout.html" %}
{% block body %}
<link rel="stylesheet" type="text/css" href="../static/chat-style.css">
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" charset="utf-8">
  var socket;
  $(document).ready(function(){
    socket = io.connect('http://' + document.domain + ':' + location.port + '/chat');
    socket.on('connect', function() {
      var sender = "{{ session['username'] }}";
      var formActionUrl = '/chat/' + sender;
      $('#chatForm').attr('action', formActionUrl);
      socket.emit('join', {});
    });
    socket.on('status', function(data) {
      $('#chat').append('<p><strong>' + data.msg + '</strong></p>');
      $('#chat').scrollTop($('#chat')[0].scrollHeight);
    });
socket.on('message', function(data) {
  var username = "{{ session['username'] }}";
  if (data.username === username) {
    $('#chat').append(`
      <div class="outgoing">
        <p class="message-date">${data['sent_at']}</p>
        <img src="{{ url_for('static', filename='profile_picture/default_profile_picture.jpg') }}" alt="Profile Picture" class="profile-picture" />
        <p>
          <em><span class="username-outgoing">${username}:</span></em> ${data.msg}
        </p>
      </div>
    `);
  } else {
    $('#chat').append(`
      <div class="incoming">
        <p class="message-date">${data['sent_at']}</p>
        <img src="{{ url_for('static', filename='profile_picture/default_profile_picture.jpg') }}" alt="Profile Picture" class="profile-picture" />
        <p>
          <em><span class="username-outgoing">${data.username}:</span></em> ${data.msg}
        </p>
      </div>
    `);
  }
  $('#chat').scrollTop($('#chat')[0].scrollHeight);
});

    $('#send').click(function(e) {
      text = $('#text').val();
      $('#text').val('');
      socket.emit('text', {msg: text});
    });
    $('#text').keypress(function(event) {
      if (event.which === 13 && !event.shiftKey) {
        event.preventDefault(); 
        $('#send').click(); 
      }
    });
    
  });
  function leave_room() {
    socket.emit('left', {}, function() {
      socket.disconnect();
      window.location.href = "{{ url_for('inbox') }}";
    });
  }
</script>

    <body class="text-center">
      <div class="chatwindow">
        <div class="messenger">
          <h3>Messenger</h3>
        </div>
        <div class="leave-button">
          <div data-bs-theme="dark">
            <br>
            <button type="button" onclick="leave_room()" class="btn-close" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
      </div>
      <br>
        <div class="username">
          <a class="nav-link" href="/user/{{ session['recipient'] }}">
            {{ session['recipient'] }}
          </a>
        </div>
        <div class="container" id="chat">
          {% for message in messages %}
            {% if message.sender == session['username'] %}

            <div class="outgoing">
              <p class="message-date">{{ message.sent_at }}</p>
              <img src="{{ url_for('static', filename='profile_picture/default_profile_picture.jpg') }}" alt="Profile Picture" class="profile-picture" />
              <p class="outgoing-outgoing"><em><span class="username-outgoing">{{ message.sender }}:</span></em> {{ message.message }}</p>
            </div>
            
            {% else %}
            <div class="incoming">
              <p class="message-date">{{ message.sent_at }}</p>
              <a href="/user/{{ message.sender }}"><img src="{{ url_for('static', filename='profile_picture/default_profile_picture.jpg') }}" alt="Profile Picture" class="profile-picture" /></a>
              <a href="/user/{{ message.sender }}" class="profile-link">
                <p class="incoming-incoming">
                  <em><a href="/user/{{ message.sender }}"><span class="username-incoming">{{ message.sender }}</span></a>:</em> 
                  {{ message.message }}
                </p>
              </a>
            </div>
            
            {% endif %}
          {% endfor %}
        </div>
        
        
      <br /><br/>
      <input type="text" id="text" size="60" placeholder="Enter your message here" />
      <button type="button" id="send" class="btn btn-success">SEND</button><br /><br />
    </div>
  </body>
</html>

{% endblock %}
#messages.html:

{% extends 'layout.html' %}

{% block body %}

<head>
  <title>Chat</title>
  <link href="../static/bootstrap.min.css" rel="stylesheet">
  <link href="../static/chat-style.css" rel="stylesheet">
</head>

<body class="text-center">
  <form method="POST" action="{{ url_for('chat', sender=session['username']) }}">

    <h1 class="h2 mb-3 font-weight-normal"></h1><br><br>
    <input type="text" id="username" name="username" class="form-control" placeholder="Username" value="{{ session['username'] }}" required autofocus><br>
    <input type="text" id="recipient" name="recipient" class="form-control" placeholder="Recipient" required><br>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Start Chat</button>
</form>


</body>

{% endblock %}

#inbox.html:
{% extends "layout.html" %}

{% block body %}
<div class="inbox">
    <h1>Mesajlar</h1>
    <hr>
    {% for message in messages %}
        <ul>
            <li id="{{ message.sender }}" onclick="openChat('{{ message.sender }}')">
                <div class="sender">{{ message.sender }}</div>
                <div class="summary">{{ message.message }}</div>
                <div class="timestamp">{{ message.date_time }}</div>
            </li>
        </ul>
    {% endfor %}
</div>

<script>
    function openChat(sender) {
        var username = "{{ username }}";  
        window.location.href = "/chat/" + sender + "?username=" + username;  // Değiştirildi
    }
</script>
{% endblock %}

  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Jun 06 '23 at 21:06

0 Answers0