Advertisement
Guest User

Untitled

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