Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local component = require("component")
- local term = require("term")
- local shell = require("shell")
- local fs = require("filesystem")
- local computer = require("computer")
- local chat = component.chat_box
- local internet = require('internet')
- local event = require('event')
- _G.imodem = {}
- local server = 'irc.esper.net:6667'
- local nick = "Message"
- imodem.channel = "#message"
- local on_exit = 1
- local con = 1
- local ex = require("term")
- cloak = "выключена"
- local rad = component.radar
- pl = rad.getPlayers()
- local online = computer.addUser
- local gpu = component.gpu
- local c = require('serialization')
- local players = {}
- local det = computer.addUser
- local roc = component.tile_defense_machine_launcherscreen_name
- function check(pmsg)
- while true do
- mssg = {}
- local find = string.find(pmsg," ")
- local i = 1
- while true do --сканим все фуфло
- if find == nil then
- mssg[i] = pmsg
- print("конец текста")
- comm()
- break
- else
- mssg[i] = string.sub(pmsg,1,find-1)
- pmsg = string.sub(pmsg,find+1)
- find = string.find(pmsg," ")
- i = i+1
- --print("финды "..find)
- --print("текст "..mssg[i])
- --print("остаток "..pmsg)
- end
- end
- break
- --print(comm)
- end
- os.sleep(1)
- end
- function comm()
- if mssg[1] == "!rtarget" then
- if mssg[2] == "жива?" then
- chat.say("Да")
- else
- local x = mssg[2]
- local y = mssg[3]
- local z = mssg[4]
- local x = tonumber(x)
- local y = tonumber(y)
- local z = tonumber(z)
- roc.setTarget(x, y, z)
- end
- end
- end
- function AddManually(rply)--ручное добавление ника в базу
- AddPlayerToBD(rply)
- end
- function detectOnline()--тут проверяем онлайн. Если игрок таки онлайн - отправляем через туннельную карту его ник
- non = 0
- for j = 1, #players do
- names=players[j]
- prov=det(names)
- if prov ~= nil then imodem.broadcast("Игрок: "..names.." ONL") non = non + 1 end--тут отправляем ник
- if names == "Domenk" then
- iws = 1
- else
- computer.removeUser(names)
- end
- end
- imodem.broadcast("Общий онлайн: "..non..".")
- end
- function readBD()--чтение базы данных в массив (один раз, при запуске программы. В дальнейшем работаем с массивом)
- local d=1
- local f = io.open("Players.txt","r")
- f:seek("set",0);
- for line in f:lines() do
- players[d]=line
- d=d+1
- end
- f:close()
- end
- function AddPlayerToBD(addply)--проверка ника и если его нет в базе данных - добавляем
- local flstr=2
- for j = 1, #players do
- if players[j]==addply then flstr=1 break end--игрок уже есть в БД, меняем переменную-флаг и прерываем цикл
- end
- if flstr == 2 then
- f = io.open("Players.txt","a");
- f:write(addply.."\n")
- --записали нового игрока в БД
- f:flush()
- f:close()
- --добавляем имя игрока в массив
- local mass = #players+1
- players[mass]=addply
- end
- end
- function name(identity)--не знаю для чего она :)
- return identity and identity:match('^[^!]+') or identity or 'Anonymous'
- end
- function chat_(nick,message)--чат
- check(message)
- if message == "!o"
- then
- detectOnline()
- else
- if message == "!help"
- then
- imodem.broadcast("Доступные команды:")
- imodem.broadcast("Онлайн сервера !o")
- imodem.broadcast("Невидимость корабля: !io ; !if")
- imodem.broadcast("Вся доступная информация: !status")
- else
- if message == "!status"
- then
- imodem.broadcast("Невидимость:" .. cloak .. ".")
- if pl[1] then
- imodem.broadcast("Игрок" .. pl[1]["name"] .. ".")
- if pl[2] then
- imodem.broadcast("Игрок" .. pl[2]["name"] .. ".")
- if pl[3] then
- imodem.broadcast("Игрок" .. pl[3]["name"] .. ".")
- if pl[4] then
- imodem.broadcast("Игрок" .. pl[4]["name"] .. ".")
- if pl[5] then
- imodem.broadcast("Игрок" .. pl[5]["name"] .. ".")
- end
- end
- end
- end
- end
- else
- if message == "!io"
- then
- component.tunnel.send("on")
- cloak = "Включена"
- imodem.broadcast("Невидимость корабля активирована.")
- else
- if message == "!if"
- then
- component.tunnel.send("off")
- cloak = "Выключена"
- imodem.broadcast("Невидимость корабля деактивирована.")
- else
- if message == "ня пока"
- then
- on_exit = 0
- imodem.stop()
- return
- else
- if nick == "DOMENK" then
- chat.setName(nick)
- term.clear()
- chat.say(message)
- print(message)
- else
- imodem.broadcast("Чужакам тут не место, уходи.")
- end
- end
- end
- end
- end
- end
- end
- end
- function imodem.broadcast(message)--функция отправки сообщений на IRC сервер
- if sock and imodem.channel then
- sock:write("PRIVMSG " .. imodem.channel .. " :" .. message..'\r\n')
- sock:flush()
- return true
- else
- con = 0
- connect(0)
- return false
- end
- end
- function imodem.stop()--отключение от IRC сервера
- if imodem.timer then
- if sock then
- sock:write('QUIT\r\n')
- sock:close()
- end
- event.cancel(imodem.timer)
- end
- end
- function connect(flag)--по сути главная функция. Отвечает за соединение с IRC сервером, за прием сообщений от него, за проверку и поддержание соединения
- if con == 0 and flag == 0 then
- sock, reason = internet.open(server)
- sock:setTimeout(0.05)
- sock:write('NICK '..nick..'\r\n')
- sock:write('USER '..nick..' 0 * :'..nick..'\r\n')
- sock:flush()
- if not sock then
- io.stderr:write(reason..'\n')
- return
- end
- end
- imodem.timer = event.timer(0.5, function()
- if not sock then return false end
- repeat
- ok, line = pcall(sock.read, sock)
- if ok then
- if not line then
- sock:close()
- sock = nil
- end
- match, prefix = line:match('^(:(%S+) )')
- if match then line = line:sub(#match+1) end
- local match, command = line:match('^(([^:]%S*))')
- if match then line = line:sub(#match+1) end
- args = {}
- repeat
- match, arg = line:match('^( ([^:]%S*))')
- if match then
- line = line:sub(#match+1)
- table.insert(args, arg)
- end
- until not match
- local message = line:match('^ :(.*)$')
- term.clear()
- print (command)
- if command == '004' then
- sock:write('JOIN '..imodem.channel..' nbgjhjvbr'..'\r\n')
- sock:flush()
- con = 1
- elseif command == 'PING' then
- sock:write('PONG :'..message..'\r\n')
- sock:flush()
- elseif command == 'PRIVMSG' then
- computer.pushSignal('modem_message', nick, name(prefix), 0, 0, message)
- print(message)--именно здесь принимаются сообщения от IRC!!
- --function(message) Вот так сюда можно вставить функцию, которая будет принимать и обрабатывать сообщение (message) от IRC
- chat_(name(prefix), message)
- end
- end
- until not ok
- end, math.huge)
- end
- function sendsms (player, message)--обработка сообщения от чата или других событий в игре и пересылка его в функцию отправки на IRC сервер
- if player ~= "Ашшарх" and player ~= "Гросс" and player ~= "Евпсихий" and player ~= "Прашнартра" and player ~= "Киппс" and player ~= "Джейк Риденс" and player ~= "Пришелец" and player ~= "ИнопланеТЯНКА" then
- AddPlayerToBD(player)
- check(message)
- imodem.broadcast(player..": "..message)
- --term.clear()
- print(message)
- end
- end
- --++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- connect(0)
- readBD()
- while on_exit == 1 do--главный цикл. И этим все сказано.
- local e = { computer.pullSignal(2) }
- if not sock and con == 1 then
- con = 0
- event.push ("soedinit")
- connect(0)
- end
- if e[1] == "modem_message" then
- if e[10] == "RLO" then--пример того, как можно принять управляющий флаг от тоннельной карты
- imodem.broadcast(e[9])-- и передать некое сообщение находяшееся в поле e[9] в IRC
- end
- elseif e[1] == "chat_message" then
- sendsms(e[3], e[4])
- elseif e[1] == "key_down" then --дальше идут клавиши управления. Выключение проги или же просто дисконнект IRC
- if e[4] == 16 then --выход из проги
- term.clear()
- on_exit = 0
- elseif e[4] == 24 then--дисконнект
- imodem.stop()
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement