Advertisement
xX-AAAAAAAAAA-Xx

ComputerCraft EnderChat Server

Sep 14th, 2024 (edited)
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.26 KB | None | 0 0
  1. -- Chat Server with MiniChat support
  2. local modem = peripheral.find("modem")
  3. if not modem then
  4.     print("Ender Modem not found!")
  5.     return
  6. end
  7.  
  8. local defaultChannel = 1
  9. modem.open(defaultChannel)
  10.  
  11. -- Table to store chat logs and users for each MiniChat channel
  12. local channels = {}
  13.  
  14. -- Function to add a user to a channel
  15. function addUserToChannel(channel, username)
  16.     if not channels[channel] then
  17.         -- Create a new channel with the user as owner
  18.         channels[channel] = {
  19.             owner = username,
  20.             users = {},
  21.             messages = {}
  22.         }
  23.     end
  24.  
  25.     -- Add the user to the channel if they are not already in
  26.     if not channels[channel].users[username] then
  27.         channels[channel].users[username] = {
  28.             role = "normal"  -- normal, muted, banned, etc.
  29.         }
  30.     end
  31. end
  32.  
  33. -- Function to handle new messages
  34. function handleChatMessage(channel, username, message)
  35.     -- Make sure the user is in the channel and not banned
  36.     if channels[channel] and channels[channel].users[username] then
  37.         -- Store the message in the channel history
  38.         local formattedMessage = "[" .. username .. "]: " .. message
  39.         table.insert(channels[channel].messages, formattedMessage)
  40.  
  41.         -- Broadcast the message to all users in the channel
  42.         for user, _ in pairs(channels[channel].users) do
  43.             modem.transmit(defaultChannel, defaultChannel, {type="message", channel=channel, data=formattedMessage})
  44.         end
  45.     end
  46. end
  47.  
  48. -- Function to handle incoming requests
  49. function handleRequest(event, side, freq, replyFreq, message)
  50.     if message.type == "join" then
  51.         addUserToChannel(message.channel, message.username)
  52.         modem.transmit(defaultChannel, replyFreq, {type="status", data="Joined channel: " .. message.channel})
  53.  
  54.     elseif message.type == "message" then
  55.         handleChatMessage(message.channel, message.username, message.message)
  56.     end
  57. end
  58.  
  59. -- Main loop to handle incoming messages
  60. print("Server is running...")
  61.  
  62. while true do
  63.     local event, side, freq, replyFreq, message, dist = os.pullEvent("modem_message")
  64.     if freq == defaultChannel and type(message) == "table" then
  65.         handleRequest(event, side, freq, replyFreq, message)
  66.     end
  67. end
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement