Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local component = require("component")
- local computer = require("computer")
- local term = require("term")
- local event = require("event")
- local chat = component.chat_box
- local gpu = component.gpu
- local con = component.me_controller
- local serialization = require("serialization")
- local unicode = require("unicode")
- local shell = require("shell")
- local os = require("os")
- chat.setName("L")
- masters = {
- ["AlexSavex"] = "AlexSavex",
- ["Dima0299"] = "Dima0299",
- ["SoriBro"] = "SoriBro",
- }
- craftables = {}
- recentCraft = nil
- function say(msg)
- chat.say("§bМЭ§a Ассистент§7: " .. msg)
- end
- function getNumber(item)
- local a = con.getItemsInNetwork()
- for i = 1,#a do
- if isEqual(a[i].label,item) then
- return a[i].size, a[i].label
- end
- end
- return "error no such item"
- end
- function displayNumber(item)
- local num,label = getNumber(item)
- if num and label then
- say("в царской сокровищнице §d" .. num .. " §9" .. label .. "§7, " .. masters[name])
- end
- end
- function displayNumber3(item)
- if item == "" or string.len(item) <= 1 then
- return true
- end
- local a = con.getItemsInNetwork()
- for i = 1,#a do
- if isEqual(a[i].label,item) then
- say("в царской сокровищнице §d" .. a[i].size .. " §9" .. a[i].label .. "§7, " .. masters[name])
- return true
- end
- end
- local results = {}
- for i = 1,#a do
- if string.find(string.lower(a[i].label),string.lower(item)) then
- results[a[i].label] = a[i].size
- end
- end
- for k,v in pairs(results) do
- say("§9" .. k .. "§7: §d" .. v)
- end
- end
- function displayNumber2(item)
- if item == "" or string.len(item) <= 1 then
- return true
- end
- local a = con.getItemsInNetwork()
- local line = ""
- local line0 = ""
- local lineF = ""
- local skip = 0
- for i = 1,#a do
- if isEqual(a[i].label,item) then
- line0 = "§9" .. a[i].label .. "§7: §d" .. a[i].size
- skip = i
- break
- end
- end
- for i = 1,#a do
- if i ~= skip then
- if string.find(string.lower(a[i].label),string.lower(item)) then
- line = line .. "§9" .. a[i].label .. "§7: §d" .. a[i].size .. "§7, "
- end
- end
- end
- if line ~= "" then
- line = string.sub(line,0,-3)
- if string.len(line) > 1000 then
- line = "слишком много результатов"
- end
- end
- if line0 ~= "" then
- lineF = line0 .. "§7, " .. line
- else
- lineF = line
- end
- if lineF ~= ", " and lineF ~= "" then
- say(lineF)
- end
- end
- function isEqual(item1,item2)
- if string.lower(item1) == string.lower(item2) then
- return true
- else
- return false
- end
- end
- function assignPBS(msg)
- if string.find(msg,"=") ~= nil then
- prefix = string.sub(msg,1,string.find(msg,"=")-1)
- if string.find(msg,":") ~= nil then
- body = string.sub(msg,string.find(msg,"=")+1,string.find(msg,":")-1)
- suffix = string.sub(msg,string.find(msg,":")+1)
- if suffix == ""
- then suffix = nil
- end
- else
- body = string.sub(msg,string.find(msg,"=")+1)
- end
- else
- prefix,body,suffix = nil,nil,nil
- end
- return prefix, body, suffix
- end
- function isDone()
- if recentCraft == nil then
- say("ты еще не заказывал крафтов")
- return true
- end
- if recentCraft.isCanceled() == true then
- say("последний крафт был отменен")
- return true
- end
- if recentCraft.isDone() == true then
- say("последний крафт уже завершен")
- else
- say("последний крафт еще в прогрессе")
- end
- end
- function recalculateCraftables()
- say("пересчет таблицы крафтов . . .")
- local t = con.getCraftables()
- for i = 1,#t do
- craftables[i] = t[i].getItemStack().label
- end
- local f,err = io.open("craftables","w")
- if err then
- say("не могу открыть файл дампа таблицы, таблица не будет записана")
- return true
- end
- f:write(serialization.serialize(craftables))
- f:close()
- say("таблица крафтов обновлена")
- end
- function longCraft(item,number)
- local ttt = con.getCraftables()
- for i = 1,#ttt do
- if isEqual(ttt[i].getItemStack().label,item) then
- recentCraft = ttt[i].request(number,true)
- os.sleep(0.2)
- if recentCraft.isCanceled() == false then
- say("-заказан крафт §9" .. item .. " §dx" .. number)
- else
- say("-ошибка, крафт отменен")
- end
- return true
- end
- end
- say("-нет крафтабельного рецепта для " .. item)
- end
- function pcraft(item,number)
- if type(item) ~= "string" or type(number) ~= "number" then
- say("неправильная команда для крафта")
- return true
- end
- local t = con.getCraftables()
- for i = 1,#craftables do
- if isEqual(craftables[i],item) then
- if isEqual(t[i].getItemStack().label,item) then
- recentCraft = t[i].request(number,true)
- os.sleep(0.2)
- if recentCraft.isCanceled() == false then
- say("заказан крафт §9" .. item .. " §dx" .. number)
- else
- say("ошибка, крафт отменен")
- end
- return true
- else
- longCraft(item,number)
- return true
- end
- end
- end
- longCraft(item,number)
- end
- function getKeys(table)
- local count = 0
- for k,v in pairs(table) do
- count = count +1
- end
- return count
- end
- function craft(item,number)
- if type(item) ~= "string" or type(number) ~= "number" then
- say("неправильная команда для крафта")
- return true
- end
- local t = con.getCraftables()
- for i = 1,#craftables do
- if isEqual(craftables[i],item) then
- if isEqual(t[i].getItemStack().label,item) then
- recentCraft = t[i].request(number,true)
- os.sleep(0.2)
- if recentCraft.isCanceled() == false then
- say("заказан крафт §9" .. item .. " §dx" .. number)
- else
- say("ошибка, крафт отменен")
- end
- return true
- end
- end
- end
- local res = {}
- for i = 1,#craftables do
- if string.find(string.lower(craftables[i]),string.lower(item)) then
- print(craftables[i])
- res[i] = craftables[i]
- end
- end
- if getKeys(res) == 1 then
- for i,v in pairs(res) do
- if isEqual(res[i],t[i].getItemStack().label) then
- recentCraft = t[i].request(number,true)
- os.sleep(0.2)
- if recentCraft.isCanceled() == false then
- say("+заказан крафт §9" .. res[i] .. " §dx" .. number)
- else
- say("+ошибка, крафт отменен")
- end
- return true
- else
- say("+проблема с таблицами крафта, рекомендовано пересчитать")
- end
- end
- elseif getKeys(res) == 0 then
- say("нет результатов для " .. item)
- return true
- else
- say("найдено §9" .. getKeys(res) .. "§7 результатов, уточни запрос")
- return true
- end
- say("нет крафтабельного рецепта для " .. item)
- end
- function checkCraftables()
- say("проверка таблиц крафта . . .")
- if not craftables then
- say("файл таблиц craftables поврежден, обнуление. необходимо пересчитать таблицы")
- craftables = {}
- return true
- end
- if #craftables ~= #con.getCraftables() then
- say("таблицы крафтов не совпадают по размеру " .. #craftables .. " - " .. #con.getCraftables())
- return true
- end
- local tt = con.getCraftables()
- for i = 1,#craftables do
- if craftables[i] ~= tt[i].getItemStack().label then
- say("таблицы крафтов не совпадают по содержанию")
- return true
- end
- end
- say("таблицы крафтов совпадают")
- end
- function cpu()
- local busy = 0
- local free = 0
- local t = con.getCraftingCPUs()
- for i = 1,#t do
- if t[i].busy == true then
- busy = busy +1
- else
- free = free +1
- end
- end
- say("статус процессоров: §a" .. free .. "§7/§c" .. busy)
- end
- function loadCraftables()
- local f,err = io.open("craftables","r")
- if err then
- say("не могу открыть файл дампа таблицы для чтения")
- return true
- end
- craftables = serialization.unserialize(f:read())
- f:close()
- say("таблица крафтов инициализирована")
- end
- function paste(text1,text2,text3,text4)
- local len = 10-(unicode.len(text1))
- if len > 0 then
- io.write(string.rep(" ",len))
- end
- gpu.setForeground(0x00D60D)
- io.write(text1)
- gpu.setForeground(0xF8C471)
- io.write(text2)
- gpu.setForeground(0xA747F3)
- io.write(text3)
- gpu.setForeground(0xF8F9F9)
- io.write(" - " .. text4 .. "\n")
- gpu.setForeground(0xFFFFFF)
- end
- function memoryUsed()
- say("занято оперативной памяти: " .. math.floor((computer.totalMemory()-computer.freeMemory())/1024) .. "KB")
- end
- function scan(pname)
- local line = ""
- if component.openperipheral_sensor.getPlayerByName(pname) then
- local a = component.openperipheral_sensor.getPlayerByName(pname).all()
- say("сканирую §9" .. a.name .. "§7 . . .")
- say("хп: §9" .. a.living.health .. "/" .. a.living.maxHealth)
- say("опыт: §9" .. a.player.experience.level .. "§7 ур. (" .. math.floor(a.player.experience.levelProgress*100) .. "%)")
- say("насыщение: §9" .. a.player.foodLevel)
- say("взгляд: направление: §9" .. math.floor(a.living.yaw) .. "°§7, угол: §9" .. math.floor(a.living.pitch) .. "°")
- if a.player.isCreativeMode == true then
- say("у этого пидора §4бескнечные ресы, бля")
- end
- line = line .. "зелья: §9"
- if a.living.potion_effects then
- p=a.living.potion_effects
- if #p ~= 0 then
- for i=1,#p do
- line = line .. "§9" .. p[i].effect.name .. "§7 - §9" .. p[i].duration .. "§7 сек, "
- end
- line = string.sub(line,0,-2)
- else line = "зелья: §9нет"
- end
- end
- say(line)
- else
- say("не вижу " .. pname)
- end
- end
- function iscan(pname)
- local line = ""
- local a = ""
- if component.openperipheral_sensor.getPlayerByName(pname) then
- a = component.openperipheral_sensor.getPlayerByName(pname).all()
- a = a.player.inventory
- end
- say("§dБроня:")
- for i = 40,37,-1 do
- if a[i] then
- local x = a[i].all()
- line = " §9" .. x.display_name
- if x.electric then
- line = line .. "§7 (" .. math.floor((x.electric.charge/x.electric.maxCharge)*100) .. "%)"
- end
- say(line)
- else
- say(" -- ")
- end
- end
- say("§dПанель быстрого доступа:")
- for i = 1,9 do
- if a[i] then
- local x = a[i].all()
- line = " §9" .. x.display_name .. "§7: " .. x.qty
- if x.electric then
- line = line .. "§7 (" .. math.floor((x.electric.charge/x.electric.maxCharge)*100) .. "%)"
- end
- say(line)
- end
- end
- say("§dИнвентарь:")
- for i = 10,36 do
- if a[i] then
- local x = a[i].all()
- line = " §9" .. x.display_name .. "§7: " .. x.qty
- if x.electric then
- line = line .. " заряд: " .. (x.electric.Charge/x.electric.macCharge)*100 .. "%"
- end
- say(line)
- end
- end
- end
- --[[function shellExec()
- shell.execute("pastebin get -f Dt0kbk77 assistant.lua")
- shell.execute("assistant.lua")
- end]]--
- function restart()
- if (nickname == "Astro") then
- say("рестарт . . .")
- timer = event.timer(3,shellExec)
- os.exit()
- end
- end
- function printCommands()
- paste("=","item","","кол-во предмета в сети (только точное название)")
- paste("d=","item","","кол-во предмета в сети (поиск по фильтру)")
- paste("dd=","item","","кол-во предмета в сети (поиск по фильтру) - результаты в столбик")
- paste("craft=","item",":number","заказ крафта по фильтру (можно писать часть названия)")
- paste("pcraft=","item",":number","старая ф-я крафта (длинный поиск по всем предметам, только точное название)")
- paste("status=","","","статус последнего заказа")
- paste("cpu=","","","статистика занятых и свободных CPU крафта")
- paste("recalc=","","","пересчитать таблицу крафта и записать в файл (полезно если меняется конфигурация шаблонов крафта в сети)")
- paste("reload=","","","инициализировать таблицу крафта из файла (необязательно, выполняется каждый раз при старте программы)")
- paste("check=","","","проверить, соответствует ли текущая таблица крафта в оперативной памяти реальным крафтам МЭ сети")
- paste("ram=","","","показать количество занятой оперативной памяти")
- --paste("restart=","","","обновить программу через pastebin и перезапустить")
- paste("scan=","player","","отсканировать пидрилу")
- paste("iscan=","player","","отсканировать его инвентарь")
- end
- commands = {
- [""] = displayNumber,
- ["craft"] = craft,
- ["pcraft"] = pcraft,
- ["status"] = isDone,
- ["check"] = checkCraftables,
- ["cpu"] = cpu,
- ["recalc"] = recalculateCraftables,
- ["reload"] = loadCraftables,
- ["d"] = displayNumber2,
- ["dd"] = displayNumber3,
- ["ram"] = memoryUsed,
- ["restart"] = restart,
- ["scan"] = scan,
- ["iscan"] = iscan,
- }
- --
- if timer then
- timer.kill(timer)
- end
- term.clear()
- loadCraftables()
- printCommands()
- local nickname = ""
- while true do
- _,_,name,msg = event.pull("chat_message")
- nickname=name
- if masters[name] then
- prefix,body,suffix = nil,nil,nil
- prefix,body,suffix = assignPBS(msg)
- if commands[prefix] then
- commands[prefix](body,tonumber(suffix))
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement