DOGGYWOOF

Chatroom rednet

Sep 24th, 2024 (edited)
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. -- Function to list all connected modems
  2. local function listModems()
  3. local modems = {}
  4. for _, side in ipairs(peripheral.getNames()) do
  5. if peripheral.getType(side) == "modem" then
  6. table.insert(modems, side)
  7. end
  8. end
  9. return modems
  10. end
  11.  
  12. -- Function to setup the modem
  13. local function setupModem()
  14. local modems = listModems()
  15. if #modems == 0 then
  16. print("No modems found! Please connect a modem and restart.")
  17. return nil
  18. end
  19.  
  20. print("Connected modems:")
  21. for i, side in ipairs(modems) do
  22. print(i .. ": " .. side)
  23. end
  24.  
  25. -- Open the first modem found
  26. rednet.open(modems[1])
  27. print("Using modem on " .. modems[1])
  28. return modems[1]
  29. end
  30.  
  31. -- Function to display a message in the chat
  32. local function displayMessage(senderId, message)
  33. term.setTextColor(colors.yellow) -- Set text color
  34. print("[" .. senderId .. "]: " .. message)
  35. term.setTextColor(colors.white) -- Reset text color
  36. end
  37.  
  38. -- Function to handle incoming messages
  39. local function handleIncomingMessages()
  40. while true do
  41. local senderId, message, protocol = rednet.receive()
  42. displayMessage(senderId, message)
  43. end
  44. end
  45.  
  46. -- Function to send a message to all connected Rednet users
  47. local function sendMessage()
  48. while true do
  49. print("Type your message (or 'exit' to quit): ")
  50. local userInput = read() -- Get the user's input
  51. if userInput == "exit" then
  52. print("Exiting chat...")
  53. break
  54. end
  55. -- Broadcast the message to all users
  56. rednet.broadcast(userInput)
  57. displayMessage("You", userInput)
  58. end
  59. end
  60.  
  61. -- Main program
  62. term.clear() -- Clear the terminal
  63. term.setCursorPos(1, 1) -- Set cursor position
  64.  
  65. print("Welcome to the Enhanced Rednet Chat Room!")
  66. local modemSide = setupModem()
  67. if modemSide == nil then return end -- Exit if no modem was found
  68.  
  69. print("Type 'exit' to leave the chat.")
  70. -- Start monitoring
  71. parallel.waitForAny(handleIncomingMessages, sendMessage)
  72.  
Add Comment
Please, Sign In to add comment