Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Chat Client with MiniChat support
- local args = { ... }
- if #args < 1 then
- print("Usage: chat_client <username>")
- return
- end
- local username = args[1]
- local modem = peripheral.find("modem")
- if not modem then
- print("Ender Modem not found!")
- return
- end
- local defaultChannel = 1
- modem.open(defaultChannel)
- -- Message history
- local messages = {}
- local maxMessages = 18
- -- Current channel
- local currentChannel = "global"
- -- Function to display chat history
- function displayMessages()
- term.clear()
- term.setCursorPos(1, 1)
- for _, msg in ipairs(messages) do
- print(msg)
- end
- end
- -- Function to send a chat message
- function sendMessage(message)
- modem.transmit(defaultChannel, defaultChannel, {type="message", username=username, channel=currentChannel, message=message})
- end
- -- Function to join a MiniChat channel
- function joinChannel(channel)
- currentChannel = channel
- modem.transmit(defaultChannel, defaultChannel, {type="join", username=username, channel=channel})
- end
- -- Function to receive incoming messages
- function handleIncomingMessage(event, side, freq, replyFreq, message, dist)
- if freq == defaultChannel and type(message) == "table" then
- if message.type == "message" then
- table.insert(messages, message.data)
- if #messages > maxMessages then
- table.remove(messages, 1)
- end
- displayMessages()
- elseif message.type == "status" then
- print(message.data)
- end
- end
- end
- -- Main function for sending and receiving messages
- function chatLoop()
- parallel.waitForAny(
- function()
- while true do
- local input = read()
- if input:sub(1, 8) == "/minichat" then
- local channel = input:sub(10)
- joinChannel(channel)
- else
- sendMessage(input)
- end
- end
- end,
- function()
- while true do
- local event, side, freq, replyFreq, message, dist = os.pullEvent("modem_message")
- handleIncomingMessage(event, side, freq, replyFreq, message, dist)
- end
- end
- )
- end
- -- Start the chat loop
- chatLoop()
- modem.close(defaultChannel)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement