How can I make a simple 2 user chat messenger in python using GetStream.io and Flask?

65 Views Asked by At

I am very new to getstream and flask, and I asked AI to help me with code, but its database is old, so code is not working.

The error message is here: AttributeError: 'StreamChat' object has no attribute 'create_user' So it says no create_user, what can I use instead?

Here is the code:

from flask import Flask, render_template, request, redirect, url_for
from stream_chat import StreamChat

app = Flask(__name__)

stream_api_key = "MY_API_KEY_DO_NOT_READ"
stream_api_secret = "MY_SECRET_CODE_DO_NOT_READ"

chat_client = StreamChat(api_key=stream_api_key, api_secret=stream_api_secret)

users_data = {
    'user1': {'password': 'password1'},
    'user2': {'password': 'password2'},
}

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username in users_data and users_data[username]['password'] == password:
            return redirect(url_for('chat', username=username))

    return render_template('index.html')

@app.route('/chat/<username>', methods=['GET', 'POST'])
def chat(username):
    user = chat_client.create_user(id=username)

    channel_id = f'direct-{user["id"]}-user1'
    channel = chat_client.channel('messaging', channel_id, { 'members': [user["id"], 'user1'] })

    # Function to send a message
    def send_message(text):
        message = {
            'text': text,
            'user': user['id'],
        }
        channel.send_message(message)

    # Function to receive and display messages
    def receive_messages():
        events = channel.watch()
        messages = []
        for event in events:
            if event['type'] == 'message.new':
                message = event['message']
                messages.append({'user': message['user'], 'text': message['text']})
        return messages

    if request.method == 'POST':
        user_message = request.form['user_message']
        send_message(user_message)

    messages = receive_messages()

    return render_template('chat.html', username=username, messages=messages)

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

I don't think I need to share the htmls because the front-end is working properly.

0

There are 0 best solutions below