import streamlit as st import asyncio import websockets import uuid import argparse from datetime import datetime import os import random import time import hashlib from PIL import Image import glob from urllib.parse import quote import base64 import io import streamlit.components.v1 as components # Initial App Configuration (static) icons = '๐ค๐ง ๐ฌ๐' START_ROOM = "Sector ๐" # Set page config once at the top st.set_page_config( page_title="๐ค๐ง MMO Chat Brain๐๐ฌ", # Initial static title page_icon=icons, layout="wide", initial_sidebar_state="auto" ) # Fun usernames with emojis FUN_USERNAMES = [ "CosmicJester ๐", "PixelPanda ๐ผ", "QuantumQuack ๐ฆ", "StellarSquirrel ๐ฟ๏ธ", "GizmoGuru โ๏ธ", "NebulaNinja ๐ ", "ByteBuster ๐พ", "GalacticGopher ๐", "RocketRaccoon ๐", "EchoElf ๐ง", "PhantomFox ๐ฆ", "WittyWizard ๐ง", "LunarLlama ๐", "SolarSloth โ๏ธ", "AstroAlpaca ๐ฆ", "CyberCoyote ๐บ", "MysticMoose ๐ฆ", "GlitchGnome ๐ง", "VortexViper ๐", "ChronoChimp ๐" ] # Directories and files CHAT_DIR = "chat_logs" VOTE_DIR = "vote_logs" STATE_FILE = "user_state.txt" os.makedirs(CHAT_DIR, exist_ok=True) os.makedirs(VOTE_DIR, exist_ok=True) CHAT_FILE = os.path.join(CHAT_DIR, "global_chat.md") QUOTE_VOTES_FILE = os.path.join(VOTE_DIR, "quote_votes.md") MEDIA_VOTES_FILE = os.path.join(VOTE_DIR, "media_votes.md") HISTORY_FILE = os.path.join(VOTE_DIR, "vote_history.md") # Unicode digits and fonts UNICODE_DIGITS = {i: f"{i}\uFE0Fโฃ" for i in range(10)} UNICODE_FONTS = [ ("Normal", lambda x: x), ("Bold", lambda x: "".join(chr(ord(c) + 0x1D400 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D41A - 0x61) if 'a' <= c <= 'z' else c for c in x)), ] server_running = False server_task = None def get_node_name(): """๐ - Naming Node with Code - Spins a name, oh so bold!""" action = "๐ - Naming Node with Code - Spins a name, oh so bold!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) parser = argparse.ArgumentParser(description='Start a chat node with a specific name') parser.add_argument('--node-name', type=str, default=None) parser.add_argument('--port', type=int, default=8501) args = parser.parse_args() return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port def save_chat_entry(username, message): """๐ - Chat Snap Trap - Logs your yap, no cap! โ๏ธ๐ง """ action = "๐ - Chat Snap Trap - Logs your yap, no cap! โ๏ธ๐ง " # Double rhyme bonus! with open(CHAT_FILE, 'a') as f: f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {username}: {action}\n") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") entry = f"[{timestamp}] {username}: {message}" with open(CHAT_FILE, 'a') as f: f.write(f"{entry}\n") def load_chat(): """๐ - Chat Fetch Quest - Grabs the log, no jest!""" action = "๐ - Chat Fetch Quest - Grabs the log, no jest!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) if not os.path.exists(CHAT_FILE): with open(CHAT_FILE, 'w') as f: f.write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub - start chatting! ๐ค\n") with open(CHAT_FILE, 'r') as f: content = f.read() lines = content.strip().split('\n') return "\n".join(f"{i+1}. {line}" for i, line in enumerate(lines) if line.strip()) def get_user_list(chat_content): """๐ฅ - Crew Clue Brew - Spots whoโs who in the crew!""" action = "๐ฅ - Crew Clue Brew - Spots whoโs who in the crew!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) users = set() for line in chat_content.split('\n'): if line.strip() and ': ' in line: user = line.split(': ')[1].split(' ')[0] users.add(user) return sorted(list(users)) def has_joined_before(client_id, chat_content): """๐ช - Join Check Trek - Sees whoโs back, no wreck!""" action = "๐ช - Join Check Trek - Sees whoโs back, no wreck!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) return any(f"Client-{client_id} has joined" in line for line in chat_content.split('\n')) def get_message_suggestions(chat_content, prefix): """๐ - Suggest Jest Chest - Finds old quips, the best!""" action = "๐ - Suggest Jest Chest - Finds old quips, the best!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) lines = chat_content.split('\n') messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()] return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5] def load_quotes(source="famous"): """๐ - Quote Tote Note - Wise words float, we gloat!""" action = "๐ - Quote Tote Note - Wise words float, we gloat!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) famous_quotes = [ "The true sign of intelligence is not knowledge but imagination. โ Albert Einstein", ] custom_quotes = [ "Every age unfolds a new lesson. Life's chapters evolve, each teaching us anew.", ] return famous_quotes if source == "famous" else custom_quotes def save_vote(file, item, user_hash, username, comment=""): """๐ - Vote Note Float - Cheers rise, we gloat!""" action = "๐ - Vote Note Float - Cheers rise, we gloat!" save_chat_entry(username, action) timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") entry = f"[{timestamp}] {user_hash} voted for {item}" with open(file, 'a') as f: f.write(f"{entry}\n") with open(HISTORY_FILE, "a") as f: f.write(f"- {timestamp} - User {user_hash} voted for {item}\n") chat_message = f"{username} upvoted: \"{item}\"" if comment: chat_message += f" - {comment}" save_chat_entry(username, chat_message) def load_votes(file): """๐ - Tally Rally Call - Counts the cheers, no stall!""" action = "๐ - Tally Rally Call - Counts the cheers, no stall!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) if not os.path.exists(file): with open(file, 'w') as f: f.write("# Vote Tally\n\nNo votes yet - get clicking! ๐ฑ๏ธ\n") with open(file, 'r') as f: lines = f.read().strip().split('\n')[2:] # Skip header votes = {} user_votes = set() for line in lines: if line.strip() and 'voted for' in line: user_hash = line.split('] ')[1].split(' voted for ')[0] item = line.split('voted for ')[1] vote_key = f"{user_hash}-{item}" if vote_key not in user_votes: votes[item] = votes.get(item, 0) + 1 user_votes.add(vote_key) return votes def generate_user_hash(): """๐ - Hash Dash Bash - Crafts a code, so brash!""" action = "๐ - Hash Dash Bash - Crafts a code, so brash!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) if 'user_hash' not in st.session_state: st.session_state.user_hash = hashlib.md5(str(random.getrandbits(128)).encode()).hexdigest()[:8] return st.session_state.user_hash def save_pasted_image(image_data): """๐ธ - Snap Cap Trap - Saves your pic, no flap!""" action = "๐ธ - Snap Cap Trap - Saves your pic, no flap!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"paste_{timestamp}.png" filepath = os.path.join('./', filename) if ',' in image_data: image_data = image_data.split(',')[1] img_bytes = base64.b64decode(image_data) img = Image.open(io.BytesIO(img_bytes)) img.save(filepath, "PNG") return filename def get_video_html(video_path, width="100%"): """๐ฅ - Reel Deal Steal - Plays your flick, so real!""" action = "๐ฅ - Reel Deal Steal - Plays your flick, so real!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}" return f'' def get_audio_html(audio_path, width="100%"): """๐ถ - Tune Moon Boom - Drops a beat, so groom!""" action = "๐ถ - Tune Moon Boom - Drops a beat, so groom!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}" return f'' active_connections = {} async def websocket_handler(websocket, path): """๐ - Web Sock Jock - Links the chat, no block!""" action = "๐ - Web Sock Jock - Links the chat, no block!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) try: client_id = str(uuid.uuid4()) room_id = "chat" active_connections.setdefault(room_id, {})[client_id] = websocket chat_content = load_chat() username = st.session_state.get('username', random.choice(FUN_USERNAMES)) if not has_joined_before(client_id, chat_content): save_chat_entry(f"Client-{client_id}", f"{username} has joined {START_ROOM}!") async for message in websocket: parts = message.split('|', 1) if len(parts) == 2: username, content = parts save_chat_entry(username, content) await broadcast_message(f"{username}|{content}", room_id) except websockets.ConnectionClosed: pass finally: if room_id in active_connections and client_id in active_connections[room_id]: del active_connections[room_id][client_id] async def broadcast_message(message, room_id): """๐ข - Shout Out Bout - Blasts the word, no doubt!""" action = "๐ข - Shout Out Bout - Blasts the word, no doubt!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) if room_id in active_connections: disconnected = [] for client_id, ws in active_connections[room_id].items(): try: await ws.send(message) except websockets.ConnectionClosed: disconnected.append(client_id) for client_id in disconnected: del active_connections[room_id][client_id] async def run_websocket_server(): """๐ฅ๏ธ - Server Ferver Verve - Spins the web, with nerve!""" action = "๐ฅ๏ธ - Server Ferver Verve - Spins the web, with nerve!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) global server_running, server_task if not server_running: server = await websockets.serve(websocket_handler, '0.0.0.0', 8765) server_running = True await server.wait_closed() def create_streamlit_interface(): """๐จ - UI Brew Crew - Builds the view, so new!""" action = "๐จ - UI Brew Crew - Builds the view, so new!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) # Dynamic title based on username if 'username' in st.session_state: dynamic_title = f"๐ค๐ง MMO {st.session_state.username}๐๐ฌ" else: dynamic_title = "๐ค๐ง MMO Chat Brain๐๐ฌ" # Base CSS st.markdown(""" """, unsafe_allow_html=True) st.title(dynamic_title) st.markdown(f"Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy! ๐") # Initialize client ID and username if 'client_id' not in st.session_state: st.session_state.client_id = str(uuid.uuid4()) if 'username' not in st.session_state: available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in load_chat().split('\n'))] st.session_state.username = random.choice(available_names) if available_names else random.choice(FUN_USERNAMES) # Session state initialization if 'refresh_rate' not in st.session_state: st.session_state.refresh_rate = 5 if 'timer_start' not in st.session_state: st.session_state.timer_start = time.time() if 'quote_index' not in st.session_state: quotes = load_quotes("famous") st.session_state.quote_index = random.randint(0, max(0, len(quotes) - 1)) if quotes else 0 if 'quote_source' not in st.session_state: st.session_state.quote_source = "famous" if 'pasted_image_data' not in st.session_state: st.session_state.pasted_image_data = None if 'message_text' not in st.session_state: st.session_state.message_text = "" # JavaScript component for image paste paste_component = components.html( """
โณ {font_func('Refresh in:')} {countdown_str}
", unsafe_allow_html=True) time.sleep(1) st.rerun() # Sidebar vote stats st.sidebar.subheader("Vote Counts") chat_votes = load_votes(QUOTE_VOTES_FILE) media_votes = load_votes(MEDIA_VOTES_FILE) for item, count in {**chat_votes, **media_votes}.items(): if count > 0: st.sidebar.write(f"{item}: {count} votes") async def main(): """๐ฎ - Game Fame Claim - Starts the fun, no shame!""" action = "๐ฎ - Game Fame Claim - Starts the fun, no shame!" save_chat_entry(st.session_state.get('username', 'System ๐'), action) global NODE_NAME, server_task NODE_NAME, port = get_node_name() if server_task is None: server_task = asyncio.create_task(run_websocket_server()) create_streamlit_interface() if __name__ == "__main__": asyncio.run(main())