Empty / app.py
OzoneAsai's picture
Update app.py
55021e9
import streamlit as st
from datetime import datetime
import os
# Create a directory to store messages
messages_dir = "messages"
if not os.path.exists(messages_dir):
os.makedirs(messages_dir)
# Initialize session state to store the list of threads
if 'thread_list' not in st.session_state:
st.session_state.thread_list = []
# Create a dictionary to store messages and threads
messages = {}
def create_thread(thread_id, user_input):
thread = {'messages': [user_input], 'created_at': datetime.now()}
messages[thread_id] = thread
st.session_state.thread_list.append(thread_id)
def add_message(thread_id, user_input):
if thread_id in messages:
messages[thread_id]['messages'].append(user_input)
else:
create_thread(thread_id, user_input)
def save_message_to_file(thread_id, message):
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
file_name = f"{messages_dir}/{thread_id}_{timestamp}.txt"
with open(file_name, 'w') as file:
file.write(message)
# Main app
def main():
st.title("Free Board with Streamlit")
# User input for creating a new thread
new_thread = st.text_input("Create a new thread:", key='new_thread_input')
if new_thread:
create_thread(new_thread, "Thread created.")
st.success(f"Thread '{new_thread}' created!")
# Display existing threads
st.subheader("Existing Threads")
for thread_id in st.session_state.thread_list:
st.write(f"- {thread_id}")
# Allow user to select a thread and add messages
thread_to_post = st.selectbox("Select a thread to post:", st.session_state.thread_list, key='thread_to_post')
if thread_to_post:
user_input = st.text_area("Write your message:", key='user_input')
if user_input:
add_message(thread_to_post, user_input)
save_message_to_file(thread_to_post, user_input) # Save the message to a file
st.success("Message added!")
# Display threads and their messages
for thread_id, thread_data in messages.items():
st.subheader(f"Thread: {thread_id}")
for message in thread_data['messages']:
st.write(f"- {message}")
if __name__ == "__main__":
main()