Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local PORTS = {{6667, false}, {35565, false}, {12345, false}} -- Тут вводим порты для сетевого интерфейса.
- -- false - порт фильтруется, true - не фильтруется.
- local ALLOWED = {"e51", "83f7"} -- Собственно, фильтр адресов. Сюда можно вводить только часть адреса (что я и делаю).
- local MAX_MSG = 10 -- Максимальное количество сообщений отображаемых.
- local LIFETIME = math.huge -- Количество итераций основного цикла, после которого удаляется первое сообщение, если всего написано более половины.
- local MAX_LEN = 75 -- Максимальная длина сообщения.
- local MOTD = true -- Включить/отключить MOTD. Выводит в чат при старте сервера содержимое файла /etc/chatserver.motd.
- local UTEST = false -- Просто фишка "для красоты". Если чат будет постоянно выключаться, ставим true, и бокс красится в жёлтый.
- local WBOX = 250 -- Ширина бокса. В пикселах.
- local HBOX = 100 -- Высота бокса. Тоже в пикселах.
- local com = require("component")
- local gpu = com.gpu
- local term = require("term")
- local modem = com.modem
- local event = require("event")
- local bridge = com.openperipheral_bridge
- local fs = require("filesystem")
- local unicode = require("unicode")
- comp = require("computer")
- bridge.clear()
- bridge.sync()
- local noexit = true
- local chat = {}
- local ct = {}
- local cmds = {}
- local group = {}
- local user = {}
- local muted = {}
- -- Управление группами --
- -- Набросал несколько в качестве примера.
- --[[GROUPS]]--
- group.default = {
- ["prefix"] = "",
- ["suffix"] = "",
- ["rank"] = 1
- }
- group.prog = {
- ["prefix"] = "[P]",
- ["suffix"] = "",
- ["rank"] = 2
- }
- group.moder = {
- ["prefix"] = "[M]",
- ["suffix"] = "",
- ["rank"] = 3
- }
- group.admin = {
- ["prefix"] = "[A]",
- ["suffix"] = "",
- ["rank"] = 4
- }
- user["Fingercomp"] = "admin"
- user["Asummonster"] = "moder"
- user["Totoro"] = "moder"
- user["Zer0Galaxy"] = "moder"
- user["Krutoy"] = "moder"
- user["AlexCC"] = "admin"
- user["MineUbuntu"] = "prog"
- user["NEO"] = "prog"
- user["YuRaNnNzZZ"] = "moder"
- user["LeshaInc"] = "prog"
- --[[END]]--
- -- Игроки, которые будут в муте при старте сервера автоматически.
- --[[MUTED]]--
- muted["Ki-Hun"] = true
- muted["Byte-Griefer"] = true
- muted["Spam-bot"] = true
- --[[END]]--
- if not fs.exists("/var/log/") then
- if not fs.exists("/var/") then
- fs.makeDirectory("/var/")
- end
- fs.makeDirectory("/var/log/")
- end
- local time = os.date():match("(%d+:%d+):%d")
- local logFile = io.open("/var/log/chatserver_" .. time .. ".log", "w")
- local box = bridge.addGradientBox(5, 30, WBOX, HBOX, 0x000000, 0, 0x00FF00, 0.6, 2)
- for i = 1, MAX_MSG, 1 do
- ct[i] = bridge.addText(5, 20 + i*10, "", 0xFFFFFF)
- ct[i].setScale(0.8)
- end
- bridge.sync()
- if UTEST then
- box.setColor2(0xFFFF00)
- else
- box.setColor2(0x000000)
- end
- bridge.sync()
- modem.setStrength(400)
- for i = 1, #PORTS, 1 do
- modem.open(PORTS[i][1])
- print("Port \"" .. PORTS[i][1] .. "\" opened!")
- end
- local function log(msg)
- logFile:write(msg.."\n")
- print(msg)
- end
- local function insertMsg(msg)
- print("Inserted: " .. msg)
- table.insert(chat, msg)
- if #chat > MAX_MSG then
- table.remove(chat, 1)
- end
- for i = 1, #PORTS, 1 do
- modem.broadcast(PORTS[i][1], msg)
- end
- log(msg)
- end
- local function updateChat()
- print("Syncing...")
- for i = 1, MAX_MSG, 1 do
- if chat[i] ~= nil and chat[i] ~= "" then
- ct[i].setText(chat[i])
- else
- ct[i].setText("")
- end
- end
- bridge.sync()
- end
- -- Система команд.
- -- Базовые команды набросал здесь.
- --[[COMMANDS]]--
- cmds.help = {} -- Объявляем ОБЯЗАТЕЛЬНО команду, как массив (cmds.имякоманды = {})
- cmds.help.desc = "List of available commands" -- Описание команды. (cmds.имякоманды.desc = "описание команды")
- cmds.help.rank = 1 -- Уровень доступа (указывается в группах) (cmds.имякоманды.rank = уровень)
- function cmds.help.func()
- -- Функция вызываемая (function cmds.имяфункции.func(args, sender) end). args - аргументы, разделённые пробелом. sender - тот, кто выполнил команду.
- insertMsg("Help page")
- for i, j in pairs(cmds) do
- insertMsg(i .. " - " .. j.desc)
- end
- end
- cmds.stop = {}
- cmds.stop.desc = "Stop the server"
- cmds.stop.rank = 4
- function cmds.stop.func()
- log("Stopped")
- box.setColor2(0xFF0000)
- bridge.sync()
- os.sleep(1)
- noexit = false
- end
- cmds.list = {}
- cmds.list.desc = "List users who are currently online"
- cmds.list.rank = 1
- function cmds.list.func()
- local users = bridge.getUsers()
- insertMsg("Users")
- for i = 1, #users, 1 do
- insertMsg(users[i]["name"] .. " (" .. users[i]["uuid"] .. ")")
- end
- end
- cmds.clear = {}
- cmds.clear.desc = "Clear the chat"
- cmds.clear.rank = 3
- function cmds.clear.func()
- for i = 1, #chat, 1 do
- table.remove(chat, 1)
- end
- insertMsg("Chat cleared!")
- end
- cmds.setgroup = {}
- cmds.setgroup.desc = "Add a user to a specified group"
- cmds.setgroup.rank = 4
- function cmds.setgroup.func(args)
- local usr = args[1]
- local groupR = args[2]
- if group[groupR] then
- user[usr] = groupR
- insertMsg("User " .. usr .. " joined the group \"" .. groupR .. "\"!")
- end
- end
- cmds.broadcast = {}
- cmds.broadcast.desc = "Broadcast a message"
- cmds.broadcast.rank = 3
- function cmds.broadcast.func(args)
- local message = ""
- for i = 1, #args, 1 do
- message = message .. args[i] .. " "
- end
- message = unicode.sub(message, 1, -2)
- insertMsg("["..os.date() .. "][!B!] " .. unicode.upper(message))
- end
- cmds.mute = {}
- cmds.mute.desc = "Mute the user"
- cmds.mute.rank = 3
- function cmds.mute.func(args, muter)
- local usr = args[1]
- muted[usr] = true
- insertMsg("User \"" .. usr .. "\" is muted ("..muter.."). Enjoy the silence!")
- end
- cmds.unmute = {}
- cmds.unmute.desc = "Unmute the user"
- cmds.unmute.rank = 3
- function cmds.unmute.func(args, unmuter)
- local usr = args[1]
- muted[usr] = false
- insertMsg("User \"" .. usr .. "\" is unmuted (" .. unmuter .. "). Enjoy the freedom!")
- end
- cmds.me = {}
- cmds.me.desc = ""
- cmds.me.rank = 1
- function cmds.me.func(args, usr)
- local msg = ""
- for i = 1, #args, 1 do
- msg = msg .. args[i] .. " "
- end
- msg = unicode.sub(msg, 1, -2)
- insertMsg("["..os.date().."] *** " .. usr .. " " .. msg)
- end
- cmds.ping = {}
- cmds.ping.desc = "Ping the server"
- cmds.ping.rank = 1
- function cmds.ping.func()
- insertMsg("["..os.date() .."] Pong! :)")
- end
- cmds.getinfo = {}
- cmds.getinfo.desc = "Get info about the server"
- cmds.getinfo.rank = 4
- function cmds.getinfo.func()
- local energy = comp.energy()
- local maxEn = comp.maxEnergy()
- local memFree = comp.freeMemory()
- local mem = comp.totalMemory()
- insertMsg("Energy: " .. energy .. "/" .. maxEn)
- insertMsg("Free: " .. memFree .. "B, cons: " .. mem - memFree .. "B, total: " .. mem)
- end
- --[[END]]--
- local function checkCommand(potCom)
- local isCom = false
- if potCom:sub(1,1) == "/" then
- isCom = true
- end
- return isCom
- end
- local function getInfo() end -- For further declaration...
- local function issueCommand(sender, command, args)
- local allowed = false
- log("["..sender.."] Command: " .. command)
- _, _, rank = getInfo(sender)
- if cmds[command] then
- if rank >= cmds[command].rank then
- insertMsg("["..sender.."]: /" .. command)
- cmds[command].func(args, sender)
- end
- end
- end
- function getInfo(usr)
- local prefix, suffix, rank, info
- if user[usr] then
- info = group[user[usr]]
- else
- info = group["default"]
- end
- prefix = info["prefix"]
- suffix = info["suffix"]
- rank = info["rank"]
- return prefix, suffix, rank
- end
- local function onReceive(sender, msg)
- if not muted[sender] then
- if not checkCommand(msg) then
- local prefix, suffix, _ = getInfo(sender)
- insertMsg("[" .. os.date():match("%d+:%d+:%d+") .. "] " .. prefix .. sender .. ": " .. msg .. suffix)
- else
- local args = {}
- for i in msg:gmatch("%s(%S+)") do
- table.insert(args, i)
- end
- local command = msg:match("%w+")
- issueCommand(sender, command, args)
- end
- updateChat()
- end
- end
- local function modemMsg(sender, port, dist, name, msg)
- print(sender, port, dist, name, msg)
- if name:sub(1, 1) == "!" then
- print("Alternate message: " .. name)
- name, msg = name:match("!(w+):(.+)")
- end
- if name and msg then
- msg = unicode.sub(msg, 1, MAX_LEN)
- local allowedPort = false
- local allowedIP = false
- for i = 1, #PORTS, 1 do
- if PORTS[i][1] == port and PORTS[i][2] == true then
- allowedPort = true
- allowedIP = true
- elseif PORTS[i][1] == port and PORTS[i][2] == false then
- allowedPort = true
- end
- end
- for i = 1, #ALLOWED, 1 do
- if sender:match(ALLOWED[i]) then
- allowedIP = true
- end
- end
- if allowedPort and allowedIP then
- onReceive("[NET]" .. name, msg)
- end
- end
- end
- local i = 1
- if MOTD then
- if fs.exists("/etc/chatserver.motd") then
- local file = io.open("/etc/chatserver.motd", "r")
- while true do
- local curLine = file:read()
- if not curLine then break end
- insertMsg(curLine)
- end
- file:close()
- updateChat()
- else
- local file = io.open("/etc/chatserver.motd", "w")
- file:write("")
- file:flush()
- file:close()
- end
- end
- while noexit do
- local event, _, sender, uuid, msg, modem_name, modem_msg = event.pull(1)
- if event == "modem_message" then
- if modem_name ~= nil and modem_name ~= "" then
- modemMsg(sender, uuid, msg, modem_name, modem_msg)
- end
- elseif event == "glasses_chat_command" then
- if msg ~= nil and msg ~= "" then
- msg = unicode.sub(msg, 1, MAX_LEN)
- onReceive(sender, msg)
- end
- elseif event == "glasses_attach" then
- insertMsg("User \"" .. sender .. "\" joined the chat server!")
- updateChat()
- elseif event == "glasses_detach" then
- insertMsg("User \"" .. sender .. "\" left the chat server.")
- updateChat()
- end
- if i == LIFETIME then
- if chat[math.floor(MAX_MSG / 2) + 1] then
- print("clearing...")
- table.remove(chat, 1)
- i = 0
- updateChat()
- else
- i = 0
- end
- logFile:flush()
- end
- i = i + 1
- end
- bridge.clear()
- bridge.sync()
- logFile:close()
- for i = 1, #PORTS, 1 do
- modem.close(PORTS[i][1])
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement