Advertisement
Guest User

Untitled

a guest
Apr 24th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.41 KB | None | 0 0
  1. local PORTS = {{1, false}, {2, false}, {3, false}} -- Тут вводим порты для сетевого интерфейса.
  2. -- false - порт фильтруется, true - не фильтруется.
  3. local ALLOWED = {"e51", "83f7"} -- Собственно, фильтр адресов. Сюда можно вводить только часть адреса (что я и делаю).
  4. local MAX_MSG = 7 -- Максимальное количество сообщений отображаемых.
  5. local LIFETIME = math.huge -- Количество итераций основного цикла, после которого удаляется первое сообщение, если всего написано более половины.
  6. local MAX_LEN = 75 -- Максимальная длина сообщения.
  7. local MOTD = true -- Включить/отключить MOTD. Выводит в чат при старте сервера содержимое файла /etc/chatserver.motd.
  8. local UTEST = false -- Просто фишка "для красоты". Если чат будет постоянно выключаться, ставим true, и бокс красится в жёлтый.
  9. local WBOX = 350 -- Ширина бокса. В пикселах.
  10. local HBOX = 75 -- Высота бокса. Тоже в пикселах.
  11.  
  12. local com = require("component")
  13. local gpu = com.gpu
  14. local term = require("term")
  15. local modem = com.modem
  16. local event = require("event")
  17. local bridge = com.openperipheral_bridge
  18. local fs = require("filesystem")
  19. local unicode = require("unicode")
  20. comp = require("computer")
  21.  
  22. bridge.clear()
  23. bridge.sync()
  24.  
  25. local noexit = true
  26. local chat = {}
  27. local ct = {}
  28. local cmds = {}
  29. local group = {}
  30. local user = {}
  31. local muted = {}
  32.  
  33. -- Управление группами --
  34. -- Набросал несколько в качестве примера.
  35. --[[GROUPS]]--
  36.  
  37. group.default = {
  38. ["prefix"] = " [Новичок] ",
  39. ["suffix"] = "",
  40. ["rank"] = 1
  41. }
  42.  
  43. group.prog = {
  44. ["prefix"] = " [Прошареный] ",
  45. ["suffix"] = "",
  46. ["rank"] = 2
  47. }
  48.  
  49. group.moder = {
  50. ["prefix"] = " [Mодер] ",
  51. ["suffix"] = "",
  52. ["rank"] = 3
  53. }
  54.  
  55. group.admin = {
  56. ["prefix"] = " [Админ] ",
  57. ["suffix"] = "",
  58. ["rank"] = 4
  59. }
  60.  
  61. group.jefferson = {
  62. ["prefix"] = " [Основатель] ",
  63. ["suffix"] = "",
  64. ["rank"] = 5
  65. }
  66.  
  67. group.rofl = {
  68. ["prefix"] = " [Пидор] ",
  69. ["suffix"] = "",
  70. ["rank"] = 3
  71. }
  72.  
  73. user["Joker95"] = "jefferson"
  74. user["LancePanthera"] = "rofl"
  75. user["nic0n0R"] = "moder"
  76.  
  77. --[[END]]--
  78.  
  79. -- Игроки, которые будут в муте при старте сервера автоматически.
  80. --[[MUTED]]--
  81.  
  82. --[[END]]--
  83.  
  84.  
  85. if not fs.exists("/var/log/") then
  86. if not fs.exists("/var/") then
  87. fs.makeDirectory("/var/")
  88. end
  89. fs.makeDirectory("/var/log/")
  90. end
  91. local time = os.date():match("(%d+:%d+):%d")
  92. local logFile = io.open("/log.log", "w")
  93. local box = bridge.addBox(5, 30, WBOX, HBOX, 0x0061ff, 0.5)
  94. for i = 1, MAX_MSG, 1 do
  95. ct[i] = bridge.addText(5, 20 + i*10, "", 0x3bff00)
  96. ct[i].setScale(1)
  97. end
  98. bridge.sync()
  99.  
  100. bridge.sync()
  101. modem.setStrength(400)
  102.  
  103. for i = 1, #PORTS, 1 do
  104. modem.open(PORTS[i][1])
  105. print("Порт \"" .. PORTS[i][1] .. "\" открыт!")
  106. end
  107.  
  108. local function log(msg)
  109. logFile:write(msg.."\n")
  110. print(msg)
  111. end
  112.  
  113. local function insertMsg(msg)
  114. --print("Вставлено: " .. msg)
  115. table.insert(chat, msg)
  116. if #chat > MAX_MSG then
  117. table.remove(chat, 1)
  118. end
  119. for i = 1, #PORTS, 1 do
  120. modem.broadcast(PORTS[i][1], msg)
  121. end
  122. log(msg)
  123. end
  124.  
  125. local function updateChat()
  126. for i = 1, MAX_MSG, 1 do
  127. if chat[i] ~= nil and chat[i] ~= "" then
  128. ct[i].setText(chat[i])
  129. else
  130. ct[i].setText("")
  131. end
  132. end
  133. bridge.sync()
  134. end
  135.  
  136. -- Система команд.
  137. -- Базовые команды набросал здесь.
  138. --[[COMMANDS]]--
  139. cmds.help = {} -- Объявляем ОБЯЗАТЕЛЬНО команду, как массив (cmds.имякоманды = {})
  140. cmds.help.desc = "Список доступных команд" -- Описание команды. (cmds.имякоманды.desc = "описание команды")
  141. cmds.help.rank = 1 -- Уровень доступа (указывается в группах) (cmds.имякоманды.rank = уровень)
  142. function cmds.help.func()
  143. -- Функция вызываемая (function cmds.имяфункции.func(args, sender) end). args - аргументы, разделённые пробелом. sender - тот, кто выполнил команду.
  144. insertMsg("Старница помощи")
  145. for i, j in pairs(cmds) do
  146. insertMsg(i .. " - " .. j.desc)
  147. end
  148. end
  149.  
  150. cmds.stop = {}
  151. cmds.stop.desc = "Остановить сервер сообщений"
  152. cmds.stop.rank = 4
  153. function cmds.stop.func()
  154. log("Остановлено")
  155. --box.setColor2(0xFF0000)
  156. bridge.clear()
  157. bridge.sync()
  158. os.sleep(1)
  159. noexit = false
  160. end
  161.  
  162. cmds.list = {}
  163. cmds.list.desc = "Список игроков онлайн"
  164. cmds.list.rank = 3
  165. function cmds.list.func()
  166. local users = bridge.getUsers()
  167. insertMsg("Игроки")
  168. for i = 1, #users, 1 do
  169. insertMsg(users[i]["name"] .. " (" .. users[i]["uuid"] .. ")")
  170. end
  171. end
  172.  
  173. cmds.clear = {}
  174. cmds.clear.desc = "Чистит чат"
  175. cmds.clear.rank = 4
  176. function cmds.clear.func()
  177. for i = 1, #chat, 1 do
  178. table.remove(chat, 1)
  179. end
  180. insertMsg("Чат очищен!")
  181. end
  182.  
  183. cmds.setgroup = {}
  184. cmds.setgroup.desc = "Игрок добавлен в указанную группу"
  185. cmds.setgroup.rank = 5
  186. function cmds.setgroup.func(args)
  187. local usr = args[1]
  188. local groupR = args[2]
  189. if group[groupR] then
  190. user[usr] = groupR
  191. insertMsg("Игрок " .. usr .. " присоеденился к группе \"" .. groupR .. "\"!")
  192. end
  193. end
  194.  
  195. cmds.broadcast = {}
  196. cmds.broadcast.desc = "Вещать сообщение"
  197. cmds.broadcast.rank = 4
  198. function cmds.broadcast.func(args)
  199. local message = ""
  200. for i = 1, #args, 1 do
  201. message = message .. args[i] .. " "
  202. end
  203. message = unicode.sub(message, 1, -2)
  204. insertMsg("["..os.date() .. "][!B!] " .. unicode.upper(message))
  205. end
  206.  
  207. cmds.mute = {}
  208. cmds.mute.desc = "Замутить игрока"
  209. cmds.mute.rank = 3
  210. function cmds.mute.func(args, muter)
  211. local usr = args[1]
  212. if muted[usr] == true then return insertMsg(""..usr.." уже замучен!")
  213. end
  214. muted[usr] = true
  215. insertMsg("Игрок \"" .. usr .. "\" был замучен ("..muter..").")
  216. end
  217.  
  218. cmds.unmute = {}
  219. cmds.unmute.desc = "Размутить игрока"
  220. cmds.unmute.rank = 3
  221. function cmds.unmute.func(args, unmuter)
  222. local usr = args[1]
  223. if muted[usr] == false then return insertMsg(""..usr.." не замучен!")
  224. end
  225. muted[usr] = false
  226. insertMsg("Игрок \"" .. usr .. "\" был размучен (" .. unmuter .. ").")
  227. end
  228.  
  229. cmds.me = {}
  230. cmds.me.desc = ""
  231. cmds.me.rank = 1
  232. function cmds.me.func(args, usr)
  233. local msg = ""
  234. for i = 1, #args, 1 do
  235. msg = msg .. args[i] .. " "
  236. end
  237. msg = unicode.sub(msg, 1, -2)
  238. insertMsg("["..os.date().."] *** " .. usr .. " " .. msg)
  239. end
  240.  
  241. cmds.ping = {}
  242. cmds.ping.desc = "Пинг до сервера"
  243. cmds.ping.rank = 2
  244. function cmds.ping.func()
  245. insertMsg("["..os.date() .."] Пинг!")
  246. end
  247.  
  248. cmds.getinfo = {}
  249. cmds.getinfo.desc = "Получить информацию о сервере"
  250. cmds.getinfo.rank = 5
  251. function cmds.getinfo.func()
  252. local energy = comp.energy()
  253. local maxEn = comp.maxEnergy()
  254. local memFree = comp.freeMemory()
  255. local mem = comp.totalMemory()
  256. insertMsg("Энергия: " .. energy .. "/" .. maxEn)
  257. insertMsg("Свободно: " .. memFree .. "Байт, Занято: " .. mem - memFree .. "Байт, Всего: " .. mem)
  258. end
  259.  
  260. --[[END]]--
  261.  
  262. local function checkCommand(potCom)
  263. local isCom = false
  264. if potCom:sub(1,1) == "/" then
  265. isCom = true
  266. end
  267. return isCom
  268. end
  269.  
  270. local function getInfo() end -- For further declaration...
  271.  
  272. local function issueCommand(sender, command, args)
  273. local allowed = false
  274. log("["..sender.."] Команда: " .. command)
  275. _, _, rank = getInfo(sender)
  276. if cmds[command] then
  277. if rank >= cmds[command].rank then
  278. insertMsg("["..sender.."]: /" .. command)
  279. cmds[command].func(args, sender)
  280. end
  281. end
  282. end
  283.  
  284. function getInfo(usr)
  285. local prefix, suffix, rank, info
  286. if user[usr] then
  287. info = group[user[usr]]
  288. else
  289. info = group["default"]
  290. end
  291. prefix = info["prefix"]
  292. suffix = info["suffix"]
  293. rank = info["rank"]
  294. return prefix, suffix, rank
  295. end
  296.  
  297. local function onReceive(sender, msg)
  298. if not muted[sender] then
  299. if not checkCommand(msg) then
  300. local prefix, suffix, _ = getInfo(sender)
  301. insertMsg( prefix .. sender .. ": " .. msg .. suffix)
  302. else
  303. local args = {}
  304. for i in msg:gmatch("%s(%S+)") do
  305. table.insert(args, i)
  306. end
  307. local command = msg:match("%w+")
  308. issueCommand(sender, command, args)
  309. end
  310. updateChat()
  311. end
  312. end
  313.  
  314. local function modemMsg(sender, port, dist, name, msg)
  315. print(sender, port, dist, name, msg)
  316. if name:sub(1, 1) == "!" then
  317. print("Альтернативное сообщение: " .. name)
  318. name, msg = name:match("!(w+):(.+)")
  319. end
  320. if name and msg then
  321. msg = unicode.sub(msg, 1, MAX_LEN)
  322. local allowedPort = false
  323. local allowedIP = false
  324. for i = 1, #PORTS, 1 do
  325. if PORTS[i][1] == port and PORTS[i][2] == true then
  326. allowedPort = true
  327. allowedIP = true
  328. elseif PORTS[i][1] == port and PORTS[i][2] == false then
  329. allowedPort = true
  330. end
  331. end
  332. for i = 1, #ALLOWED, 1 do
  333. if sender:match(ALLOWED[i]) then
  334. allowedIP = true
  335. end
  336. end
  337. if allowedPort and allowedIP then
  338. onReceive("[NET]" .. name, msg)
  339. end
  340. end
  341. end
  342.  
  343. local i = 1
  344. if MOTD then
  345. if fs.exists("/etc/chatserver.motd") then
  346. local file = io.open("/etc/chatserver.motd", "r")
  347. while true do
  348. local curLine = file:read()
  349. if not curLine then break end
  350. insertMsg(curLine)
  351. end
  352. file:close()
  353. updateChat()
  354. else
  355. local file = io.open("/etc/chatserver.motd", "w")
  356. file:write("")
  357. file:flush()
  358. file:close()
  359. end
  360. end
  361. while noexit do
  362. local event, _, sender, uuid, msg, modem_name, modem_msg = event.pull(1)
  363. if event == "modem_message" then
  364. if modem_name ~= nil and modem_name ~= "" then
  365. modemMsg(sender, uuid, msg, modem_name, modem_msg)
  366. end
  367. elseif event == "glasses_chat_command" then
  368. if msg ~= nil and msg ~= "" then
  369. msg = unicode.sub(msg, 1, MAX_LEN)
  370. onReceive(sender, msg)
  371. end
  372. elseif event == "glasses_attach" then
  373. insertMsg("Игрок \"" .. sender .. "\" присоединился к серверу сообщений!")
  374. updateChat()
  375. elseif event == "glasses_detach" then
  376. insertMsg("Игрок \"" .. sender .. "\" покинул сервер сообщений")
  377. updateChat()
  378. end
  379. if i == LIFETIME then
  380. if chat[math.floor(MAX_MSG / 2) + 1] then
  381. print("Очистка...")
  382. table.remove(chat, 1)
  383. i = 0
  384. updateChat()
  385. else
  386. i = 0
  387. end
  388. logFile:flush()
  389. end
  390. i = i + 1
  391. end
  392.  
  393. bridge.clear()
  394. bridge.sync()
  395. logFile:close()
  396. for i = 1, #PORTS, 1 do
  397. modem.close(PORTS[i][1])
  398. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement