Help with Threading for Chat CLI

Question:
I’m new to therading btw:
How can I make the threading in this code better? I want to make the inputs not get erased on refresh but still be there when enter is pressed. I also want the refreshing to happen only when a new message is added and I dont want refreshing to lag. Also feel free to tell me if there is any other way to make the code better.
Repl link:
https://replit.com/@MiloCat/Chatting-Oversimplified#main.py

import os
import time
import threading
from replit import db

db.db_url ="https://kv.replit.com/v0/eyJhbGciOiJIUzUxMiIsImlzcyI6ImNvbm1hbiIsImtpZCI6InByb2Q6MSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjb25tYW4iLCJleHAiOjE2NzUxMzQ5MzIsImlhdCI6MTY3NTAyMzMzMiwiZGF0YWJhc2VfaWQiOiI2NWFkYzVhNS1mMDE3LTRjNGUtYjkwOC1lODdhYjgxYTliNmEiLCJ1c2VyIjoiTWlsb0NhdCIsInNsdWciOiJDaGF0dGluZy1PdmVyc2ltcGxpcensored.xxxxxxx4ye1VjDayALaku1-E6vxPpOIZO70Fow5x_GsaA9Wa_wS13y_BfBiG471qM84kqxbNf_2BqAJs1hlY93rftK5aQ"

user = os.environ["REPL_OWNER"]
if user in ("MiloCat", "ItsRaphael"):
    checkmark = "✓"
else:
    checkmark = ""
print("[1] Chat\n[2] Leave")
start = input("")

def update_chat():
    while True:
        last_x_messages = db["messages"][-10:] # Only prints the last 10 messages
        print(*last_x_messages, sep='\n')
        time.sleep(1)
        print("\033c", flush=True, end="")

if start == "2":
    thread = threading.Thread(target=update_chat)
    thread.start()
    while True:
        mess = input(f"{checkmark}{user}: ")
        message = f"{checkmark}{user}: {mess}"
        db["messages"].append(message)

Edit:

Solved by @MNA41, his post was removed on here :confused: so we had to talk through disc and I can’t mark his post as solution

You’ve just leaked your/a database url, you might want to keep that secret. You should be using os.environ["REPLIT_DB_URL"]. If you’re accessing the db from another Repl, keep in mind I believe the URL is not persistent, I believe it potentially changes on reboot, otherwise possibly at some other time.

1 Like

I believe the url changes every few days. The reason why I didn’t put it as an env variable is that then it can’t be used.

What stops you from using it?

Ima encrypt it once i’m done, I just havn’t added that yet

You can’t do that. why though? because that’s how the replit terminal works.

When a user runs a text-based/vnc based repl, replit will fork it. (https://replit.com/@MNA4/Replit-system)

Say we have 2 users, user1 and user2. user1 say “hi!”. however, user2 won’t notice that user1 did say “hi”. why? because they each have different db urls.

Maybe this guide could help : An Intro to Threading in Python – Real Python

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.