Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Function to list all connected modems
- local function listModems()
- local modems = {}
- for _, side in ipairs(peripheral.getNames()) do
- if peripheral.getType(side) == "modem" then
- table.insert(modems, side)
- end
- end
- return modems
- end
- -- Function to setup the modem
- local function setupModem()
- local modems = listModems()
- if #modems == 0 then
- print("No modems found! Please connect a modem and restart.")
- return nil
- end
- print("Connected modems:")
- for i, side in ipairs(modems) do
- print(i .. ": " .. side)
- end
- -- Open the first modem found
- rednet.open(modems[1])
- print("Using modem on " .. modems[1])
- return modems[1]
- end
- -- Function to display a message in the chat
- local function displayMessage(senderId, message, isOlderClient)
- term.setTextColor(colors.yellow) -- Set text color
- if isOlderClient then
- print("[Unknown User (" .. senderId .. ")]: " .. message) -- Show ID for older clients
- else
- print("[" .. senderId .. "]: " .. message)
- end
- term.setTextColor(colors.white) -- Reset text color
- end
- -- Function to handle incoming messages
- local function handleIncomingMessages()
- while true do
- local senderId, message, protocol = rednet.receive()
- local username, chatMessage = message:match("^(.-): (.+)$")
- if username and chatMessage then
- displayMessage(username, chatMessage, false)
- else
- displayMessage(senderId, message, true) -- Handle messages from older clients
- end
- end
- end
- -- Function to send a message to all connected Rednet users
- local function sendMessage(username)
- while true do
- print("Type your message (or 'exit' to quit): ")
- local userInput = read() -- Get the user's input
- if userInput == "exit" then
- print("Exiting chat...")
- shell.run("/disk/os/gui") -- Run the GUI program on exit
- break
- end
- -- Format the message to include the username
- local formattedMessage = username .. ": " .. userInput
- -- Broadcast the message to all users
- rednet.broadcast(formattedMessage)
- displayMessage(username, userInput, false)
- end
- end
- -- Main program
- term.clear() -- Clear the terminal
- term.setCursorPos(1, 1) -- Set cursor position
- print("Welcome to the Doggy OS Network Chatroom!")
- -- Prompt for the username
- print("Enter your username:")
- local username = read()
- local modemSide = setupModem()
- if modemSide == nil then return end -- Exit if no modem was found
- print("Type 'exit' to leave the chat.")
- -- Start monitoring messages in a separate thread
- parallel.waitForAny(handleIncomingMessages, function()
- sendMessage(username)
- end)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement