repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
vietlq/luasocket
src/http.lua
121
12193
----------------------------------------------------------------------------- -- HTTP/1.1 client support for the Lua language. -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: http.lua,v 1.71 2007/10/13 23:55:20 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ------------------------------------------------------------------------------- local socket = require("socket") local url = require("socket.url") local ltn12 = require("ltn12") local mime = require("mime") local string = require("string") local base = _G local table = require("table") module("socket.http") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- connection timeout in seconds TIMEOUT = 60 -- default port for document retrieval PORT = 80 -- user agent field sent in request USERAGENT = socket._VERSION ----------------------------------------------------------------------------- -- Reads MIME headers from a connection, unfolding where needed ----------------------------------------------------------------------------- local function receiveheaders(sock, headers) local line, name, value, err headers = headers or {} -- get first line line, err = sock:receive() if err then return nil, err end -- headers go until a blank line is found while line ~= "" do -- get field-name and value name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)")) if not (name and value) then return nil, "malformed reponse headers" end name = string.lower(name) -- get next line (value might be folded) line, err = sock:receive() if err then return nil, err end -- unfold any folded values while string.find(line, "^%s") do value = value .. line line = sock:receive() if err then return nil, err end end -- save pair in table if headers[name] then headers[name] = headers[name] .. ", " .. value else headers[name] = value end end return headers end ----------------------------------------------------------------------------- -- Extra sources and sinks ----------------------------------------------------------------------------- socket.sourcet["http-chunked"] = function(sock, headers) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() -- get chunk size, skip extention local line, err = sock:receive() if err then return nil, err end local size = base.tonumber(string.gsub(line, ";.*", ""), 16) if not size then return nil, "invalid chunk size" end -- was it the last chunk? if size > 0 then -- if not, get chunk and skip terminating CRLF local chunk, err, part = sock:receive(size) if chunk then sock:receive() end return chunk, err else -- if it was, read trailers into headers table headers, err = receiveheaders(sock, headers) if not headers then return nil, err end end end }) end socket.sinkt["http-chunked"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if not chunk then return sock:send("0\r\n\r\n") end local size = string.format("%X\r\n", string.len(chunk)) return sock:send(size .. chunk .. "\r\n") end }) end ----------------------------------------------------------------------------- -- Low level HTTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function open(host, port, create) -- create socket with user connect function, or with default local c = socket.try((create or socket.tcp)()) local h = base.setmetatable({ c = c }, metat) -- create finalized try h.try = socket.newtry(function() h:close() end) -- set timeout before connecting h.try(c:settimeout(TIMEOUT)) h.try(c:connect(host, port or PORT)) -- here everything worked return h end function metat.__index:sendrequestline(method, uri) local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri) return self.try(self.c:send(reqline)) end function metat.__index:sendheaders(headers) local h = "\r\n" for i, v in base.pairs(headers) do h = i .. ": " .. v .. "\r\n" .. h end self.try(self.c:send(h)) return 1 end function metat.__index:sendbody(headers, source, step) source = source or ltn12.source.empty() step = step or ltn12.pump.step -- if we don't know the size in advance, send chunked and hope for the best local mode = "http-chunked" if headers["content-length"] then mode = "keep-open" end return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step)) end function metat.__index:receivestatusline() local status = self.try(self.c:receive(5)) -- identify HTTP/0.9 responses, which do not contain a status line -- this is just a heuristic, but is what the RFC recommends if status ~= "HTTP/" then return nil, status end -- otherwise proceed reading a status line status = self.try(self.c:receive("*l", status)) local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)")) return self.try(base.tonumber(code), status) end function metat.__index:receiveheaders() return self.try(receiveheaders(self.c)) end function metat.__index:receivebody(headers, sink, step) sink = sink or ltn12.sink.null() step = step or ltn12.pump.step local length = base.tonumber(headers["content-length"]) local t = headers["transfer-encoding"] -- shortcut local mode = "default" -- connection close if t and t ~= "identity" then mode = "http-chunked" elseif base.tonumber(headers["content-length"]) then mode = "by-length" end return self.try(ltn12.pump.all(socket.source(mode, self.c, length), sink, step)) end function metat.__index:receive09body(status, sink, step) local source = ltn12.source.rewind(socket.source("until-closed", self.c)) source(status) return self.try(ltn12.pump.all(source, sink, step)) end function metat.__index:close() return self.c:close() end ----------------------------------------------------------------------------- -- High level HTTP API ----------------------------------------------------------------------------- local function adjusturi(reqt) local u = reqt -- if there is a proxy, we need the full url. otherwise, just a part. if not reqt.proxy and not PROXY then u = { path = socket.try(reqt.path, "invalid path 'nil'"), params = reqt.params, query = reqt.query, fragment = reqt.fragment } end return url.build(u) end local function adjustproxy(reqt) local proxy = reqt.proxy or PROXY if proxy then proxy = url.parse(proxy) return proxy.host, proxy.port or 3128 else return reqt.host, reqt.port end end local function adjustheaders(reqt) -- default headers local lower = { ["user-agent"] = USERAGENT, ["host"] = reqt.host, ["connection"] = "close, TE", ["te"] = "trailers" } -- if we have authentication information, pass it along if reqt.user and reqt.password then lower["authorization"] = "Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password)) end -- override with user headers for i,v in base.pairs(reqt.headers or lower) do lower[string.lower(i)] = v end return lower end -- default url parts local default = { host = "", port = PORT, path ="/", scheme = "http" } local function adjustrequest(reqt) -- parse url if provided local nreqt = reqt.url and url.parse(reqt.url, default) or {} -- explicit components override url for i,v in base.pairs(reqt) do nreqt[i] = v end if nreqt.port == "" then nreqt.port = 80 end socket.try(nreqt.host and nreqt.host ~= "", "invalid host '" .. base.tostring(nreqt.host) .. "'") -- compute uri if user hasn't overriden nreqt.uri = reqt.uri or adjusturi(nreqt) -- ajust host and port if there is a proxy nreqt.host, nreqt.port = adjustproxy(nreqt) -- adjust headers in request nreqt.headers = adjustheaders(nreqt) return nreqt end local function shouldredirect(reqt, code, headers) return headers.location and string.gsub(headers.location, "%s", "") ~= "" and (reqt.redirect ~= false) and (code == 301 or code == 302) and (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD") and (not reqt.nredirects or reqt.nredirects < 5) end local function shouldreceivebody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end -- forward declarations local trequest, tredirect function tredirect(reqt, location) local result, code, headers, status = trequest { -- the RFC says the redirect URL has to be absolute, but some -- servers do not respect that url = url.absolute(reqt.url, location), source = reqt.source, sink = reqt.sink, headers = reqt.headers, proxy = reqt.proxy, nredirects = (reqt.nredirects or 0) + 1, create = reqt.create } -- pass location header back as a hint we redirected headers = headers or {} headers.location = headers.location or location return result, code, headers, status end function trequest(reqt) -- we loop until we get what we want, or -- until we are sure there is no way to get it local nreqt = adjustrequest(reqt) local h = open(nreqt.host, nreqt.port, nreqt.create) -- send request line and headers h:sendrequestline(nreqt.method, nreqt.uri) h:sendheaders(nreqt.headers) -- if there is a body, send it if nreqt.source then h:sendbody(nreqt.headers, nreqt.source, nreqt.step) end local code, status = h:receivestatusline() -- if it is an HTTP/0.9 server, simply get the body and we are done if not code then h:receive09body(status, nreqt.sink, nreqt.step) return 1, 200 end local headers -- ignore any 100-continue messages while code == 100 do headers = h:receiveheaders() code, status = h:receivestatusline() end headers = h:receiveheaders() -- at this point we should have a honest reply from the server -- we can't redirect if we already used the source, so we report the error if shouldredirect(nreqt, code, headers) and not nreqt.source then h:close() return tredirect(reqt, headers.location) end -- here we are finally done if shouldreceivebody(nreqt, code) then h:receivebody(headers, nreqt.sink, nreqt.step) end h:close() return 1, code, headers, status end local function srequest(u, b) local t = {} local reqt = { url = u, sink = ltn12.sink.table(t) } if b then reqt.source = ltn12.source.string(b) reqt.headers = { ["content-length"] = string.len(b), ["content-type"] = "application/x-www-form-urlencoded" } reqt.method = "POST" end local code, headers, status = socket.skip(1, trequest(reqt)) return table.concat(t), code, headers, status end request = socket.protect(function(reqt, body) if base.type(reqt) == "string" then return srequest(reqt, body) else return trequest(reqt) end end)
mit
FFXIOrgins/FFXIOrgins
scripts/globals/items/plate_of_patlican_salata.lua
35
1211
----------------------------------------- -- ID: 5582 -- Item: plate_of_patlican_salata -- Food Effect: 180Min, All Races ----------------------------------------- -- Agility 4 -- Vitality -1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5582); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 4); target:addMod(MOD_VIT, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 4); target:delMod(MOD_VIT, -1); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Port_Windurst/npcs/Kohlo-Lakolo.lua
36
10182
----------------------------------- -- Area: Port Windurst -- NPC: Kohlo-Lakolo -- Invloved In Quests: Truth, Justice, and the Onion Way!, -- Know One's Onions, -- Inspector's Gadget, -- Onion Rings, -- Crying Over Onions, -- Wild Card, -- The Promise ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS); if (KnowOnesOnions == QUEST_ACCEPTED) then count = trade:getItemCount(); WildOnion = trade:hasItemQty(4387,4); if (WildOnion == true and count == 4) then player:startEvent(0x018e,0,4387); end elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then count = trade:getItemCount(); RarabTail = trade:hasItemQty(4444,1); if (RarabTail == true and count == 1) then player:startEvent(0x017a,0,4444); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS); InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET); OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS); CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS); WildCard = player:getQuestStatus(WINDURST,WILD_CARD); ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE); NeedToZone = player:needToZone(); Level = player:getMainLvl(); Fame = player:getFameLevel(WINDURST); if (ThePromise == QUEST_COMPLETED) then player:startEvent(0x0220); elseif (ThePromise == QUEST_ACCEPTED) then InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER); if (InvisibleManSticker == true) then ThePromiseCS_Seen = player:getVar("ThePromiseCS_Seen"); if (ThePromiseCS_Seen == 1) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,THE_PROMISE); player:addFame(WINDURST,WIN_FAME*150); player:delKeyItem(INVISIBLE_MAN_STICKER); player:addItem(13135); player:messageSpecial(ITEM_OBTAINED,13135); player:setVar("ThePromise",0); player:setVar("ThePromiseCS_Seen",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135); end else player:startEvent(0x020a,0,INVISIBLE_MAN_STICKER); end else player:startEvent(0x0202); end elseif (WildCard == QUEST_COMPLETED) then player:startEvent(0x0201,0,INVISIBLE_MAN_STICKER); elseif (WildCard == QUEST_ACCEPTED) then WildCardVar = player:getVar("WildCard"); if (WildCardVar == 0) then player:setVar("WildCard",1); end player:showText(npc,KOHLO_LAKOLO_DIALOG_A); elseif (CryingOverOnions == QUEST_COMPLETED) then player:startEvent(0x01f9); elseif (CryingOverOnions == QUEST_ACCEPTED) then CryingOverOnionsVar = player:getVar("CryingOverOnions"); if (CryingOverOnionsVar == 3) then player:startEvent(0x0200); elseif (CryingOverOnionsVar == 2) then player:startEvent(0x01f1); else player:startEvent(0x01f2); end elseif (OnionRings == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 5) then player:startEvent(0x01f0); else player:startEvent(0x01b8); end elseif (OnionRings == QUEST_ACCEPTED) then OldRing = player:hasKeyItem(OLD_RING); if (OldRing == true) then OnionRingsTime = player:getVar("OnionRingsTime"); CurrentTime = os.time(); if (CurrentTime >= OnionRingsTime) then player:startEvent(0x01b1); else player:startEvent(0x01af); end end elseif (InspectorsGadget == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 3) then OldRing = player:hasKeyItem(OLD_RING); if (OldRing == true) then OnionRingsVar = player:getVar("OnionRings"); if (OnionRingsVar == 1) then player:startEvent(0x01ae,0,OLD_RING); else player:startEvent(0x01b0,0,OLD_RING); end else player:startEvent(0x01ad); end else player:startEvent(0x01a6); end elseif (InspectorsGadget == QUEST_ACCEPTED) then FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE); if (FakeMoustache == true) then player:startEvent(0x01a5); else player:startEvent(0x019e); end elseif (KnowOnesOnions == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 2) then player:startEvent(0x019d); else player:startEvent(0x0191); end elseif (KnowOnesOnions == QUEST_ACCEPTED) then KnowOnesOnionsVar = player:getVar("KnowOnesOnions"); KnowOnesOnionsTime = player:getVar("KnowOnesOnionsTime"); CurrentTime = os.time(); if (KnowOnesOnionsVar == 2) then player:startEvent(0x0190); elseif (KnowOnesOnionsVar == 1 and CurrentTime >= KnowOnesOnionsTime) then player:startEvent(0x0182); elseif (KnowOnesOnionsVar == 1) then player:startEvent(0x018f,0,4387); else player:startEvent(0x0188,0,4387); end elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then if (NeedToZone == false and Level >= 5) then player:startEvent(0x0187,0,4387); else player:startEvent(0x017b); end elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then player:startEvent(0x0173); elseif (TruthJusticeOnionWay == QUEST_AVAILABLE) then player:startEvent(0x0170); else player:startEvent(0x0169); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0170 and option == 0) then player:addQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); elseif (csid == 0x017a) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); player:addFame(WINDURST,WIN_FAME*75); player:addTitle(STAR_ONION_BRIGADE_MEMBER); player:tradeComplete(); player:addItem(13093); player:messageSpecial(ITEM_OBTAINED,13093); player:needToZone(true); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,13093); end elseif (csid == 0x0187) then player:addQuest(WINDURST,KNOW_ONE_S_ONIONS); elseif (csid == 0x018e) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then TradeTime = os.time(); player:tradeComplete(); player:addItem(4857); player:messageSpecial(ITEM_OBTAINED,4857); player:setVar("KnowOnesOnions",1); player:setVar("KnowOnesOnionsTime", TradeTime + 86400); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,4857); end elseif (csid == 0x0182 or csid == 0x0190) then player:completeQuest(WINDURST,KNOW_ONE_S_ONIONS); player:addFame(WINDURST,WIN_FAME*80); player:addTitle(SOB_SUPER_HERO); player:setVar("KnowOnesOnions",0); player:setVar("KnowOnesOnionsTime",0); player:needToZone(true); elseif (csid == 0x019d and option == 0) then player:addQuest(WINDURST,INSPECTOR_S_GADGET); elseif (csid == 0x01a5) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,INSPECTOR_S_GADGET); player:addFame(WINDURST,WIN_FAME*90); player:addTitle(FAKEMOUSTACHED_INVESTIGATOR); player:addItem(13204); player:messageSpecial(ITEM_OBTAINED,13204); player:needToZone(true); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13204); end elseif (csid == 0x01ad) then player:setVar("OnionRings",1); elseif (csid == 0x01ae) then OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS); if (OnionRings == QUEST_AVAILABLE) then CurrentTime = os.time(); player:addQuest(WINDURST,ONION_RINGS); player:setVar("OnionRingsTime", CurrentTime + 86400); end elseif (csid == 0x01b0 or csid == 0x01b1) then player:completeQuest(WINDURST,ONION_RINGS); player:addFame(WINDURST,WIN_FAME*100); player:addTitle(STAR_ONION_BRIGADIER); player:delKeyItem(OLD_RING); player:setVar("OnionRingsTime",0); player:needToZone(true); elseif (csid == 0x01b8) then OnionRingsVar = player:getVar("OnionRings"); NeedToZone = player:getVar("NeedToZone"); if (OnionRingsVar == 2 and NeedToZone == 0) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:setVar("OnionRings",0); player:addItem(17029); player:messageSpecial(ITEM_OBTAINED,17029); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17029); end end elseif (csid == 0x01f0) then player:addQuest(WINDURST,CRYING_OVER_ONIONS); elseif (csid == 0x01f1) then player:setVar("CryingOverOnions",3); elseif (csid == 0x0201) then player:addQuest(WINDURST,THE_PROMISE); elseif (csid == 0x020a) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,THE_PROMISE); player:addFame(WINDURST,WIN_FAME*150); player:delKeyItem(INVISIBLE_MAN_STICKER); player:addItem(13135); player:messageSpecial(ITEM_OBTAINED,13135); player:setVar("ThePromise",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135); player:setVar("ThePromiseCS_Seen",1); end end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Upper_Jeuno/npcs/Souren.lua
20
2050
----------------------------------- -- Area: Upper Jeuno -- NPC: Souren -- Involved in Quests: Save the Clock Tower -- @zone 244 -- @pos -51 0 4 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then a = player:getVar("saveTheClockTowerNPCz1"); -- NPC Part1 if(a == 0 or (a ~= 16 and a ~= 17 and a ~= 18 and a ~= 20 and a ~= 24 and a ~= 19 and a ~= 28 and a ~= 21 and a ~= 26 and a ~= 22 and a ~= 25 and a ~= 23 and a ~= 27 and a ~= 29 and a ~= 30 and a ~= 31)) then player:startEvent(0x00b6,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getQuestStatus(JEUNO,SAVE_THE_CLOCK_TOWER) == QUEST_ACCEPTED) then player:startEvent(0x0078); elseif(player:getQuestStatus(JEUNO,SAVE_THE_CLOCK_TOWER) == QUEST_COMPLETED) then player:startEvent(0x00b5); else player:startEvent(0x0058); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x00b6) then player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1); player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 16); end end;
gpl-3.0
hb9cwp/snabbswitch
src/lib/ipc/shmem/mib.lua
14
8133
-- Subclass of ipc.shmem.shmem that handles data types from the SMIv2 -- specification. -- -- It defines the name space "MIB", which uses the default index -- format. By definition, the object names must be literal OIDs or -- textual object identifiers that can be directly translated into -- OIDs through a MIB (e.g. ".1.3.6.1.2.1.1.3" or "sysUpTime"). Names -- that do not comply to this requirement can be used upon agreement -- between the producer and consumer of an instance of this class. By -- convention, such names must be prefixed with the string'_X_'. The -- mib class itself treats the names as opaque objects. -- -- The intended consumer of this data is an SNMP agent or sub-agent -- (that necessarily runs on the same host) which is able to serve the -- sub-trees that cover all of the OIDs in the index to regular SNMP -- clients (e.g. monitoring stations). It is recommended that the -- OIDs do *not* include any indices for conceptual rows of the -- relevant MIB (this includes the ".0" instance id of scalar -- objects). The SNMP (sub-)agent should know the structure of the -- MIB and construct all indices itself. This may require the -- inclusion of non-MIB objects in the data file for MIBs whose -- specification does not include the index objects themselves (which -- represents an example of the situation where the consumer and -- producer will have to agree upon a naming convention beyond the -- regular name space). -- -- Usage of the numerical data types is straight forward. Octet -- strings are encoded as a sequence of a 2-byte length field (uint16) -- followed by the indicated number of bytes. The maximum length is -- fixed upon creation of the container of the string. The size of -- the object (as registered in the index file) is 2+n, where n is the -- maximum length of the octet string. This module does not make use -- of ASN.1 in any form :) -- module(..., package.seeall) local ffi = require("ffi") local bit = require("bit") local bor, band, lshift, rshift = bit.bor, bit.band, bit.lshift, bit.rshift local shmem = require("lib.ipc.shmem.shmem") local mib = subClass(shmem) mib._name = "MIB shared memory" mib._namespace = "MIB" mib._version = 1 local int32_t = ffi.typeof("int32_t") local uint32_t = ffi.typeof("uint32_t") local uint64_t = ffi.typeof("uint64_t") local octetstr_types = {} local function octetstr_t (length) assert(length <= 65535) if octetstr_types[length] then return octetstr_types[length] else local type = ffi.typeof( [[ struct { uint16_t length; uint8_t data[$]; } __attribute__((packed)) ]], length) octetstr_types[length] = type return type end end -- Base types including the BITS construct according to the SMIv2, RFC -- 2578 (Section 7.1) and their mapping onto the ctypes used to store -- them in the context of the shmem system. The default 'OctetStr' -- supports octet strings up to 255 bytes. local types = { Integer32 = int32_t, Unsigned32 = uint32_t, OctetStr = octetstr_t(255), Counter32 = uint32_t, Counter64 = uint64_t, Gauge32 = uint32_t, TimeTicks = uint32_t, Bits = octetstr_t(16), } -- The 'type' argument of the constructor must either be a string that -- identifies one of the supported types -- -- Integer32 -- Unsigned32 -- OctetStr -- Counter32 -- Counter64 -- Gauge32 -- TimeTicks -- Bits -- -- or a table of the form { type = 'OctetStr', length = <length> }, -- where <length> is an integer in the range 0..65535. The simple -- type 'OctetStr' is equivalent to the extended OctetStr type with -- length=255. An OctetStr can hold any sequence of bytes up to a -- length of <length>. The sequence is passed as a Lua string to the -- register() and set() methods and received as such from the get() -- method. -- -- The Bits pseudo-type is mapped to an OctetStr of length 16. The -- SMIv2 specifies no maximum number of enumerable bits (except the -- one implied by the maximum size of an octet string, of course), but -- also notes that values in excess of 128 bits are likely to cause -- interoperability problems. This implementation uses a limit of 128 -- bits, i.e. the underlying OctetStr is of length 16. To keep things -- simple, all Bits object use the same size. Note that if no initial -- value is specified, the resulting octet string will have length -- zero. -- -- The "type" field of the table may also contain any of the other -- valid types. In this case, all other fields in the table are -- ignored and the method behaves as if the type had been passed as a -- string. function mib:register (name, type, value) assert(name and type) local ctype local smi_type = type if _G.type(type) == 'table' then assert(type.type) smi_type = type.type if type.type == 'OctetStr' then assert(type.length and type.length <= 65535) ctype = octetstr_t(type.length) else -- Accept all other legal types type = type.type end end ctype = ctype or types[type] if ctype == nil then error("illegal SMIv2 type "..type) end local ptr = mib:superClass().register(self, name, ctype) self._objs[name].smi_type = smi_type self:set(name, value) return ptr end -- Extension of the base set() method for objects of type OctetStr and -- Bits. -- -- For OctetStr, the value must be a Lua string, which will be -- stored in the "data" portion of the underlying octet string data -- type. The string is truncated to the maximum size of the object. -- -- For Bits, the value must be an array whose values specify which of -- the bits in the underlying OctetStr must be set to one according to -- the enumeration rule of the BITS construct as explained for the -- get() method. The length of the octet string is always set to 16 -- bytes for every set() operation. function mib:set (name, value) if value ~= nil then local obj = self._objs[name] if obj and obj.smi_type == 'OctetStr' then local length = math.min(string.len(value), obj.length - 2) local octet = mib:superClass().get(self, name) octet.length = length ffi.copy(octet.data, value, length) elseif obj and obj.smi_type == 'Bits' then local octet = mib:superClass().get(self, name) octet.length = 16 ffi.fill(octet.data, 16) local i = 1 while value[i] do local bit_n = value[i] local byte = rshift(bit_n, 3) octet.data[byte] = bor(octet.data[byte], lshift(1, 7-band(bit_n, 7))) i = i+1 end else mib:superClass().set(self, name, value) end end end -- Extension of the base get() method for objects of type OctetStr and -- Bits. -- -- For OctetStr, the returned value is the "data" portion of the -- underlying octet string, converted to a Lua string. -- -- For Bits, the returned value is an array that contains the numbers -- of the bits which are set in the underlying OctetStr according to -- the enumeration rules of the BITS construct, i.e. byte #0 is the -- first byte in the OctetStr and bit #0 in a byte is the leftmost bit -- etc. To avoid a table allocation, the caller may pass a table as -- the second argument, which will be filled with the result instead. function mib:get (name, ...) local octet = mib:superClass().get(self, name) local obj = self._objs[name] if obj.smi_type == 'OctetStr' then return ffi.string(octet.data, octet.length) elseif obj.smi_type == 'Bits' then local result = ... or {} local index = 1 for i = 0, 15 do local byte = octet.data[i] for j = 0, 7 do if band(byte, lshift(1, 7-j)) ~= 0 then result[index] = i*8+j index = index+1 end end end result[index] = nil return result else return octet end end return mib
apache-2.0
CAAP/ferre
ferre/updates.lua
2
1580
#!/usr/local/bin/lua local sql = require'carlos.sqlite' local fd = require'carlos.fold' local aux = require'ferre.aux' local hd = require'ferre.header' local ex = require'ferre.extras' local week = ex.week() local ups = {store='VERS', week='', vers=0} local QRY = 'SELECT * FROM updates %s' local function push(ret) local conn = assert( ex.dbconn( ups.week ), 'Failed connecting to DB: '..ups.week ) -- sql.connect(string.format('/db/%s.db', ups.week)) local clause = string.format('WHERE vers > %d', ups.vers) local function into(w) local clave = w.clave if not ret[clave] then ret[clave] = {clave=clave, store='PRICE'} end local z = ret[clave] z[w.campo] = w.valor or '' end if conn.count('updates', clause) > 0 then fd.reduce(conn.query(string.format(QRY, clause)), into) ups.vers = conn.count'updates' end end local function week2time( week ) local time = ex.now() local wk = ex.asweek( time ) while wk ~= week do time = time - 3600*24*7 wk = ex.asweek( time ) end return time end local function records(w) local ret = {ups} local time = week2time(w.oweek) -- ex.now() -- mx() ups.week = w.oweek; ups.vers = w.overs -- Initial values push( ret ) while ups.week ~= w.nweek do time = time + 3600*24*7 ups.week = ex.asweek( time ) --os.date('Y%YW%U', time) ups.vers = 0 push( ret ) end ret = fd.reduce(fd.keys( ret ), fd.map( hd.asJSON ), fd.into, {}) return string.format('Content-Type: text/plain; charset=utf-8\r\n\r\n[%s]\n', table.concat(ret, ', ')) end aux( records )
bsd-2-clause
FFXIOrgins/FFXIOrgins
scripts/globals/abilities/samurai_roll.lua
6
1417
----------------------------------- -- Ability: Choral Roll ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- OnUseAbility ----------------------------------- function OnAbilityCheck(player,target,ability) local effectID = getCorsairRollEffect(ability:getID()); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else return 0,0; end end; function OnUseAbilityRoll(caster, target, ability, total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {8, 32, 10, 12, 14, 4, 16, 20, 22, 24, 40, 5} local effectpower = effectpowers[total] if (total < 12 and caster:hasPartyJob(JOB_SAM) ) then effectpower = effectpower + 10; end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_SAMURAI_ROLL, effectpower, 0, duration, target:getID(), total, MOD_STORETP) == false) then ability:setMsg(423); end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/magic_maps.lua
8
4371
--------------------------------------------- -- -- Function that all map NPCS use. -- SE updated the map NPCs to sell maps from the normal areas, RoZ, and CoP areas (Update was in Nov 5, 2013) --------------------------------------------- require("scripts/globals/keyitems"); local Maps = {MAP_OF_THE_SAN_DORIA_AREA, MAP_OF_THE_BASTOK_AREA, MAP_OF_THE_WINDURST_AREA, MAP_OF_THE_JEUNO_AREA, MAP_OF_ORDELLES_CAVES, MAP_OF_GHELSBA, MAP_OF_DAVOI, MAP_OF_CARPENTERS_LANDING, MAP_OF_THE_ZERUHN_MINES, MAP_OF_THE_PALBOROUGH_MINES, MAP_OF_BEADEAUX, MAP_OF_GIDDEUS, MAP_OF_CASTLE_OZTROJA, MAP_OF_THE_MAZE_OF_SHAKHRAMI, MAP_OF_THE_LITELOR_REGION, MAP_OF_BIBIKI_BAY, MAP_OF_QUFIM_ISLAND, MAP_OF_THE_ELDIEME_NECROPOLIS, MAP_OF_THE_GARLAIGE_CITADEL, MAP_OF_THE_ELSHIMO_REGIONS, MAP_OF_THE_NORTHLANDS_AREA, MAP_OF_KING_RANPERRES_TOMB, MAP_OF_THE_DANGRUF_WADI, MAP_OF_THE_HORUTOTO_RUINS, MAP_OF_BOSTAUNIEUX_OUBLIETTE, MAP_OF_THE_TORAIMARAI_CANAL, MAP_OF_THE_GUSGEN_MINES, MAP_OF_THE_CRAWLERS_NEST, MAP_OF_THE_RANGUEMONT_PASS, MAP_OF_DELKFUTTS_TOWER, MAP_OF_FEIYIN, MAP_OF_CASTLE_ZVAHL}; local Uoption = { --User option selected. 1, --SanDoria Area 65537, --Bastok Area 131073, --Windurst Area 196609, --Jeuno Area 262145, --Ordelles Caves 327681, --Ghelsba 393217, --Davoi 458753, --Carpenters Landing 524289, --Zeruhn Mines 589825, --Palborough Mines 655361, --Beadeaux 720897, --Giddeus 786433, --Castle Oztroja 851969, --Maze of Shakhrami 917505, --Li'Telor Region 983041, --Bibiki Bay 1048577, --Qufim Island 1114113, --Eldieme Necropolis 1179649, --Garlaige Citadel 1245185, --Elshimo Regions 1310721, --Northlands Area 1376257, --King Ranperres Tomb 1441793, --Dangruf Wadi 1507329, --Horutoto Ruins 1572865, --Bostaunieux Oubliette 1638401, --Toraimarai Canal 1703937, --Gusgen Mines 1769473, --Crawlers Nest 1835009, --Ranguemont Pass 1900545, --Delkfutts Tower 1966081, --Feiyin 2031617 --Castle Zvahl }; --Groups maps by price, based off the user option. local p2 = { --Maps that are price at 200 gil Uoption[1], --SanDoria Area Uoption[2], --Bastok Area Uoption[3], --Windurst Area Uoption[9] --Zeruhn Mines }; local p6 = { --Maps that are price at 600 gil Uoption[4], --Jeuno Area Uoption[5], --Ordelles Caves Uoption[6], --Ghelsba Uoption[10], --Palborough Mines Uoption[11], --Beadeaux Uoption[12], --Giddeus Uoption[14], --Maze of Shakhrami Uoption[22], --King Ranperres Tomb Uoption[23], --Dangruf Wadi Uoption[24], --Horutoto Ruins Uoption[27] --Gusgen Mines }; local p3 = { --Maps that are price at 3000 gil Uoption[7], --Davoi Uoption[8], --Carpenters Landing Uoption[13], --Castle Oztroja Uoption[15], --Li'Telor Region Uoption[16], --Bibiki Bay Uoption[17], --Qufim Island Uoption[18], --Eldieme Necropolis Uoption[19], --Garlaige Citadel Uoption[20], --Elshimo Regions Uoption[21], --Northlands Area Uoption[25], --Bostaunieux Oubliette Uoption[26], --Toraimarai Canal Uoption[28], --Crawlers Nest Uoption[29], --Ranguemont Pass Uoption[30], --Delkfutts Tower Uoption[31], --Feiyin Uoption[32] --Castle Zvahl } function CheckMaps(player, npc, csid) local i = 0; local mapVar = 0; while i <= 31 do if player:hasKeyItem(Maps[i+1]) then mapVar = bit.bor(mapVar, bit.lshift(1,i)); end i = i + 1; end player:startEvent(csid, mapVar); end; function CheckMapsUpdate (player, option, NOT_HAVE_ENOUGH_GIL, KEYITEM_OBTAINED) local price = 0; local MadePurchase = false; local KI = 0; local i = 0; local mapVar = 0; while i <= 31 do if (option == Uoption[i+1]) then local x =1; while x <= 17 do if (x <= 4 and option == p2[x]) then price = 200; elseif (x <= 11 and option == p6[x]) then price = 600; elseif (x <= 17 and option == p3[x]) then price = 3000; end x=x+1; end MadePurchase = true; KI = Maps[i+1]; end i = i + 1; end if (price > player:getGil()) then player:messageSpecial(NOT_HAVE_ENOUGH_GIL); MadePurchase = false; price = 0; elseif (price > 0 and MadePurchase == true) then player:delGil(price); MadePurchase = false; player:addKeyItem(KI); player:messageSpecial(KEYITEM_OBTAINED, KI); end i=0; while i <= 31 do if player:hasKeyItem(Maps[i+1]) then mapVar = bit.bor(mapVar, bit.lshift(1,i)); end i = i + 1; end player:updateEvent(mapVar); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Abyssea-Misareaux/Zone.lua
32
1543
----------------------------------- -- -- Zone: Abyssea - Misareaux -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Misareaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Misareaux/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then -- player:setPos(670,-15,318,119); end if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED and player:getVar("1stTimeAyssea") == 0) then player:setVar("1stTimeAyssea",1); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
PioneerMakeTeam/Cretaceous
wicker/kernel_extensions/dst_abstraction/replicas.lua
6
1601
local Lambda = wickerrequire "paradigms.functional" if IsWorldgen() then init = Lambda.Nil return _M end --- local AddReplicatableComponent local get_replica if IsDST() then local get_repcmps_table = memoize_0ary(function() local Reflection = wickerrequire "game.reflection" require "entityscript" require "entityreplica" return Reflection.RequireUpvalue(_G.EntityScript.ReplicateComponent, "REPLICATABLE_COMPONENTS") end) AddReplicatableComponent = function(name) get_repcmps_table()[name] = true end get_replica = function(inst) return inst.replica end else local REPLICA_KEY = {} --- local replicatable_set = {} AddReplicatableComponent = function(name) if replicatable_set[name] then return end replicatable_set[name] = true local cmp_pkgname = "components/"..name local replica_cmp = require(cmp_pkgname.."_replica") TheMod:AddClassPostConstruct(cmp_pkgname, function(self) self[REPLICA_KEY] = replica_cmp(self.inst) end) end --- local new_virtual_replica = (function() local meta = { __index = function(t, k) local inst = t[t] local cmp = inst.components[k] return cmp ~= nil and cmp[REPLICA_KEY] or cmp end, } return function(inst) local t = {} t[t] = inst return setmetatable(t, meta) end end)() get_replica = function(inst) local ret = inst[REPLICA_KEY] if ret == nil then ret = new_virtual_replica(inst) inst[REPLICA_KEY] = ret end return ret end end TheMod:EmbedAdder("ReplicatableComponent", AddReplicatableComponent) function init(kernel) kernel.replica = get_replica end
mit
FFXIOrgins/FFXIOrgins
scripts/globals/spells/mages_ballad.lua
4
1183
----------------------------------------- -- Spell: Mage's Ballad -- Gradually restores target's MP. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local power = 1; local iBoost = caster:getMod(MOD_BALLAD_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_BALLAD,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(75); end return EFFECT_BALLAD; end;
gpl-3.0
moj69/m
plugins/chats.lua
1
2087
local function run(msg) if msg.text == "hi" then return "Hello bb" end if msg.text == "Hi" then return "Hello honey" end if msg.text == "Hello" then return "Hi bb" end if msg.text == "hello" then return "Hi honey" end if msg.text == "مجتبی" then return "با باباییم چیکار داری؟" end if msg.text == "سلام" then return "سلام عزیزم" end if msg.text == "خوبی" then return "ممنون شما چطورید؟" end if msg.text == "خوبی؟" then return "ممنون شما چطورید؟" end if msg.text == "بای" then return "بای بای" end if msg.text == "قیمت" then return [[قیمت گروه: 📢 یک ماهه:2000 تومان 1⃣ دو ماهه: 3000 تومان 2⃣ سه ماهه:4000 تومان 3⃣ مادام العمر: 5000 هزار تومان⭕️ خرید از طریق واریز به کارت ممکن است✔️ شماره حساب:🏧 6037694032107454 ( بانک صادرات - سید رسول میراحمدی ) ادمین: @MoBotSuDo 👤]] end if msg.text == "ربات" then return "بله؟" end if msg.text == "Salam" then return "Salam aleykom" end if msg.text == "salam" then return "و علیکم السلام" end if msg.text == "MoBot" then return "BEst Bot In The World!" end if msg.text == "mobot" then return "Best Bot In The World!" end if msg.text == "Mobot" then return "Best Bot In The World" end if msg.text == "MoBotSudo" then return "Yes?" end if msg.text == "Mo" then return "What?" end if msg.text == "bot" then return "hum?" end if msg.text == "Bot" then return "Huuuum?" end if msg.text == "?" then return "Hum??" end if msg.text == "Bye" then return "Babay" end if msg.text == "bye" then return "Bye Bye" end end return { description = "Chat With Robot Server", usage = "chat with robot", patterns = { "^[Hh]ello$", "^TeleAgent$", "^خوبی$", "^بای$", "^ربات$", "^خوبی؟$", "^مجتبی$", "^قیمت$", "^[Bb]ot$", "^[Mm]oBot$", "^[Bb]ye$", "^?$", }, run = run, --privileged = true, pre_process = pre_process }
agpl-3.0
MAXtgBOT/Telemax-TG
plugins/anti_fosh.lua
14
1450
local function run(msg, matches) if is_owner(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['antifosh'] then lock_fosh = data[tostring(msg.to.id)]['settings']['antifosh'] end end end local chat = get_receiver(msg) local user = "user#id"..msg.from.id if lock_fosh == "yes" then send_large_msg(chat, 'بدلیل فحاشی از گروه سیکتیر شدید') chat_del_user(chat, user, ok_cb, true) end end return { patterns = { "کس(.*)", "کون(.*)", "کیر(.*)", "ممه(.*)", "سکس(.*)", "سیکتیر(.*)", "قهبه(.*)", "بسیک(.*)", "بیناموس(.*)", "اوبی(.*)", "کونی(.*)", "بیشرف(.*)", "کس ننه(.*)", "ساک(.*)", "کیری(.*)", "خار کوسه(.*)", "ننه(.*)", "خواهرتو(.*)", "سکسی(.*)", "کسکش(.*)", "سیک تیر(.*)", "گاییدم(.*)", "میگام(.*)", "میگامت(.*)", "بسیک(.*)", "خواهرت(.*)", "خارتو(.*)", "کونت(.*)", "کوست(.*)", "شورت(.*)", "سگ(.*)", "کیری(.*)", "دزد(.*)", "ننت(.*)", "ابمو(.*)", "جق(.*)" }, run = run }
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Port_San_dOria/npcs/Apstaule.lua
36
1764
----------------------------------- -- Area: Port San d'Oria -- NPC: Apstaule -- Not used cutscenes: 541 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); AuctionParcel = trade:hasItemQty(0x0252,1); if (MagicFlyer == true and count == 1) then FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then player:messageSpecial(FLYER_REFUSED); end elseif (AuctionParcel == true and count == 1) then TheBrugaireConsortium = player:getQuestStatus(SANDORIA,THE_BRUGAIRE_CONSORTIUM); if (TheBrugaireConsortium == 1) then player:tradeComplete(); player:startEvent(0x021c); player:setVar("TheBrugaireConsortium-Parcels", 21); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x21e); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
JulianVolodia/awesome
themes/xresources/theme.lua
4
3298
--------------------------------------------- -- Awesome theme which follows xrdb config -- -- by Yauhen Kirylau -- --------------------------------------------- local xresources = require("beautiful").xresources local xrdb = xresources.get_current_theme() local dpi = xresources.apply_dpi -- inherit default theme local theme = dofile("@AWESOME_THEMES_PATH@/default/theme.lua") -- load vector assets' generators for this theme local theme_assets = dofile("@AWESOME_THEMES_PATH@/xresources/assets.lua") theme.font = "sans 8" theme.bg_normal = xrdb.background theme.bg_focus = xrdb.color12 theme.bg_urgent = xrdb.color9 theme.bg_minimize = xrdb.color8 theme.bg_systray = theme.bg_normal theme.fg_normal = xrdb.foreground theme.fg_focus = theme.bg_normal theme.fg_urgent = theme.bg_normal theme.fg_minimize = theme.bg_normal theme.useless_gap = dpi(3) theme.border_width = dpi(2) theme.border_normal = xrdb.color0 theme.border_focus = theme.bg_focus theme.border_marked = xrdb.color10 -- There are other variable sets -- overriding the default one when -- defined, the sets are: -- taglist_[bg|fg]_[focus|urgent|occupied|empty] -- tasklist_[bg|fg]_[focus|urgent] -- titlebar_[bg|fg]_[normal|focus] -- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color] -- mouse_finder_[color|timeout|animate_timeout|radius|factor] -- Example: --theme.taglist_bg_focus = "#ff0000" -- Variables set for theming the menu: -- menu_[bg|fg]_[normal|focus] -- menu_[border_color|border_width] theme.menu_submenu_icon = "@AWESOME_THEMES_PATH@/default/submenu.png" theme.menu_height = dpi(16) theme.menu_width = dpi(100) -- You can add as many variables as -- you wish and access them by using -- beautiful.variable in your rc.lua --theme.bg_widget = "#cc0000" -- Recolor titlebar icons: theme = theme_assets.recolor_titlebar_normal(theme, theme.fg_normal) theme = theme_assets.recolor_titlebar_focus(theme, theme.fg_focus) theme = theme_assets.recolor_layout(theme, theme.fg_normal) -- Define the icon theme for application icons. If not set then the icons -- from /usr/share/icons and /usr/share/icons/hicolor will be used. theme.icon_theme = nil -- Generate Awesome icon: theme.awesome_icon = theme_assets.awesome_icon( theme.menu_height, theme.bg_focus, theme.fg_focus ) -- Generate taglist squares: local taglist_square_size = dpi(4) theme.taglist_squares_sel = theme_assets.taglist_squares_sel( taglist_square_size, theme.fg_normal ) theme.taglist_squares_unsel = theme_assets.taglist_squares_unsel( taglist_square_size, theme.fg_normal ) -- Try to determine if we are running light or dark colorscheme: local bg_numberic_value = 0; for s in theme.bg_normal:gmatch("[a-fA-F0-9][a-fA-F0-9]") do bg_numberic_value = bg_numberic_value + tonumber("0x"..s); end local is_dark_bg = (bg_numberic_value < 383) -- Generate wallpaper: local wallpaper_bg = xrdb.color8 local wallpaper_fg = xrdb.color7 local wallpaper_alt_fg = xrdb.color12 if not is_dark_bg then wallpaper_bg, wallpaper_fg = wallpaper_fg, wallpaper_bg end theme.wallpaper = theme_assets.wallpaper( wallpaper_bg, wallpaper_fg, wallpaper_alt_fg ) return theme -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Bastok_Mines/npcs/Phara.lua
20
2542
----------------------------------- -- Area: Bastok Mines -- NPC: Phara -- Starts and Finishes Quest: The doorman (start) -- Involved in Quest: The Talekeeper's Truth -- @zone 234 -- @pos 75 0 -80 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) theDoorman = player:getQuestStatus(BASTOK,THE_DOORMAN); theTalekeeperTruth = player:getQuestStatus(BASTOK,THE_TALEKEEPER_S_TRUTH); if(theDoorman == QUEST_AVAILABLE and player:getMainJob() == 1 and player:getMainLvl() >= 40) then player:startEvent(0x0097); -- Start Quests "The doorman" elseif(player:hasKeyItem(SWORD_GRIP_MATERIAL)) then player:startEvent(0x0098); -- Need to wait 1 vanadiel day elseif(player:getVar("theDoormanCS") == 2 and VanadielDayOfTheYear() ~= player:getVar("theDoorman_time")) then player:startEvent(0x0099); -- The doorman notification, go to naji elseif(theDoorman == QUEST_COMPLETED and theTalekeeperTruth == QUEST_AVAILABLE) then player:startEvent(0x009a); -- New standard dialog else player:startEvent(0x0096); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0097) then player:addQuest(BASTOK,THE_DOORMAN); player:setVar("theDoormanCS",1); elseif(csid == 0x0098) then player:setVar("theDoorman_time",VanadielDayOfTheYear()); player:setVar("theDoormanCS",2); player:delKeyItem(SWORD_GRIP_MATERIAL); elseif(csid == 0x0099) then player:addKeyItem(YASINS_SWORD); player:messageSpecial(KEYITEM_OBTAINED,YASINS_SWORD); player:setVar("theDoormanCS",3); player:setVar("theDoorman_time",0); elseif(csid == 0x009a) then player:setVar("theTalekeeperTruthCS",1); end end;
gpl-3.0
subzrk/BadRotations
System/engines/HealingEngine.lua
3
21447
--[[--------------------------------------------------------------------------------------------------- -----------------------------------------Bubba's Healing Engine--------------------------------------]] if not metaTable1 then -- localizing the commonly used functions while inside loops local getDistance,tinsert,tremove,UnitGUID,UnitClass,UnitIsUnit = getDistance,tinsert,tremove,UnitGUID,UnitClass,UnitIsUnit local UnitDebuff,UnitExists,UnitHealth,UnitHealthMax = UnitDebuff,UnitExists,UnitHealth,UnitHealthMax local GetSpellInfo,GetTime,UnitDebuffID,getBuffStacks = GetSpellInfo,GetTime,UnitDebuffID,getBuffStacks br.friend = {} -- This is our main Table that the world will see memberSetup = {} -- This is one of our MetaTables that will be the default user/contructor memberSetup.cache = { } -- This is for the cache Table to check against metaTable1 = {} -- This will be the MetaTable attached to our Main Table that the world will see metaTable1.__call = function(_, ...) -- (_, forceRetable, excludePets, onlyInRange) [Not Implemented] local group = IsInRaid() and "raid" or "party" -- Determining if the UnitID will be raid or party based local groupSize = IsInRaid() and GetNumGroupMembers() or GetNumGroupMembers() - 1 -- If in raid, we check the entire raid. If in party, we remove one from max to account for the player. if group == "party" then tinsert(br.friend, memberSetup:new("player")) end -- We are creating a new User for player if in a Group for i=1, groupSize do -- start of the loop to read throught the party/raid local groupUnit = group..i local groupMember = memberSetup:new(groupUnit) if groupMember then tinsert(br.friend, groupMember) end -- Inserting a newly created Unit into the Main Frame end end metaTable1.__index = {-- Setting the Metamethod of Index for our Main Table name = "Healing Table", author = "Bubba", } -- Creating a default Unit to default to on a check memberSetup.__index = { name = "noob", hp = 100, unit = "noob", role = "NOOB", range = false, guid = 0, guidsh = 0, class = "NONE", } -- If ever somebody enters or leaves the raid, wipe the entire Table local updateHealingTable = CreateFrame("frame", nil) updateHealingTable:RegisterEvent("GROUP_ROSTER_UPDATE") updateHealingTable:SetScript("OnEvent", function() table.wipe(br.friend) table.wipe(memberSetup.cache) SetupTables() end) -- This is for those NPC units that need healing. Compare them against our list of Unit ID's local function SpecialHealUnit(tar) for i=1, #novaEngineTables.SpecialHealUnitList do if getGUID(tar) == novaEngineTables.SpecialHealUnitList[i] then return true end end end -- We are checking if the user has a Debuff we either can not or don't want to heal them local function CheckBadDebuff(tar) for i=1, #novaEngineTables.BadDebuffList do if UnitDebuff(tar, GetSpellInfo(novaEngineTables.BadDebuffList[i])) or UnitBuff(tar, GetSpellInfo(novaEngineTables.BadDebuffList[i])) then return false end end return true end -- This is for NPC units we do not want to heal. Compare to list in collections. local function CheckSkipNPC(tar) local npcId = (getGUID(tar)) for i=1, #novaEngineTables.skipNPC do if npcId == novaEngineTables.skipNPC[i] then return true end end return false end local function CheckCreatureType(tar) local CreatureTypeList = {"Critter", "Totem", "Non-combat Pet", "Wild Pet"} for i=1, #CreatureTypeList do if UnitCreatureType(tar) == CreatureTypeList[i] then return false end end if not UnitIsBattlePet(tar) and not UnitIsWildBattlePet(tar) then return true else return false end end -- Verifying the target is a Valid Healing target function HealCheck(tar) if ((UnitIsVisible(tar) and not UnitIsCharmed(tar) and UnitReaction("player",tar) > 4 and not UnitIsDeadOrGhost(tar) and UnitIsConnected(tar) and UnitInPhase(tar)) or novaEngineTables.SpecialHealUnitList[tonumber(select(2,getGUID(tar)))] ~= nil or (getOptionCheck("Heal Pets") == true and UnitIsOtherPlayersPet(tar) or UnitGUID(tar) == UnitGUID("pet"))) and CheckBadDebuff(tar) and CheckCreatureType(tar) and getLineOfSight("player", tar) and UnitInPhase(tar) then return true else return false end end function memberSetup:new(unit) -- Seeing if we have already cached this unit before if memberSetup.cache[getGUID(unit)] then return false end local o = {} setmetatable(o, memberSetup) if unit and type(unit) == "string" then o.unit = unit end -- This is the function for Dispel checking built into the player itself. function o:Dispel() for i = 1, #novaEngineTables.DispelID do if UnitDebuff(o.unit,GetSpellInfo(novaEngineTables.DispelID[i].id)) ~= nil and novaEngineTables.DispelID[i].id ~= nil then if select(4,UnitDebuff(o.unit,GetSpellInfo(novaEngineTables.DispelID[i].id))) >= novaEngineTables.DispelID[i].stacks and (isChecked("Dispel delay") and (getDebuffDuration(o.unit, novaEngineTables.DispelID[i].id) - getDebuffRemain(o.unit, novaEngineTables.DispelID[i].id)) > (getDebuffDuration(o.unit, novaEngineTables.DispelID[i].id) * (math.random(getValue("Dispel delay")-2, getValue("Dispel delay")+2)/100) ))then -- Dispel Delay if novaEngineTables.DispelID[i].range ~= nil then if #getAllies(o.unit,novaEngineTables.DispelID[i].range) > 1 then return false end end return true end end end return false end -- We are checking the HP of the person through their own function. function o:CalcHP() -- Place out of range players at the end of the list -- replaced range to 40 as we should be using lib range if not UnitInRange(o.unit) and getDistance(o.unit) > 40 and not UnitIsUnit("player", o.unit) then return 250,250,250 end -- Place Dead players at the end of the list if HealCheck(o.unit) ~= true then return 250,250,250 end -- incoming heals local incomingheals if getOptionCheck("Incoming Heals") == true and UnitGetIncomingHeals(o.unit,"player") ~= nil then incomingheals = UnitGetIncomingHeals(o.unit,"player") else incomingheals = 0 end -- absorbs local nAbsorbs if getOptionCheck("No Absorbs") ~= true then nAbsorbs = (UnitGetTotalAbsorbs(o.unit)*0.25) else nAbsorbs = 0 end -- calc base + absorbs + incomings local PercentWithIncoming = 100 * ( UnitHealth(o.unit) + incomingheals + nAbsorbs ) / UnitHealthMax(o.unit) -- Using the group role assigned to the Unit if o.role == "TANK" then PercentWithIncoming = PercentWithIncoming - 5 end -- Using Dispel Check to see if we should give bonus weight if o.dispel then PercentWithIncoming = PercentWithIncoming - 2 end -- Using threat to remove 3% to all tanking units if o.threat == 3 then PercentWithIncoming = PercentWithIncoming - 3 end -- Tank in Proving Grounds if o.guidsh == 72218 then PercentWithIncoming = PercentWithIncoming - 5 end local ActualWithIncoming = ( UnitHealthMax(o.unit) - ( UnitHealth(o.unit) + incomingheals ) ) -- Malkorok shields logic local SpecificHPBuffs = { {buff = 142865,value = select(15,UnitDebuffID(o.unit,142865))}, -- Strong Ancient Barrier (Green) {buff = 142864,value = select(15,UnitDebuffID(o.unit,142864))}, -- Ancient Barrier (Yellow) {buff = 142863,value = select(15,UnitDebuffID(o.unit,142863))}, -- Weak Ancient Barrier (Red) } if UnitDebuffID(o.unit, 142861) then -- If Miasma found for i = 1,#SpecificHPBuffs do -- start iteration if UnitDebuffID(o.unit, SpecificHPBuffs[i].buff) ~= nil then -- if buff found if SpecificHPBuffs[i].value ~= nil then PercentWithIncoming = 100 + (SpecificHPBuffs[i].value/UnitHealthMax(o.unit)*100) -- we set its amount + 100 to make sure its within 50-100 range break end end end PercentWithIncoming = PercentWithIncoming/2 -- no mather what as long as we are on miasma buff our life is cut in half so unshielded ends up 0-50 end -- Tyrant Velhair Aura logic if UnitDebuffID(o.unit, 179986) then -- If Aura of Contempt found max_percentage = select(15,UnitAura("boss1",GetSpellInfo(179986))) -- find current reduction % in healing if max_percentage then PercentWithIncoming = (PercentWithIncoming/max_percentage)* 100 -- Calculate Actual HP % after reduction end end -- Debuffs HP compensation local HpDebuffs = novaEngineTables.SpecificHPDebuffs for i = 1, #HpDebuffs do local _,_,_,count,_,_,_,_,_,_,spellID = UnitDebuffID(o.unit,HpDebuffs[i].debuff) if spellID ~= nil and (HpDebuffs[i].stacks == nil or (count and count >= HpDebuffs[i].stacks)) then PercentWithIncoming = PercentWithIncoming - HpDebuffs[i].value break end end if getOptionCheck("Blacklist") == true and br.data.blackList ~= nil then for i = 1, #br.data.blackList do if o.guid == br.data.blackList[i].guid then PercentWithIncoming,ActualWithIncoming,nAbsorbs = PercentWithIncoming + getValue("Blacklist"),ActualWithIncoming + getValue("Blacklist"),nAbsorbs + getValue("Blacklist") break end end end return PercentWithIncoming,ActualWithIncoming,nAbsorbs end -- returns unit GUID function o:nGUID() local nShortHand = "" if GetUnitExists(unit) then targetGUID = UnitGUID(unit) nShortHand = UnitGUID(unit):sub(-5) end return targetGUID, nShortHand end -- Returns unit class function o:GetClass() if UnitGroupRolesAssigned(o.unit) == "NONE" then if UnitIsUnit("player",o.unit) then return UnitClass("player") end if novaEngineTables.roleTable[UnitName(o.unit)] ~= nil then return novaEngineTables.roleTable[UnitName(o.unit)].class end else return UnitClass(o.unit) end end -- return unit role function o:GetRole() if UnitGroupRolesAssigned(o.unit) == "NONE" then -- if we already have a role defined we dont scan if novaEngineTables.roleTable[UnitName(o.unit)] ~= nil then return novaEngineTables.roleTable[UnitName(o.unit)].role end else return UnitGroupRolesAssigned(o.unit) end end -- sets actual position of unit in engine, shouldnt refresh more than once/sec function o:GetPosition() if GetUnitIsVisible(o.unit) then o.refresh = GetTime() local x,y,z = GetObjectPosition(o.unit) x = math.ceil(x*100)/100 y = math.ceil(y*100)/100 z = math.ceil(z*100)/100 return x,y,z else return 0,0,0 end end -- Group Number of Player: getUnitGroupNumber(1) function o:getUnitGroupNumber() -- check if in raid if IsInRaid() and UnitInRaid(o.unit) ~= nil then return select(3,GetRaidRosterInfo(UnitInRaid(o.unit))) end return 0 end -- Unit distance to player function o:getUnitDistance() if UnitIsUnit("player",o.unit) then return 0 end return getDistance("player",o.unit) end -- Updating the values of the Unit function o:UpdateUnit() if br.data.settings[br.selectedSpec].toggles["isDebugging"] == true then local startTime, duration local debugprofilestop = debugprofilestop -- assign Name of unit startTime = debugprofilestop() o.name = UnitName(o.unit) br.debug.cpu.healingEngine.UnitName = br.debug.cpu.healingEngine.UnitName + debugprofilestop()-startTime -- assign real GUID of unit startTime = debugprofilestop() o.guid = o:nGUID() br.debug.cpu.healingEngine.nGUID = br.debug.cpu.healingEngine.nGUID + debugprofilestop()-startTime -- assign unit role startTime = debugprofilestop() o.role = o:GetRole() br.debug.cpu.healingEngine.GetRole = br.debug.cpu.healingEngine.GetRole + debugprofilestop()-startTime -- subgroup number startTime = debugprofilestop() o.subgroup = o:getUnitGroupNumber() br.debug.cpu.healingEngine.getUnitGroupNumber = br.debug.cpu.healingEngine.getUnitGroupNumber+ debugprofilestop()-startTime -- Short GUID of unit for the SetupTable o.guidsh = select(2, o:nGUID()) -- set to true if unit should be dispelled startTime = debugprofilestop() o.dispel = o:Dispel(o.unit) br.debug.cpu.healingEngine.Dispel = br.debug.cpu.healingEngine.Dispel + debugprofilestop()-startTime -- distance to player startTime = debugprofilestop() o.distance = o:getUnitDistance() br.debug.cpu.healingEngine.getUnitDistance = br.debug.cpu.healingEngine.getUnitDistance + debugprofilestop()-startTime -- Unit's threat situation(1-4) startTime = debugprofilestop() o.threat = UnitThreatSituation(o.unit) br.debug.cpu.healingEngine.UnitThreatSituation = br.debug.cpu.healingEngine.UnitThreatSituation + debugprofilestop()-startTime -- Unit HP absolute startTime = debugprofilestop() o.hpabs = UnitHealth(o.unit) br.debug.cpu.healingEngine.UnitHealth = br.debug.cpu.healingEngine.UnitHealth + debugprofilestop()-startTime -- Unit HP missing absolute startTime = debugprofilestop() o.hpmissing = UnitHealthMax(o.unit) - UnitHealth(o.unit) br.debug.cpu.healingEngine.hpMissing = br.debug.cpu.healingEngine.hpMissing + debugprofilestop()-startTime -- Unit HP startTime = debugprofilestop() o.hp = o:CalcHP() o.absorb = select(3, o:CalcHP()) br.debug.cpu.healingEngine.absorb = br.debug.cpu.healingEngine.absorb + debugprofilestop()-startTime -- Target's target o.target = tostring(o.unit).."target" -- Unit Class startTime = debugprofilestop() o.class = o:GetClass() br.debug.cpu.healingEngine.GetClass = br.debug.cpu.healingEngine.GetClass + debugprofilestop()-startTime -- Unit is player startTime = debugprofilestop() o.isPlayer = UnitIsPlayer(o.unit) br.debug.cpu.healingEngine.UnitIsPlayer = br.debug.cpu.healingEngine.UnitIsPlayer + debugprofilestop()-startTime -- precise unit position startTime = debugprofilestop() if o.refresh == nil or o.refresh < GetTime() - 1 then o.x,o.y,o.z = o:GetPosition() end br.debug.cpu.healingEngine.GetPosition = br.debug.cpu.healingEngine.GetPosition + debugprofilestop()-startTime --debug startTime = debugprofilestop() o.hp, _, o.absorb = o:CalcHP() br.debug.cpu.healingEngine.absorbANDhp = br.debug.cpu.healingEngine.absorbANDhp + debugprofilestop()-startTime else -- assign Name of unit o.name = UnitName(o.unit) -- assign real GUID of unit and Short GUID of unit for the SetupTable o.guid, o.guidsh = o:nGUID() -- assign unit role o.role = o:GetRole() -- subgroup number o.subgroup = o:getUnitGroupNumber() -- set to true if unit should be dispelled o.dispel = o:Dispel(o.unit) -- distance to player o.distance = o:getUnitDistance() -- Unit's threat situation(1-4) o.threat = UnitThreatSituation(o.unit) -- Unit HP absolute o.hpabs = UnitHealth(o.unit) -- Unit HP missing absolute o.hpmissing = UnitHealthMax(o.unit) - UnitHealth(o.unit) -- Unit HP and Absorb o.hp, _, o.absorb = o:CalcHP() -- Target's target o.target = tostring(o.unit).."target" -- Unit Class o.class = o:GetClass() -- Unit is player o.isPlayer = UnitIsPlayer(o.unit) -- precise unit position if o.refresh == nil or o.refresh < GetTime() - 1 then o.x,o.y,o.z = o:GetPosition() end end -- add unit to setup cache memberSetup.cache[select(2, getGUID(o.unit))] = o -- Add unit to SetupTable end -- Adding the user and functions we just created to this cached version in case we need it again -- This will also serve as a good check for if the unit is already in the table easily --Print(UnitName(unit), select(2, getGUID(unit))) memberSetup.cache[select(2, o:nGUID())] = o return o end -- Setting up the tables on either Wipe or Initial Setup function SetupTables() -- Creating the cache (we use this to check if some1 is already in the table) setmetatable(br.friend, metaTable1) -- Set the metaTable of Main to Meta function br.friend:Update() local refreshTimer = 0.666 if br.friendTableTimer == nil or br.friendTableTimer <= GetTime() - refreshTimer then br.friendTableTimer = GetTime() -- Print("HEAL PULSE: "..GetTime()) -- debug Print to check update time -- This is for special situations, IE world healing or NPC healing in encounters local selectedMode,SpecialTargets = getOptionValue("Special Heal"), {} if getOptionCheck("Special Heal") == true then if selectedMode == 1 then SpecialTargets = { "target" } elseif selectedMode == 2 then SpecialTargets = { "target","mouseover","focus" } elseif selectedMode == 3 then SpecialTargets = { "target","mouseover" } else SpecialTargets = { "target","focus" } end end for p=1, #SpecialTargets do -- Checking if Unit Exists and it's possible to heal them if GetUnitExists(SpecialTargets[p]) and HealCheck(SpecialTargets[p]) and not CheckSkipNPC(SpecialTargets[p]) then if not memberSetup.cache[select(2, getGUID(SpecialTargets[p]))] then local SpecialCase = memberSetup:new(SpecialTargets[p]) if SpecialCase then -- Creating a new user, if not already tabled, will return with the User for j=1, #br.friend do if br.friend[j].unit == SpecialTargets[p] then -- Now we add the Unit we just created to the Main Table for k,v in pairs(memberSetup.cache) do if br.friend[j].guidsh == k then memberSetup.cache[k] = nil end end tremove(br.friend, j) break end end end tinsert(br.friend, SpecialCase) novaEngineTables.SavedSpecialTargets[SpecialTargets[p]] = select(2,getGUID(SpecialTargets[p])) end end end for p=1, #SpecialTargets do local removedTarget = false for j=1, #br.friend do -- Trying to find a case of the unit inside the Main Table to remove if br.friend[j].unit == SpecialTargets[p] and (br.friend[j].guid ~= 0 and br.friend[j].guid ~= UnitGUID(SpecialTargets[p])) then tremove(br.friend, j) removedTarget = true break end end if removedTarget == true then for k,v in pairs(memberSetup.cache) do -- Now we're trying to find that unit in the Cache table to remove if SpecialTargets[p] == v.unit then memberSetup.cache[k] = nil end end end end for i=1, #br.friend do -- We are updating all of the User Info (Health/Range/Name) br.friend[i]:UpdateUnit() end -- We are sorting by Health first table.sort(br.friend, function(x,y) return x.hp < y.hp end) -- Sorting with the Role if getOptionCheck("Sorting with Role") then table.sort(br.friend, function(x,y) if x.role and y.role then return x.role > y.role elseif x.role then return true elseif y.role then return false end end) end if getOptionCheck("Special Priority") == true then if GetUnitExists("focus") and memberSetup.cache[select(2, getGUID("focus"))] then table.sort(br.friend, function(x) if x.unit == "focus" then return true else return false end end) end if GetUnitExists("target") and memberSetup.cache[select(2, getGUID("target"))] then table.sort(br.friend, function(x) if x.unit == "target" then return true else return false end end) end if GetUnitExists("mouseover") and memberSetup.cache[select(2, getGUID("mouseover"))] then table.sort(br.friend, function(x) if x.unit == "mouseover" then return true else return false end end) end end if pulseNovaDebugTimer == nil or pulseNovaDebugTimer <= GetTime() then pulseNovaDebugTimer = GetTime() + 0.5 pulseNovaDebug() end -- update these frames to current br.friend values via a pulse in nova engine end -- timer capsule end -- We are creating the initial Main Table br.friend() end -- We are setting up the Tables for the first time SetupTables() end
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Temenos/mobs/Cryptonberry_Skulker.lua
17
1139
----------------------------------- -- Area: Temenos N T -- NPC: Cryptonberry_Skulker ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if(IsMobDead(16928816)==true and IsMobDead(16928817)==true )then GetNPCByID(16928768+38):setPos(-412,-78,426); GetNPCByID(16928768+38):setStatus(STATUS_NORMAL); GetNPCByID(16928768+172):setPos(-415,-78,427); GetNPCByID(16928768+172):setStatus(STATUS_NORMAL); GetNPCByID(16928768+214):setPos(-412,-78,422); GetNPCByID(16928768+214):setStatus(STATUS_NORMAL); GetNPCByID(16928770+455):setStatus(STATUS_NORMAL); end end;
gpl-3.0
cjtallman/lua_sysenv
spec/setenv_spec.lua
1
1717
describe(".setenv", function() local sysenv = require("lua_sysenv") local setenv = sysenv.setenv it("is a valid type", function() assert.is_function(setenv) end) it("sets new variable", function() local var = "FOO" local val = "BAR" assert.is_nil(os.getenv(var)) assert.is_true(setenv(var, val)) assert.is_equal(os.getenv(var), val) end) it("sets existing variable", function() local var = "PATH" local val = "BAR" assert.is_string(os.getenv(var)) assert.is_true(setenv(var, val)) assert.is_equal(os.getenv(var), val) end) describe("throws errors", function() it("with 1 argument", function() assert.is_error(function() setenv("FOO") end) end) it("with 0 arguments", function() assert.is_error(function() setenv() end) end) it("with invalid argument types", function() assert.is_error(function() setenv(1, "BAR") end) -- should not convert to string assert.is_error(function() setenv(true, "BAR") end) assert.is_error(function() setenv({1}, "BAR") end) assert.is_error(function() setenv(nil, "BAR") end) assert.is_error(function() setenv(function() end, "BAR") end) assert.is_not_error(function() setenv("FOO", 1) end) -- able to convert to string assert.is_error(function() setenv("FOO", true) end) assert.is_error(function() setenv("FOO", {1}) end) assert.is_error(function() setenv("FOO", nil) end) assert.is_error(function() setenv("FOO", function() end) end) end) end) end)
mit
fartoverflow/naev
dat/missions/neutral/dts_02.lua
6
13600
--[[ MISSION: Defend the System 3 DESCRIPTION: A mission to defend the system against swarm of pirate ships. This will be the third in a series of random encounters. After the mission, perhaps there'll be a regular diet of similar missions Perhaps the random missions will eventually lead on to a plot line relating to the pirates. Notable events: * Stage one: From the bar, the player learns of a pirate fleet attacking the system and joins a defense force. * Stage two: The volunteer force attacks the pirates. * Stage three: When a sufficient number have been killed, the pirates retreat. * Stage four: The portmaster welcomes the fleet back and thanks them with money. * Stage five: In the bar afterward, another pilot wonders why the pirates behaved unusually. TO DO Make comm chatter appear during the battle NOTE Because of bad planning, this mission is badly organized. Anyone looking for a model of good mission-making should look elsewhere! -- the author ]]-- include "dat/scripts/numstring.lua" -- localization stuff, translators would work here lang = naev.lang() if lang == "es" then else -- default english -- This section stores the strings (text) for the mission. -- Mission details misn_title = "Defend the System" misn_reward = "%s credits and the pleasure of serving the Empire." misn_desc = "Defend the system against a pirate fleet." -- Stage one: in the bar you hear a fleet of Pirates have invaded the system. title = {} text = {} title[1] = "In the bar" text[1] = [[The bar rests in the dull clink of glasses and the scattered murmur of conversation when the door bursts open. An older couple stumbles in, faces gaping, eyes staring. They take a few steps before the woman sinks to her knees and bursts into tears. "Our son... his ship was supposed to land a minute ago," her partner says mechanically. "But pirates, suddenly everywhere-" he swallows. "-they didn't make it." His wife throws her head back and wails. Two young men rise abruptly from a table in the back of the room and come stiffly forward. One goes to the grieving couple while the other turns address the room. "These raiders must be stopped. We are cadets at the Imperial Flight School. If you feel the injustice of this family's loss, will you fly with us to avenge their son's death?"]] title[11] = "Volunteers" text[11] = [["These terrorists cannot sustain many losses," one of the young men explains as you and a group of other volunteers prepare for takeoff, "and they have no organization. We can destroy them if you team up and focus your fire on one ship at a time."]] -- Stage two: comm chatter, now no longer used except to initialize the table comm = {} -- Stage three: Victorious comm chatter comm[6] = "We've got them on the run!" comm[61] = "Broadcast %s> The raiders are retreating!" comm[7] = "Good flying, volunteers. The governor is waiting for us back in port." comm[71] = "Comm %s> Good flying, volunteers. The governor is waiting for you back in port." -- Stage four: the governor greets you and the cadets in front of a crowd title[2] = "A public occasion" text[2] = [[Night is falling by the time you land back on %s. Looking solemn in front of a gathering crowd and news recorders, a large man with a fleshy face comes forward to greet the survivors of the fight. A flock of men and women follow him. When he shakes your hand, the Governor looks keenly at you at smiles, "Very well done." After meeting each surviving pilot, the tall man stands still for aide to attach an amplifier to his lapel. Then he turns his face to the news-casters and the crowd.]] -- Stage five: the commander welcomes you back title[3] = "The Governor's speech" text[3] = [[ "Even here on %s, even in the protective embrace of civilization, we face many dangers. The ties that bind us through space to other worlds are fragile. When criminals attack these precious connections, they trouble the very foundations of our peace. How glad we are now for the security of the Empire whose young navy cadets led a team of independent pilots to defend us today." The Governor turns to the pair of officers-in-training. "In the name of the Emperor, I have the privilege of decorating these two young heroes with the %s Silver Heart. I hope they and their volunteers will not be too proud to also accept a generous purse, along with the gratitude of all our people. Please join me in applauding their bravery." The public ceremony lasts only a few minutes. Afterwards, as interviewers draw the young navy officers aside and the crowd disperses, you catch sight of the elderly couple from the bar holding each other and looking up into the darkening sky.]] -- Other text for the mission comm[8] = "You fled from the battle. The Empire won't forget." comm[9] = "Comm Lancelot> You're a coward, %s. You better hope I never see you again." comm[10] = "Comm Lancelot> You're running away now, %s? The fight's finished, you know..." title[4] = "Good job!" text[4] = [[A freighter hails you as you jump into the system. "Thank you for responding %s, are you coming in from %s? I have a delivery I need to get to %s and I can't wait much longer. Is the system safe now?" You relate the outcome of the space battle. "Oh, that's good news! You know, these raids are getting worse all the time. I wish the Empire would do something about it. Anyway, thank you for the information. Safe travels."]] title[5] = "Not fighting" text[5] = [[You stand by the grieving couple as the two cadets lead a group of pilots out of the bar toward the padfield. "Oh no!" the woman cries suddenly, looking up into her partner's face. "They're going off to fight. Those young men, they... there'll be more killing because of us." He nods grimly. "That's the way of things." For long time, the two of them sit on the floor of the bar holding each other.]] bounce_title = "Not done yet." bounce_text = "The system isn't safe yet. Get back out there!" noReward = "No reward for you." noDesc = "Watch others defend the system." noTitle = "Observe the action." end -- Create the mission on the current planet, and present the first Bar text. function create() this_planet, this_system = planet.cur() if ( this_system:presences()["Pirate"] or this_system:presences()["Collective"] or this_system:presences()["FLF"] or this_system:name() == "Gamma Polaris" or this_system:name() == "Doeston" or this_system:name() == "NGC-7291") then misn.finish(false) end missys = {this_system} if not misn.claim(missys) then misn.finish(false) end planet_name = planet.name( this_planet) system_name = this_system:name() if tk.yesno( title[1], text[1] ) then misn.accept() tk.msg( title[11], text[11]) reward = 40000 misn.setReward( string.format( misn_reward, numstring(reward)) ) misn.setDesc( misn_desc) misn.setTitle( misn_title) misn.markerAdd( this_system, "low" ) defender = true -- hook an abstract deciding function to player entering a system hook.enter( "enter_system") -- hook warm reception to player landing hook.land( "celebrate_victory") else -- If player didn't accept the mission, the battle's still on, but player has no stake. misn.accept() var.push( "dts_firstSystem", "planet_name") tk.msg( title[5], text[5]) misn.setReward( noReward) misn.setDesc( noDesc) misn.setTitle( noTitle) defender = false -- hook an abstract deciding function to player entering a system when not part of defense hook.enter( "enter_system") end end -- Decides what to do when player either takes off starting planet or jumps into another system function enter_system() if this_system == system.cur() and defender == true then defend_system() elseif victory == true and defender == true then pilot.add( "Trader Koala", "def", player.pos(), false) hook.timer(1000, "ship_enters") elseif defender == true then player.msg( comm[8]) faction.modPlayerSingle( "Empire", -3) misn.finish( true) elseif this_system == system.cur() and been_here_before ~= true then been_here_before = true defend_system() else misn.finish( true) end end -- There's a battle to defend the system function defend_system() -- Makes the system empty except for the two fleets. No help coming. pilot.clear () pilot.toggleSpawn( false ) -- Set up distances angle = rnd.rnd() * 2 * math.pi if defender == true then raider_position = vec2.new( 400*math.cos(angle), 400*math.sin(angle) ) defense_position = vec2.new( 0, 0 ) else raider_position = vec2.new( 800*math.cos(angle), 800*math.sin(angle) ) defense_position = vec2.new( 400*math.cos(angle), 400*math.sin(angle) ) end -- Create a fleet of raiding pirates raider_fleet = pilot.add( "DTS Raiders", "def", raider_position ) for k,v in ipairs( raider_fleet) do v:setHostile() end -- And a fleet of defending independents defense_fleet = pilot.add( "DTS Defense Fleet", "def", defense_position ) cadet1 = pilot.add( "Empire Lancelot", "def", defense_position )[1] do cadet1_alive = true hook.pilot( cadet1, "death", "cadet1_dead") end cadet2 = pilot.add( "Empire Lancelot", "def", defense_position )[1] do cadet2_alive = true hook.pilot( cadet2, "death", "cadet2_dead") end for k,v in ipairs( defense_fleet) do v:setFriendly() end cadet1:setFriendly() cadet2:setFriendly() --[[ Set conditions for the end of the Battle: hook fleet departure to disabling or killing ships]] casualties = 0 casualty_max = (#raider_fleet / 2 + 1) victories = 0 victory = false for k, v in ipairs( raider_fleet) do hook.pilot (v, "disable", "add_cas_and_check") end if defender == false then misn.finish( true) end end -- If they die, they can't communicate with the player. function cadet1_dead() cadet1_alive = false end function cadet2_dead() cadet2_alive = false end -- Record each raider death and make the raiders flee after too many casualties function add_cas_and_check() if victory then return end casualties = casualties + 1 if casualties > casualty_max then raiders_left = pilot.get( { faction.get("Raider") } ) for k, v in ipairs( raiders_left ) do v:changeAI("flee") end if victories < 1 then -- Send in the second wave victories = victories + 1 second_wave_attacks() else victory = true player.msg( comm[6]) -- A few seconds after victory, the system is back under control hook.timer(8000, "victorious") return end end end function second_wave_attacks() casualties = 0 second_wave = pilot.add( "Pirate Hyena Pack", "def", player.pos(), true) for k, v in ipairs( second_wave) do v:setFaction( "Raider") v:setHostile() end casualty_max = math.modf( #second_wave / 2) for k, v in ipairs( second_wave) do hook.pilot (v, "disable", "add_cas_and_check") end end -- Separate mission for a mid-mission interjection <-- bad organization function cadet_first_comm() if cadet1_alive then cadet1:comm( comm[6]) elseif cadet2_alive then cadet2:comm( comm[6]) else player.msg( string.format(comm[61], planet_name)) end end -- When the raiders are on the run then the Empire takes over function victorious() if cadet1_alive then cadet1:comm( comm[7]) elseif cadet2_alive then cadet2:comm( comm[7]) else player.msg( string.format(comm[71], planet_name)) end end -- The player lands to a warm welcome (if the job is done). function celebrate_victory() if victory == true then tk.msg( title[2], string.format( text[2], planet_name) ) player.pay( reward) faction.modPlayerSingle( "Empire", 3) tk.msg( title[3], string.format( text[3], planet_name, planet_name) ) misn.finish( true) else tk.msg( bounce_title, bounce_text) -- If any pirates still alive, send player back out. player.takeoff() end end -- A fellow warrior says hello in passing if player jumps out of the system without landing function ship_enters() enter_vect = player.pos() hook.timer(1000, "congratulations") end function congratulations() tk.msg( title[4], string.format( text[4], player.ship(), system_name, planet_name)) misn.finish( true) end -- If the player aborts the mission, the Empire and Traders react function abort() if victory == false then faction.modPlayerSingle( "Empire", -10) faction.modPlayerSingle( "Trader", -10) player.msg( string.format( comm[9], player.name())) else player.msg( string.format( comm[10], player.name())) end misn.finish( true) end
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/bowl_of_ambrosia.lua
35
2277
----------------------------------------- -- ID: 4511 -- Item: Bowl of Ambrosia -- Food Effect: 240Min, All Races ----------------------------------------- -- Health 7 -- Magic 7 -- Strength 7 -- Dexterity 7 -- Agility 7 -- Vitality 7 -- Intelligence 7 -- Mind 7 -- Charisma 7 -- Health Regen While Healing 7 -- Magic Regen While Healing 7 -- Attack 7 -- defense 7 -- Accuracy 7 -- Evasion 7 -- Store TP 7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4511); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 7); target:addMod(MOD_MP, 7); target:addMod(MOD_STR, 7); target:addMod(MOD_DEX, 7); target:addMod(MOD_AGI, 7); target:addMod(MOD_VIT, 7); target:addMod(MOD_INT, 7); target:addMod(MOD_MND, 7); target:addMod(MOD_CHR, 7); target:addMod(MOD_HPHEAL, 7); target:addMod(MOD_MPHEAL, 7); target:addMod(MOD_ATT, 7); target:addMod(MOD_DEF, 7); target:addMod(MOD_ACC, 7); target:addMod(MOD_EVA, 7); target:addMod(MOD_STORETP, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 7); target:delMod(MOD_MP, 7); target:delMod(MOD_STR, 7); target:delMod(MOD_DEX, 7); target:delMod(MOD_AGI, 7); target:delMod(MOD_VIT, 7); target:delMod(MOD_INT, 7); target:delMod(MOD_MND, 7); target:delMod(MOD_CHR, 7); target:delMod(MOD_HPHEAL, 7); target:delMod(MOD_MPHEAL, 7); target:delMod(MOD_ATT, 7); target:delMod(MOD_DEF, 7); target:delMod(MOD_ACC, 7); target:delMod(MOD_EVA, 7); target:delMod(MOD_STORETP, 7); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/spells/armys_paeon_vi.lua
4
1390
----------------------------------------- -- Spell: Army's Paeon VI -- Gradually restores target's HP. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 6; if (sLvl+iLvl > 450) then power = power + 1; end local iBoost = caster:getMod(MOD_PAEON_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_PAEON,power,0,duration,caster:getID(), 0, 6)) then spell:setMsg(75); end return EFFECT_PAEON; end;
gpl-3.0
teahouse/FWServer
script/util/luajson.lua
1
15456
----------------------------------------------------------------------------- -- JSON4Lua: JSON encoding / decoding support for the Lua language. -- json Module. -- Author: Craig Mason-Jones -- Homepage: http://json.luaforge.net/ -- Version: 0.9.40 -- This module is released under the MIT License (MIT). -- Please see LICENCE.txt for details. -- -- USAGE: -- This module exposes two functions: -- json.encode(o) -- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string. -- json.decode(json_string) -- Returns a Lua object populated with the data encoded in the JSON string json_string. -- -- REQUIREMENTS: -- compat-5.1 if using Lua 5.0 -- -- CHANGELOG -- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix). -- Fixed Lua 5.1 compatibility issues. -- Introduced json.null to have null values in associative arrays. -- json.encode() performance improvement (more than 50%) through table.concat rather than .. -- Introduced json.decode ability to ignore /**/ comments in the JSON string. -- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Imports and dependencies ----------------------------------------------------------------------------- local math = require('math') local string = require("string") local table = require("table") local base = _G ----------------------------------------------------------------------------- -- Module declaration ----------------------------------------------------------------------------- --module("json") local json = {} -- Public functions -- Private functions local decode_scanArray local decode_scanComment local decode_scanConstant local decode_scanNumber local decode_scanObject local decode_scanString local decode_scanWhitespace local encodeString local isArray local isEncodable local null ----------------------------------------------------------------------------- -- PUBLIC FUNCTIONS ----------------------------------------------------------------------------- --- Encodes an arbitrary Lua object / variable. -- @param v The Lua object / variable to be JSON encoded. -- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode) function json.encode (v) -- Handle nil values if v==nil then return "null" end local vtype = base.type(v) -- Handle strings if vtype=='string' then return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string end -- Handle booleans if vtype=='number' or vtype=='boolean' then return base.tostring(v) end -- Handle tables if vtype=='table' then local rval = {} -- Consider arrays separately local bArray, maxCount = isArray(v) if bArray then for i = 1,maxCount do table.insert(rval, json.encode(v[i])) end else -- An object, not an array for i,j in base.pairs(v) do if isEncodable(i) and isEncodable(j) then table.insert(rval, '"' .. encodeString(i) .. '":' .. json.encode(j)) end end end if bArray then return '[' .. table.concat(rval,',') ..']' else return '{' .. table.concat(rval,',') .. '}' end end -- Handle null values if vtype=='function' and v==null then return 'null' end base.assert(false,'json.encode attempt to json.encode unsupported type ' .. vtype .. ':' .. base.tostring(v)) end --- Decodes a JSON string and returns the decoded value as a Lua data structure / value. -- @param s The string to scan. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil, -- and the position of the first character after -- the scanned JSON object. function json.decode(s, startPos) startPos = startPos and startPos or 1 startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']') local curChar = string.sub(s,startPos,startPos) -- Object if curChar=='{' then return decode_scanObject(s,startPos) end -- Array if curChar=='[' then return decode_scanArray(s,startPos) end -- Number if string.find("+-0123456789.e", curChar, 1, true) then return decode_scanNumber(s,startPos) end -- String if curChar==[["]] or curChar==[[']] then return decode_scanString(s,startPos) end if string.sub(s,startPos,startPos+1)=='/*' then return json.decode(s, decode_scanComment(s,startPos)) end -- Otherwise, it must be a constant return decode_scanConstant(s,startPos) end --- The null function allows one to specify a null value in an associative array (which is otherwise -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null } function json.null() return null -- so json.null() will also return null ;-) end ----------------------------------------------------------------------------- -- Internal, PRIVATE functions. -- Following a Python-like convention, I have prefixed all these 'PRIVATE' -- functions with an underscore. ----------------------------------------------------------------------------- --- Scans an array from JSON into a Lua object -- startPos begins at the start of the array. -- Returns the array and the next starting position -- @param s The string being scanned. -- @param startPos The starting position for the scan. -- @return table, int The scanned array as a table, and the position of the next character to scan. function decode_scanArray(s,startPos) local array = {} -- The return value local stringLen = string.len(s) base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s ) startPos = startPos + 1 -- Infinite loop for array elements repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.') local curChar = string.sub(s,startPos,startPos) if (curChar==']') then return array, startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.') object, startPos = json.decode(s,startPos) table.insert(array,object) until false end --- Scans a comment and discards the comment. -- Returns the position of the next character following the comment. -- @param string s The JSON string to scan. -- @param int startPos The starting position of the comment function decode_scanComment(s, startPos) base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos) local endPos = string.find(s,'*/',startPos+2) base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos) return endPos+2 end --- Scans for given constants: true, false or null -- Returns the appropriate Lua type, and the position of the next character to read. -- @param s The string being scanned. -- @param startPos The position in the string at which to start scanning. -- @return object, int The object (true, false or nil) and the position at which the next character should be -- scanned. function decode_scanConstant(s, startPos) local consts = { ["true"] = true, ["false"] = false, ["null"] = nil } local constNames = {"true","false","null"} for i,k in base.pairs(constNames) do --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k) if string.sub(s,startPos, startPos + string.len(k) -1 )==k then return consts[k], startPos + string.len(k) end end base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos) end --- Scans a number from the JSON encoded string. -- (in fact, also is able to scan numeric +- eqns, which is not -- in the JSON spec.) -- Returns the number, and the position of the next character -- after the number. -- @param s The string being scanned. -- @param startPos The position at which to start scanning. -- @return number, int The extracted number and the position of the next character to scan. function decode_scanNumber(s,startPos) local endPos = startPos+1 local stringLen = string.len(s) local acceptableChars = "+-0123456789.e" while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true) and endPos<=stringLen ) do endPos = endPos + 1 end local stringValue = 'return ' .. string.sub(s,startPos, endPos-1) local stringEval = base.load(stringValue) base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON object into a Lua object. -- startPos begins at the start of the object. -- Returns the object and the next starting position. -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return table, int The scanned object as a table and the position of the next character to scan. function decode_scanObject(s,startPos) local object = {} local stringLen = string.len(s) local key, value base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s) startPos = startPos + 1 repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.') local curChar = string.sub(s,startPos,startPos) if (curChar=='}') then return object,startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.') -- Scan the key key, startPos = json.decode(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos) startPos = decode_scanWhitespace(s,startPos+1) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) value, startPos = json.decode(s,startPos) object[key]=value until false -- infinite loop while key-value pairs are found end --- Scans a JSON string from the opening inverted comma or single quote to the -- end of the string. -- Returns the string extracted as a Lua string, -- and the position of the next non-string character -- (after the closing inverted comma or single quote). -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return string, int The extracted string as a Lua string, and the next character to parse. function decode_scanString(s,startPos) base.assert(startPos, 'decode_scanString(..) called without start position') local startChar = string.sub(s,startPos,startPos) base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string') local escaped = false local endPos = startPos + 1 local bEnded = false local stringLen = string.len(s) repeat local curChar = string.sub(s,endPos,endPos) if not escaped then if curChar==[[\]] then escaped = true else bEnded = curChar==startChar end else -- If we're escaped, we accept the current character come what may escaped = false end endPos = endPos + 1 base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos) until bEnded local stringValue = 'return ' .. string.sub(s, startPos, endPos-1) local stringEval = base.load(stringValue) base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON string skipping all whitespace from the current start position. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached. -- @param s The string being scanned -- @param startPos The starting position where we should begin removing whitespace. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string -- was reached. function decode_scanWhitespace(s,startPos) local whitespace=" \n\r\t" local stringLen = string.len(s) while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do startPos = startPos + 1 end return startPos end --- Encodes a string to be JSON-compatible. -- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-) -- @param s The string to return as a JSON encoded (i.e. backquoted string) -- @return The string appropriately escaped. function encodeString(s) s = string.gsub(s,'\\','\\\\') s = string.gsub(s,'"','\\"') s = string.gsub(s,"'","\\'") s = string.gsub(s,'\n','\\n') s = string.gsub(s,'\t','\\t') return s end -- Determines whether the given Lua type is an array or a table / dictionary. -- We consider any table an array if it has indexes 1..n for its n items, and no -- other data in the table. -- I think this method is currently a little 'flaky', but can't think of a good way around it yet... -- @param t The table to evaluate as an array -- @return boolean, number True if the table can be represented as an array, false otherwise. If true, -- the second returned value is the maximum -- number of indexed elements in the array. function isArray(t) -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable -- (with the possible exception of 'n') local maxIndex = 0 for k,v in base.pairs(t) do if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair if (not isEncodable(v)) then return false end -- All array elements must be encodable maxIndex = math.max(maxIndex,k) else if (k=='n') then if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements else -- Else of (k=='n') if isEncodable(v) then return false end end -- End of (k~='n') end -- End of k,v not an indexed pair end -- End of loop across all pairs return true, maxIndex end --- Determines whether the given Lua object / table / variable can be JSON encoded. The only -- types that are JSON encodable are: string, boolean, number, nil, table and json.null. -- In this implementation, all other types are ignored. -- @param o The object to examine. -- @return boolean True if the object should be JSON encoded, false if it should be ignored. function isEncodable(o) local t = base.type(o) return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null) end return json
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Valkurm_Dunes/npcs/qm4.lua
37
1033
----------------------------------- -- Area: Valkurm Dunes -- NPC: qm4 (???) -- Involved in quest: Pirate's Chart -- @pos -160 4 -131 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MONSTERS_KILLED_ADVENTURERS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Gael-de-Sailly/minetest-minetestforfun-server
mods/profnsched/queue.lua
7
2496
scheduler = {} -- scheduler.queue = {[1]={first=1, last=2, groups={[1]={}, [2]={}}}} scheduler.queue = {[1]={cur={}, nxt={}, ncur=1, nnxt=1}} function scheduler.add(priority, job) -- get asked class local class = scheduler.queue[priority] local p = priority while not class do -- create all classes under 'priority' --scheduler.queue[p] = {first=1, last=2, groups={[1]={}, [2]={}}} scheduler.queue[p] = {cur={}, nxt={}, ncur=1, nnxt=1} p = p-1 class = scheduler.queue[p] end class = scheduler.queue[priority] class.nxt[class.nnxt] = job class.nnxt = class.nnxt+1 -- get last group --local grp = class.groups[class.last] -- add job into last group --grp[#grp+1] = job end function scheduler.asap(priority, func) scheduler.add(priority, { mod_name = core.get_last_run_mod(), func_id = "#"..debug.getinfo(2, "S").linedefined, --imprecis func_code = func, arg = {}, }) end function scheduler.mdebug(s) minetest.debug("[Profnsched] "..s) end function scheduler.shift() local nb = scheduler.waitingjobs() local qnext = nil for class,q in ipairs(scheduler.queue) do q.cur = q.nxt q.nxt = {} q.ncur = q.nnxt q.nnxt = 1 --local tnext = class+1 qnext = scheduler.queue[class+1] if qnext then local src = qnext.cur for i,j in pairs(src) do q.cur[q.ncur] = j q.ncur = q.ncur+1 src[i] = nil end qnext.cur = {} qnext.ncur = 1 end end --[[ q.groups[q.first] = q.groups[q.last] q.groups[q.last] = {} local tnext = class+1 tnext = scheduler.queue[tnext] if tnext then tsrc = tnext.groups[tnext.first] tdst = q.groups[q.first] for i,j in pairs(tsrc) do tdst[#tdst+1] = j tsrc[i] = nil end end end]] if nb ~= scheduler.waitingjobs() then --This should never happen, left because it was used during debug phase mdebug("ERROR, This should never happen ! Lost jobs, some mod may not work from now, please restart the server.") end -- end function scheduler.fulldebug() minetest.log("[Profnsched]"..#scheduler.queue.." classes") for class,q in pairs(scheduler.queue) do minetest.log("[Profnsched] class "..class..":") minetest.log("[Profnsched] current "..q.ncur) minetest.log("[Profnsched] next "..q.nnxt) end minetest.log("[Profnsched] end") end function scheduler.waitingjobs() local n = 0 for class, q in pairs(scheduler.queue) do for i,grp in pairs(q.cur) do n = n+1 end for i,grp in pairs(q.nxt) do n = n+1 end end return n end
unlicense
gitfancode/skynet
lualib/socketchannel.lua
3
9639
local skynet = require "skynet" local socket = require "socket" local socketdriver = require "socketdriver" -- channel support auto reconnect , and capture socket error in request/response transaction -- { host = "", port = , auth = function(so) , response = function(so) session, data } local socket_channel = {} local channel = {} local channel_socket = {} local channel_meta = { __index = channel } local channel_socket_meta = { __index = channel_socket, __gc = function(cs) local fd = cs[1] cs[1] = false if fd then socket.shutdown(fd) end end } local socket_error = setmetatable({}, {__tostring = function() return "[Error: socket]" end }) -- alias for error object socket_channel.error = socket_error function socket_channel.channel(desc) local c = { __host = assert(desc.host), __port = assert(desc.port), __backup = desc.backup, __auth = desc.auth, __response = desc.response, -- It's for session mode __request = {}, -- request seq { response func or session } -- It's for order mode __thread = {}, -- coroutine seq or session->coroutine map __result = {}, -- response result { coroutine -> result } __result_data = {}, __connecting = {}, __sock = false, __closed = false, __authcoroutine = false, __nodelay = desc.nodelay, } return setmetatable(c, channel_meta) end local function close_channel_socket(self) if self.__sock then local so = self.__sock self.__sock = false -- never raise error pcall(socket.close,so[1]) end end local function wakeup_all(self, errmsg) if self.__response then for k,co in pairs(self.__thread) do self.__thread[k] = nil self.__result[co] = socket_error self.__result_data[co] = errmsg skynet.wakeup(co) end else for i = 1, #self.__request do self.__request[i] = nil end for i = 1, #self.__thread do local co = self.__thread[i] self.__thread[i] = nil self.__result[co] = socket_error self.__result_data[co] = errmsg skynet.wakeup(co) end end end local function dispatch_by_session(self) local response = self.__response -- response() return session while self.__sock do local ok , session, result_ok, result_data, padding = pcall(response, self.__sock) if ok and session then local co = self.__thread[session] if co then if padding and result_ok then -- If padding is true, append result_data to a table (self.__result_data[co]) local result = self.__result_data[co] or {} self.__result_data[co] = result table.insert(result, result_data) else self.__thread[session] = nil self.__result[co] = result_ok if result_ok and self.__result_data[co] then table.insert(self.__result_data[co], result_data) else self.__result_data[co] = result_data end skynet.wakeup(co) end else self.__thread[session] = nil skynet.error("socket: unknown session :", session) end else close_channel_socket(self) local errormsg if session ~= socket_error then errormsg = session end wakeup_all(self, errormsg) end end end local function pop_response(self) while true do local func,co = table.remove(self.__request, 1), table.remove(self.__thread, 1) if func then return func, co end self.__wait_response = coroutine.running() skynet.wait(self.__wait_response) end end local function push_response(self, response, co) if self.__response then -- response is session self.__thread[response] = co else -- response is a function, push it to __request table.insert(self.__request, response) table.insert(self.__thread, co) if self.__wait_response then skynet.wakeup(self.__wait_response) self.__wait_response = nil end end end local function dispatch_by_order(self) while self.__sock do local func, co = pop_response(self) local ok, result_ok, result_data, padding = pcall(func, self.__sock) if ok then if padding and result_ok then -- if padding is true, wait for next result_data -- self.__result_data[co] is a table local result = self.__result_data[co] or {} self.__result_data[co] = result table.insert(result, result_data) else self.__result[co] = result_ok if result_ok and self.__result_data[co] then table.insert(self.__result_data[co], result_data) else self.__result_data[co] = result_data end skynet.wakeup(co) end else close_channel_socket(self) local errmsg if result_ok ~= socket_error then errmsg = result_ok end self.__result[co] = socket_error self.__result_data[co] = errmsg skynet.wakeup(co) wakeup_all(self, errmsg) end end end local function dispatch_function(self) if self.__response then return dispatch_by_session else return dispatch_by_order end end local function connect_backup(self) if self.__backup then for _, addr in ipairs(self.__backup) do local host, port if type(addr) == "table" then host, port = addr.host, addr.port else host = addr port = self.__port end skynet.error("socket: connect to backup host", host, port) local fd = socket.open(host, port) if fd then self.__host = host self.__port = port return fd end end end end local function connect_once(self) if self.__closed then return false end assert(not self.__sock and not self.__authcoroutine) local fd,err = socket.open(self.__host, self.__port) if not fd then fd = connect_backup(self) if not fd then return false, err end end if self.__nodelay then socketdriver.nodelay(fd) end self.__sock = setmetatable( {fd} , channel_socket_meta ) skynet.fork(dispatch_function(self), self) if self.__auth then self.__authcoroutine = coroutine.running() local ok , message = pcall(self.__auth, self) if not ok then close_channel_socket(self) if message ~= socket_error then self.__authcoroutine = false skynet.error("socket: auth failed", message) end end self.__authcoroutine = false if ok and not self.__sock then -- auth may change host, so connect again return connect_once(self) end return ok end return true end local function try_connect(self , once) local t = 0 while not self.__closed do local ok, err = connect_once(self) if ok then if not once then skynet.error("socket: connect to", self.__host, self.__port) end return elseif once then return err else skynet.error("socket: connect", err) end if t > 1000 then skynet.error("socket: try to reconnect", self.__host, self.__port) skynet.sleep(t) t = 0 else skynet.sleep(t) end t = t + 100 end end local function check_connection(self) if self.__sock then local authco = self.__authcoroutine if not authco then return true end if authco == coroutine.running() then -- authing return true end end if self.__closed then return false end end local function block_connect(self, once) local r = check_connection(self) if r ~= nil then return r end local err if #self.__connecting > 0 then -- connecting in other coroutine local co = coroutine.running() table.insert(self.__connecting, co) skynet.wait(co) else self.__connecting[1] = true err = try_connect(self, once) self.__connecting[1] = nil for i=2, #self.__connecting do local co = self.__connecting[i] self.__connecting[i] = nil skynet.wakeup(co) end end r = check_connection(self) if r == nil then error(string.format("Connect to %s:%d failed (%s)", self.__host, self.__port, err)) else return r end end function channel:connect(once) if self.__closed then self.__closed = false end return block_connect(self, once) end local function wait_for_response(self, response) local co = coroutine.running() push_response(self, response, co) skynet.wait(co) local result = self.__result[co] self.__result[co] = nil local result_data = self.__result_data[co] self.__result_data[co] = nil if result == socket_error then if result_data then error(result_data) else error(socket_error) end else assert(result, result_data) return result_data end end local socket_write = socket.write local socket_lwrite = socket.lwrite function channel:request(request, response, padding) assert(block_connect(self, true)) -- connect once local fd = self.__sock[1] if padding then -- padding may be a table, to support multi part request -- multi part request use low priority socket write -- socket_lwrite returns nothing socket_lwrite(fd , request) for _,v in ipairs(padding) do socket_lwrite(fd, v) end else if not socket_write(fd , request) then close_channel_socket(self) wakeup_all(self) error(socket_error) end end if response == nil then -- no response return end return wait_for_response(self, response) end function channel:response(response) assert(block_connect(self)) return wait_for_response(self, response) end function channel:close() if not self.__closed then self.__closed = true close_channel_socket(self) end end function channel:changehost(host, port) self.__host = host if port then self.__port = port end if not self.__closed then close_channel_socket(self) end end function channel:changebackup(backup) self.__backup = backup end channel_meta.__gc = channel.close local function wrapper_socket_function(f) return function(self, ...) local result = f(self[1], ...) if not result then error(socket_error) else return result end end end channel_socket.read = wrapper_socket_function(socket.read) channel_socket.readline = wrapper_socket_function(socket.readline) return socket_channel
mit
hacker44-h44/1104
vir/Get.lua
15
1052
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = '> '..text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found variable' else return value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "View Saved Variables With !set", usage = { "/get : view all variables", "/get (value) : view variable", }, patterns = { "^([!/]get) (.+)$", "^[!/]get$" }, run = run }
gpl-2.0
mahdikord/mahdihop
plugins/banhammer.lua
13
11897
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^([Bb]anall) (.*)$", "^([Bb]anall)$", "^([Bb]anlist) (.*)$", "^([Bb]anlist)$", "^([Gg]banlist)$", "^([Bb]an) (.*)$", "^([Kk]ick)$", "^([Uu]nban) (.*)$", "^([Uu]nbanall) (.*)$", "^([Uu]nbanall)$", "^([Kk]ick) (.*)$", "^([Kk]ickme)$", "^([Bb]an)$", "^([Uu]nban)$", "^([Ii][Dd])$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Lower_Jeuno/npcs/_l02.lua
36
1562
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- @zone 245 -- @pos -89.022 -0 -123.317 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); if (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then if (player:getVar("cService") == 9) then player:setVar("cService",10); end elseif (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (player:getVar("cService") == 22) then player:setVar("cService",23); end end end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Norg/npcs/Heizo.lua
19
3109
----------------------------------- -- Area: Norg -- NPC: Heizo -- Starts and Ends Quest: Like Shining Leggings -- @pos -1 -5 25 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) ShiningLeggings = player:getQuestStatus(OUTLANDS,LIKE_A_SHINING_LEGGINGS); Legging = trade:getItemQty(14117); if(Legging > 0 and Legging == trade:getItemCount()) then TurnedInVar = player:getVar("shiningLeggings_nb"); if(ShiningLeggings == QUEST_ACCEPTED and TurnedInVar + Legging >= 10) then -- complete quest player:startEvent(0x0081); elseif(ShiningLeggings == QUEST_ACCEPTED and TurnedInVar <= 9) then -- turning in less than the amount needed to finish the quest TotalLeggings = Legging + TurnedInVar player:tradeComplete(); player:setVar("shiningLeggings_nb",TotalLeggings); player:startEvent(0x0080,TotalLeggings); -- Update player on number of leggings turned in end else if(ShiningLeggings == QUEST_ACCEPTED) then player:startEvent(0x0080,TotalLeggings); -- Update player on number of leggings turned in, but doesn't accept anything other than leggings else player:startEvent(0x007e); -- Give standard conversation if items are traded but no quest is accepted end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) ShiningLeggings = player:getQuestStatus(OUTLANDS,LIKE_A_SHINING_LEGGINGS); if(ShiningLeggings == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3) then player:startEvent(0x007f); -- Start Like Shining Leggings elseif(ShiningLeggings == QUEST_ACCEPTED) then player:startEvent(0x0080,player:getVar("shiningSubligar_nb")); -- Update player on number of Leggings turned in else player:startEvent(0x007e); -- Standard Conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x007f) then player:addQuest(OUTLANDS,LIKE_A_SHINING_LEGGINGS); elseif (csid == 0x0081) then player:tradeComplete(); player:addItem(4958); -- Scroll of Dokumori: Ichi player:messageSpecial(ITEM_OBTAINED, 4958); -- Scroll of Dokumori: Ichi player:addFame(OUTLANDS,NORG_FAME*100); player:addTitle(LOOKS_GOOD_IN_LEGGINGS); player:setVar("shiningLeggings_nb",0); player:completeQuest(OUTLANDS,LIKE_A_SHINING_LEGGINGS); end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Nashmau/npcs/Yoyoroon.lua
34
1613
----------------------------------- -- Area: Nashmau -- NPC: Yoyoroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,YOYOROON_SHOP_DIALOG); stock = {0x08BF,4940, -- Tension Spring 0x08C0,9925, -- Inhibitor 0x08C2,9925, -- Mana Booster 0x08C3,4940, -- Loudspeaker 0x08C6,4940, -- Accelerator 0x08C7,9925, -- Scope 0x08CA,9925, -- Shock Absorber 0x08CB,4940, -- Armor Plate 0x08CE,4940, -- Stabilizer 0x08CF,9925, -- Volt Gun 0x08D2,4940, -- Mana Jammer 0x08D4,9925, -- Stealth Screen 0x08D6,4940, -- Auto-Repair Kit 0x08D8,9925, -- Damage Gauge 0x08DA,4940, -- Mana Tank 0x08DC,9925} -- Mana Conserver showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
sjznxd/lc-20130127
applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-codec.lua
80
2172
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true codec_a_mu = module:option(ListValue, "codec_a_mu", "A-law and Mulaw direct Coder/Decoder", "") codec_a_mu:value("yes", "Load") codec_a_mu:value("no", "Do Not Load") codec_a_mu:value("auto", "Load as Required") codec_a_mu.rmempty = true codec_adpcm = module:option(ListValue, "codec_adpcm", "Adaptive Differential PCM Coder/Decoder", "") codec_adpcm:value("yes", "Load") codec_adpcm:value("no", "Do Not Load") codec_adpcm:value("auto", "Load as Required") codec_adpcm.rmempty = true codec_alaw = module:option(ListValue, "codec_alaw", "A-law Coder/Decoder", "") codec_alaw:value("yes", "Load") codec_alaw:value("no", "Do Not Load") codec_alaw:value("auto", "Load as Required") codec_alaw.rmempty = true codec_g726 = module:option(ListValue, "codec_g726", "ITU G.726-32kbps G726 Transcoder", "") codec_g726:value("yes", "Load") codec_g726:value("no", "Do Not Load") codec_g726:value("auto", "Load as Required") codec_g726.rmempty = true codec_gsm = module:option(ListValue, "codec_gsm", "GSM/PCM16 (signed linear) Codec Translation", "") codec_gsm:value("yes", "Load") codec_gsm:value("no", "Do Not Load") codec_gsm:value("auto", "Load as Required") codec_gsm.rmempty = true codec_speex = module:option(ListValue, "codec_speex", "Speex/PCM16 (signed linear) Codec Translator", "") codec_speex:value("yes", "Load") codec_speex:value("no", "Do Not Load") codec_speex:value("auto", "Load as Required") codec_speex.rmempty = true codec_ulaw = module:option(ListValue, "codec_ulaw", "Mu-law Coder/Decoder", "") codec_ulaw:value("yes", "Load") codec_ulaw:value("no", "Do Not Load") codec_ulaw:value("auto", "Load as Required") codec_ulaw.rmempty = true return cbimap
apache-2.0
subzrk/BadRotations
Libs/LibRangeCheck-2.0/LibRangeCheck-2.0.lua
6
32636
--[[ Name: LibRangeCheck-2.0 Revision: $Revision: 168 $ Author(s): mitch0 Website: http://www.wowace.com/projects/librangecheck-2-0/ Description: A range checking library based on interact distances and spell ranges Dependencies: LibStub License: Public Domain ]] --- LibRangeCheck-2.0 provides an easy way to check for ranges and get suitable range checking functions for specific ranges.\\ -- The checkers use spell and item range checks, or interact based checks for special units where those two cannot be used.\\ -- The lib handles the refreshing of checker lists in case talents / spells / glyphs change and in some special cases when equipment changes (for example some of the mage pvp gloves change the range of the Fire Blast spell), and also handles the caching of items used for item-based range checks.\\ -- A callback is provided for those interested in checker changes. -- @usage -- local rc = LibStub("LibRangeCheck-2.0") -- -- rc.RegisterCallback(self, rc.CHECKERS_CHANGED, function() print("need to refresh my stored checkers") end) -- -- local minRange, maxRange = rc:GetRange('target') -- if not minRange then -- print("cannot get range estimate for target") -- elseif not maxRange then -- print("target is over " .. minRange .. " yards") -- else -- print("target is between " .. minRange .. " and " .. maxRange .. " yards") -- end -- -- local meleeChecker = rc:GetFriendMaxChecker(rc.MeleeRange) -- 5 yds -- for i = 1, 4 do -- -- TODO: check if unit is valid, etc -- if meleeChecker("party" .. i) then -- print("Party member " .. i .. " is in Melee range") -- end -- end -- -- local safeDistanceChecker = rc:GetHarmMinChecker(30) -- -- negate the result of the checker! -- local isSafelyAway = not safeDistanceChecker('target') -- -- @class file -- @name LibRangeCheck-2.0 local MAJOR_VERSION = "LibRangeCheck-2.0" local MINOR_VERSION = tonumber(("$Revision: 168 $"):match("%d+")) + 100000 local lib, oldminor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION) if not lib then return end -- << STATIC CONFIG local UpdateDelay = .5 local ItemRequestTimeout = 10.0 -- interact distance based checks. ranges are based on my own measurements (thanks for all the folks who helped me with this) local DefaultInteractList = { [3] = 8, [2] = 9, [4] = 28, } -- interact list overrides for races local InteractLists = { ["Tauren"] = { [3] = 6, [2] = 7, [4] = 25, }, ["Scourge"] = { [3] = 7, [2] = 8, [4] = 27, }, } local MeleeRange = 5 -- list of friendly spells that have different ranges local FriendSpells = {} -- list of harmful spells that have different ranges local HarmSpells = {} FriendSpells["DEATHKNIGHT"] = { 47541, -- ["Death Coil"], -- 40 } HarmSpells["DEATHKNIGHT"] = { 47541, -- ["Death Coil"], -- 40 49576, -- ["Death Grip"], -- 30 } FriendSpells["DEMONHUNTER"] = { } HarmSpells["DEMONHUNTER"] = { 185123, -- ["Throw Glaive"], -- 30 } FriendSpells["DRUID"] = { 774, -- ["Rejuvenation"], -- 40 2782, -- ["Remove Corruption"], -- 40 } HarmSpells["DRUID"] = { 5176, -- ["Wrath"], -- 40 339, -- ["Entangling Roots"], -- 35 6795, -- ["Growl"], -- 30 33786, -- ["Cyclone"], -- 20 106839, -- ["Skull Bash"], -- 13 22568, -- ["Ferocious Bite"], -- 5 } FriendSpells["HUNTER"] = {} HarmSpells["HUNTER"] = { 75, -- ["Auto Shot"], -- 40 } FriendSpells["MAGE"] = { } HarmSpells["MAGE"] = { 44614, --["Frostfire Bolt"], -- 40 5019, -- ["Shoot"], -- 30 } FriendSpells["MONK"] = { 115450, -- ["Detox"], -- 40 115546, -- ["Provoke"], -- 30 } HarmSpells["MONK"] = { 115546, -- ["Provoke"], -- 30 115078, -- ["Paralysis"], -- 20 100780, -- ["Tiger Palm"], -- 5 } FriendSpells["PALADIN"] = { 19750, -- ["Flash of Light"], -- 40 } HarmSpells["PALADIN"] = { 62124, -- ["Reckoning"], -- 30 20271, -- ["Judgement"], -- 30 853, -- ["Hammer of Justice"], -- 10 35395, -- ["Crusader Strike"], -- 5 } FriendSpells["PRIEST"] = { 527, -- ["Purify"], -- 40 17, -- ["Power Word: Shield"], -- 40 } HarmSpells["PRIEST"] = { 589, -- ["Shadow Word: Pain"], -- 40 5019, -- ["Shoot"], -- 30 } FriendSpells["ROGUE"] = {} HarmSpells["ROGUE"] = { 2764, -- ["Throw"], -- 30 2094, -- ["Blind"], -- 15 } FriendSpells["SHAMAN"] = { 8004, -- ["Healing Surge"], -- 40 546, -- ["Water Walking"], -- 30 } HarmSpells["SHAMAN"] = { 403, -- ["Lightning Bolt"], -- 40 370, -- ["Purge"], -- 30 73899, -- ["Primal Strike"],. -- 5 } FriendSpells["WARRIOR"] = {} HarmSpells["WARRIOR"] = { 355, -- ["Taunt"], -- 30 100, -- ["Charge"], -- 8-25 5246, -- ["Intimidating Shout"], -- 8 } FriendSpells["WARLOCK"] = { 5697, -- ["Unending Breath"], -- 30 } HarmSpells["WARLOCK"] = { 686, -- ["Shadow Bolt"], -- 40 5019, -- ["Shoot"], -- 30 } -- Items [Special thanks to Maldivia for the nice list] local FriendItems = { [5] = { 37727, -- Ruby Acorn }, [6] = { 63427, -- Worgsaw }, [8] = { 34368, -- Attuned Crystal Cores 33278, -- Burning Torch }, [10] = { 32321, -- Sparrowhawk Net }, [15] = { 1251, -- Linen Bandage 2581, -- Heavy Linen Bandage 3530, -- Wool Bandage 3531, -- Heavy Wool Bandage 6450, -- Silk Bandage 6451, -- Heavy Silk Bandage 8544, -- Mageweave Bandage 8545, -- Heavy Mageweave Bandage 14529, -- Runecloth Bandage 14530, -- Heavy Runecloth Bandage 21990, -- Netherweave Bandage 21991, -- Heavy Netherweave Bandage 34721, -- Frostweave Bandage 34722, -- Heavy Frostweave Bandage -- 38643, -- Thick Frostweave Bandage -- 38640, -- Dense Frostweave Bandage }, [20] = { 21519, -- Mistletoe }, [25] = { 31463, -- Zezzak's Shard }, [30] = { 1180, -- Scroll of Stamina 1478, -- Scroll of Protection II 3012, -- Scroll of Agility 1712, -- Scroll of Spirit II 2290, -- Scroll of Intellect II 1711, -- Scroll of Stamina II 34191, -- Handful of Snowflakes }, [35] = { 18904, -- Zorbin's Ultra-Shrinker }, [40] = { 34471, -- Vial of the Sunwell }, [45] = { 32698, -- Wrangling Rope }, [50] = { 116139, -- Haunting Memento }, [60] = { 32825, -- Soul Cannon 37887, -- Seeds of Nature's Wrath }, [70] = { 41265, -- Eyesore Blaster }, [80] = { 35278, -- Reinforced Net }, } local HarmItems = { [5] = { 37727, -- Ruby Acorn }, [6] = { 63427, -- Worgsaw }, [8] = { 34368, -- Attuned Crystal Cores 33278, -- Burning Torch }, [10] = { 32321, -- Sparrowhawk Net }, [15] = { 33069, -- Sturdy Rope }, [20] = { 10645, -- Gnomish Death Ray }, [25] = { 24268, -- Netherweave Net 41509, -- Frostweave Net 31463, -- Zezzak's Shard }, [30] = { 835, -- Large Rope Net 7734, -- Six Demon Bag 34191, -- Handful of Snowflakes }, [35] = { 24269, -- Heavy Netherweave Net 18904, -- Zorbin's Ultra-Shrinker }, [40] = { 28767, -- The Decapitator }, [45] = { -- 32698, -- Wrangling Rope 23836, -- Goblin Rocket Launcher }, [50] = { 116139, -- Haunting Memento }, [60] = { 32825, -- Soul Cannon 37887, -- Seeds of Nature's Wrath }, [70] = { 41265, -- Eyesore Blaster }, [80] = { 35278, -- Reinforced Net }, [100] = { 33119, -- Malister's Frost Wand }, } -- This could've been done by checking player race as well and creating tables for those, but it's easier like this for k, v in pairs(FriendSpells) do tinsert(v, 28880) -- ["Gift of the Naaru"] end -- >> END OF STATIC CONFIG -- cache local setmetatable = setmetatable local tonumber = tonumber local pairs = pairs local tostring = tostring local print = print local next = next local type = type local wipe = wipe local tinsert = tinsert local tremove = tremove local BOOKTYPE_SPELL = BOOKTYPE_SPELL local GetSpellInfo = GetSpellInfo local GetSpellBookItemName = GetSpellBookItemName local GetNumSpellTabs = GetNumSpellTabs local GetSpellTabInfo = GetSpellTabInfo local GetItemInfo = GetItemInfo local UnitAura = UnitAura local UnitCanAttack = UnitCanAttack local UnitCanAssist = UnitCanAssist local UnitExists = UnitExists local UnitIsDeadOrGhost = UnitIsDeadOrGhost local CheckInteractDistance = CheckInteractDistance local IsSpellInRange = IsSpellInRange local IsItemInRange = IsItemInRange local UnitClass = UnitClass local UnitRace = UnitRace local GetInventoryItemLink = GetInventoryItemLink local GetSpecialization = GetSpecialization local GetSpecializationInfo = GetSpecializationInfo local GetTime = GetTime local HandSlotId = GetInventorySlotInfo("HandsSlot") local math_floor = math.floor -- temporary stuff local itemRequestTimeoutAt local foundNewItems local cacheAllItems local friendItemRequests local harmItemRequests local lastUpdate = 0 -- minRangeCheck is a function to check if spells with minimum range are really out of range, or fail due to range < minRange. See :init() for its setup local minRangeCheck = function(unit) return CheckInteractDistance(unit, 2) end local checkers_Spell = setmetatable({}, { __index = function(t, spellIdx) local func = function(unit) if IsSpellInRange(spellIdx, BOOKTYPE_SPELL, unit) == 1 then return true end end t[spellIdx] = func return func end }) local checkers_SpellWithMin = setmetatable({}, { __index = function(t, spellIdx) local func = function(unit) if IsSpellInRange(spellIdx, BOOKTYPE_SPELL, unit) == 1 then return true elseif minRangeCheck(unit) then return true, true end end t[spellIdx] = func return func end }) local checkers_Item = setmetatable({}, { __index = function(t, item) local func = function(unit) return IsItemInRange(item, unit) end t[item] = func return func end }) local checkers_Interact = setmetatable({}, { __index = function(t, index) local func = function(unit) if CheckInteractDistance(unit, index) then return true end end t[index] = func return func end }) -- helper functions local function copyTable(src, dst) if type(dst) ~= "table" then dst = {} end if type(src) == "table" then for k, v in pairs(src) do if type(v) == "table" then v = copyTable(v, dst[k]) end dst[k] = v end end return dst end local function initItemRequests(cacheAll) friendItemRequests = copyTable(FriendItems) harmItemRequests = copyTable(HarmItems) cacheAllItems = cacheAll foundNewItems = nil end local function getNumSpells() local _, _, offset, numSpells = GetSpellTabInfo(GetNumSpellTabs()) return offset + numSpells end -- return the spellIndex of the given spell by scanning the spellbook local function findSpellIdx(spellName) if not spellName or spellName == "" then return nil end for i = 1, getNumSpells() do local spell, rank = GetSpellBookItemName(i, BOOKTYPE_SPELL) if spell == spellName then return i end end return nil end -- minRange should be nil if there's no minRange, not 0 local function addChecker(t, range, minRange, checker) local rc = { ["range"] = range, ["minRange"] = minRange, ["checker"] = checker } for i = 1, #t do local v = t[i] if rc.range == v.range then return end if rc.range > v.range then tinsert(t, i, rc) return end end tinsert(t, rc) end local function createCheckerList(spellList, itemList, interactList) local res = {} if spellList then for i = 1, #spellList do local sid = spellList[i] local name, _, _, _, minRange, range = GetSpellInfo(sid) local spellIdx = findSpellIdx(name) if spellIdx and range then minRange = math_floor(minRange + 0.5) range = math_floor(range + 0.5) -- print("### spell: " .. tostring(name) .. ", " .. tostring(minRange) .. " - " .. tostring(range)) if minRange == 0 then -- getRange() expects minRange to be nil in this case minRange = nil end if range == 0 then range = MeleeRange end if minRange then addChecker(res, range, minRange, checkers_SpellWithMin[spellIdx]) else addChecker(res, range, minRange, checkers_Spell[spellIdx]) end end end end if itemList then for range, items in pairs(itemList) do for i = 1, #items do local item = items[i] if GetItemInfo(item) then addChecker(res, range, nil, checkers_Item[item]) break end end end end if interactList and not next(res) then for index, range in pairs(interactList) do addChecker(res, range, nil, checkers_Interact[index]) end end return res end -- returns minRange, maxRange or nil local function getRange(unit, checkerList) local min, max = 0, nil for i = 1, #checkerList do local rc = checkerList[i] if not max or max > rc.range then if rc.minRange then local inRange, inMinRange = rc.checker(unit) if inMinRange then max = rc.minRange elseif inRange then min, max = rc.minRange, rc.range elseif min > rc.range then return min, max else return rc.range, max end elseif rc.checker(unit) then max = rc.range elseif min > rc.range then return min, max else return rc.range, max end end end return min, max end local function updateCheckers(origList, newList) if #origList ~= #newList then wipe(origList) copyTable(newList, origList) return true end for i = 1, #origList do if origList[i].range ~= newList[i].range or origList[i].checker ~= newList[i].checker then wipe(origList) copyTable(newList, origList) return true end end end local function rcIterator(checkerList) local curr = #checkerList return function() local rc = checkerList[curr] if not rc then return nil end curr = curr - 1 return rc.range, rc.checker end end local function getMinChecker(checkerList, range) local checker, checkerRange for i = 1, #checkerList do local rc = checkerList[i] if rc.range < range then return checker, checkerRange end checker, checkerRange = rc.checker, rc.range end return checker, checkerRange end local function getMaxChecker(checkerList, range) for i = 1, #checkerList do local rc = checkerList[i] if rc.range <= range then return rc.checker, rc.range end end end local function getChecker(checkerList, range) for i = 1, #checkerList do local rc = checkerList[i] if rc.range == range then return rc.checker end end end local function null() end local function createSmartChecker(friendChecker, harmChecker, miscChecker) miscChecker = miscChecker or null friendChecker = friendChecker or miscChecker harmChecker = harmChecker or miscChecker return function(unit) if not UnitExists(unit) then return nil end if UnitIsDeadOrGhost(unit) then return miscChecker(unit) end if UnitCanAttack("player", unit) then return harmChecker(unit) elseif UnitCanAssist("player", unit) then return friendChecker(unit) else return miscChecker(unit) end end end -- OK, here comes the actual lib -- pre-initialize the checkerLists here so that we can return some meaningful result even if -- someone manages to call us before we're properly initialized. miscRC should be independent of -- race/class/talents, so it's safe to initialize it here -- friendRC and harmRC will be properly initialized later when we have all the necessary data for them lib.checkerCache_Spell = lib.checkerCache_Spell or {} lib.checkerCache_Item = lib.checkerCache_Item or {} lib.miscRC = createCheckerList(nil, nil, DefaultInteractList) lib.friendRC = createCheckerList(nil, nil, DefaultInteractList) lib.harmRC = createCheckerList(nil, nil, DefaultInteractList) lib.failedItemRequests = {} -- << Public API --- The callback name that is fired when checkers are changed. -- @field lib.CHECKERS_CHANGED = "CHECKERS_CHANGED" -- "export" it, maybe someone will need it for formatting --- Constant for Melee range (5yd). -- @field lib.MeleeRange = MeleeRange function lib:findSpellIndex(spell) if type(spell) == 'number' then spell = GetSpellInfo(spell) end return findSpellIdx(spell) end -- returns the range estimate as a string -- deprecated, use :getRange(unit) instead and build your own strings -- (checkVisible is not used any more, kept for compatibility only) function lib:getRangeAsString(unit, checkVisible, showOutOfRange) local minRange, maxRange = self:getRange(unit) if not minRange then return nil end if not maxRange then return showOutOfRange and minRange .. " +" or nil end return minRange .. " - " .. maxRange end -- initialize RangeCheck if not yet initialized or if "forced" function lib:init(forced) if self.initialized and (not forced) then return end self.initialized = true local _, playerClass = UnitClass("player") local _, playerRace = UnitRace("player") minRangeCheck = nil -- first try to find a nice item we can use for minRangeCheck if HarmItems[15] then local items = HarmItems[15] for i = 1, #items do local item = items[i] if GetItemInfo(item) then minRangeCheck = function(unit) return IsItemInRange(item, unit) end break end end end if not minRangeCheck then -- ok, then try to find some class specific spell if playerClass == "WARRIOR" then -- for warriors, use Intimidating Shout if available local name = GetSpellInfo(5246) -- ["Intimidating Shout"] local spellIdx = findSpellIdx(name) if spellIdx then minRangeCheck = function(unit) return (IsSpellInRange(spellIdx, BOOKTYPE_SPELL, unit) == 1) end end elseif playerClass == "ROGUE" then -- for rogues, use Blind if available local name = GetSpellInfo(2094) -- ["Blind"] local spellIdx = findSpellIdx(name) if spellIdx then minRangeCheck = function(unit) return (IsSpellInRange(spellIdx, BOOKTYPE_SPELL, unit) == 1) end end end end if not minRangeCheck then -- fall back to interact distance checks if playerClass == "HUNTER" or playerRace == "Tauren" then -- for hunters, use interact4 as it's safer -- for Taurens interact4 is actually closer than 25yd and interact2 is closer than 8yd, so we can't use that minRangeCheck = checkers_Interact[4] else minRangeCheck = checkers_Interact[2] end end local interactList = InteractLists[playerRace] or DefaultInteractList self.handSlotItem = GetInventoryItemLink("player", HandSlotId) local changed = false if updateCheckers(self.friendRC, createCheckerList(FriendSpells[playerClass], FriendItems, interactList)) then changed = true end if updateCheckers(self.harmRC, createCheckerList(HarmSpells[playerClass], HarmItems, interactList)) then changed = true end if updateCheckers(self.miscRC, createCheckerList(nil, nil, interactList)) then changed = true end if changed and self.callbacks then self.callbacks:Fire(self.CHECKERS_CHANGED) end end --- Return an iterator for checkers usable on friendly units as (**range**, **checker**) pairs. function lib:GetFriendCheckers() return rcIterator(self.friendRC) end --- Return an iterator for checkers usable on enemy units as (**range**, **checker**) pairs. function lib:GetHarmCheckers() return rcIterator(self.harmRC) end --- Return an iterator for checkers usable on miscellaneous units as (**range**, **checker**) pairs. These units are neither enemy nor friendly, such as people in sanctuaries or corpses. function lib:GetMiscCheckers() return rcIterator(self.miscRC) end --- Return a checker suitable for out-of-range checking on friendly units, that is, a checker whose range is equal or larger than the requested range. -- @param range the range to check for. -- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for. function lib:GetFriendMinChecker(range) return getMinChecker(self.friendRC, range) end --- Return a checker suitable for out-of-range checking on enemy units, that is, a checker whose range is equal or larger than the requested range. -- @param range the range to check for. -- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for. function lib:GetHarmMinChecker(range) return getMinChecker(self.harmRC, range) end --- Return a checker suitable for out-of-range checking on miscellaneous units, that is, a checker whose range is equal or larger than the requested range. -- @param range the range to check for. -- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for. function lib:GetMiscMinChecker(range) return getMinChecker(self.miscRC, range) end --- Return a checker suitable for in-range checking on friendly units, that is, a checker whose range is equal or smaller than the requested range. -- @param range the range to check for. -- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for. function lib:GetFriendMaxChecker(range) return getMaxChecker(self.friendRC, range) end --- Return a checker suitable for in-range checking on enemy units, that is, a checker whose range is equal or smaller than the requested range. -- @param range the range to check for. -- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for. function lib:GetHarmMaxChecker(range) return getMaxChecker(self.harmRC, range) end --- Return a checker suitable for in-range checking on miscellaneous units, that is, a checker whose range is equal or smaller than the requested range. -- @param range the range to check for. -- @return **checker**, **range** pair or **nil** if no suitable checker is available. **range** is the actual range the returned **checker** checks for. function lib:GetMiscMaxChecker(range) return getMaxChecker(self.miscRC, range) end --- Return a checker for the given range for friendly units. -- @param range the range to check for. -- @return **checker** function or **nil** if no suitable checker is available. function lib:GetFriendChecker(range) return getChecker(self.friendRC, range) end --- Return a checker for the given range for enemy units. -- @param range the range to check for. -- @return **checker** function or **nil** if no suitable checker is available. function lib:GetHarmChecker(range) return getChecker(self.harmRC, range) end --- Return a checker for the given range for miscellaneous units. -- @param range the range to check for. -- @return **checker** function or **nil** if no suitable checker is available. function lib:GetMiscChecker(range) return getChecker(self.miscRC, range) end --- Return a checker suitable for out-of-range checking that checks the unit type and calls the appropriate checker (friend/harm/misc). -- @param range the range to check for. -- @return **checker** function. function lib:GetSmartMinChecker(range) return createSmartChecker( getMinChecker(self.friendRC, range), getMinChecker(self.harmRC, range), getMinChecker(self.miscRC, range)) end --- Return a checker suitable for in-of-range checking that checks the unit type and calls the appropriate checker (friend/harm/misc). -- @param range the range to check for. -- @return **checker** function. function lib:GetSmartMaxChecker(range) return createSmartChecker( getMaxChecker(self.friendRC, range), getMaxChecker(self.harmRC, range), getMaxChecker(self.miscRC, range)) end --- Return a checker for the given range that checks the unit type and calls the appropriate checker (friend/harm/misc). -- @param range the range to check for. -- @param fallback optional fallback function that gets called as fallback(unit) if a checker is not available for the given type (friend/harm/misc) at the requested range. The default fallback function return nil. -- @return **checker** function. function lib:GetSmartChecker(range, fallback) return createSmartChecker( getChecker(self.friendRC, range) or fallback, getChecker(self.harmRC, range) or fallback, getChecker(self.miscRC, range) or fallback) end --- Get a range estimate as **minRange**, **maxRange**. -- @param unit the target unit to check range to. -- @return **minRange**, **maxRange** pair if a range estimate could be determined, **nil** otherwise. **maxRange** is **nil** if **unit** is further away than the highest possible range we can check. -- Includes checks for unit validity and friendly/enemy status. -- @usage -- local rc = LibStub("LibRangeCheck-2.0") -- local minRange, maxRange = rc:GetRange('target') function lib:GetRange(unit) if not UnitExists(unit) then return nil end if UnitIsDeadOrGhost(unit) then return getRange(unit, self.miscRC) end if UnitCanAttack("player", unit) then return getRange(unit, self.harmRC) elseif UnitCanAssist("player", unit) then return getRange(unit, self.friendRC) else return getRange(unit, self.miscRC) end end -- keep this for compatibility lib.getRange = lib.GetRange -- >> Public API function lib:OnEvent(event, ...) if type(self[event]) == 'function' then self[event](self, event, ...) end end function lib:LEARNED_SPELL_IN_TAB() self:scheduleInit() end function lib:CHARACTER_POINTS_CHANGED() self:scheduleInit() end function lib:PLAYER_TALENT_UPDATE() self:scheduleInit() end function lib:GLYPH_ADDED() self:scheduleInit() end function lib:GLYPH_REMOVED() self:scheduleInit() end function lib:GLYPH_UPDATED() self:scheduleInit() end function lib:SPELLS_CHANGED() self:scheduleInit() end function lib:UNIT_INVENTORY_CHANGED(event, unit) if self.initialized and unit == "player" and self.handSlotItem ~= GetInventoryItemLink("player", HandSlotId) then self:scheduleInit() end end function lib:UNIT_AURA(event, unit) if self.initialized and unit == "player" then self:scheduleAuraCheck() end end function lib:processItemRequests(itemRequests) while true do local range, items = next(itemRequests) if not range then return end while true do local i, item = next(items) if not i then itemRequests[range] = nil break elseif self.failedItemRequests[item] then tremove(items, i) elseif GetItemInfo(item) then if itemRequestTimeoutAt then foundNewItems = true itemRequestTimeoutAt = nil end if not cacheAllItems then itemRequests[range] = nil break end tremove(items, i) elseif not itemRequestTimeoutAt then itemRequestTimeoutAt = GetTime() + ItemRequestTimeout return true elseif GetTime() > itemRequestTimeoutAt then if cacheAllItems then print(MAJOR_VERSION .. ": timeout for item: " .. tostring(item)) end self.failedItemRequests[item] = true itemRequestTimeoutAt = nil tremove(items, i) else return true -- still waiting for server response end end end end function lib:initialOnUpdate() self:init() if friendItemRequests then if self:processItemRequests(friendItemRequests) then return end friendItemRequests = nil end if harmItemRequests then if self:processItemRequests(harmItemRequests) then return end harmItemRequests = nil end if foundNewItems then self:init(true) foundNewItems = nil end if cacheAllItems then print(MAJOR_VERSION .. ": finished cache") cacheAllItems = nil end self.frame:Hide() end function lib:scheduleInit() self.initialized = nil lastUpdate = 0 self.frame:Show() end function lib:scheduleAuraCheck() lastUpdate = UpdateDelay self.frame:Show() end -- << load-time initialization function lib:activate() if not self.frame then local frame = CreateFrame("Frame") self.frame = frame frame:RegisterEvent("LEARNED_SPELL_IN_TAB") frame:RegisterEvent("CHARACTER_POINTS_CHANGED") frame:RegisterEvent("PLAYER_TALENT_UPDATE") frame:RegisterEvent("GLYPH_ADDED") frame:RegisterEvent("GLYPH_REMOVED") frame:RegisterEvent("GLYPH_UPDATED") frame:RegisterEvent("SPELLS_CHANGED") local _, playerClass = UnitClass("player") if playerClass == "MAGE" or playerClass == "SHAMAN" then -- Mage and Shaman gladiator gloves modify spell ranges frame:RegisterUnitEvent("UNIT_INVENTORY_CHANGED", "player") end end initItemRequests() self.frame:SetScript("OnEvent", function(frame, ...) self:OnEvent(...) end) self.frame:SetScript("OnUpdate", function(frame, elapsed) lastUpdate = lastUpdate + elapsed if lastUpdate < UpdateDelay then return end lastUpdate = 0 self:initialOnUpdate() end) self:scheduleInit() end --- BEGIN CallbackHandler stuff do local lib = lib -- to keep a ref even though later we nil lib --- Register a callback to get called when checkers are updated -- @class function -- @name lib.RegisterCallback -- @usage -- rc.RegisterCallback(self, rc.CHECKERS_CHANGED, "myCallback") -- -- or -- rc.RegisterCallback(self, "CHECKERS_CHANGED", someCallbackFunction) -- @see CallbackHandler-1.0 documentation for more details lib.RegisterCallback = lib.RegisterCallback or function(...) local CBH = LibStub("CallbackHandler-1.0") lib.RegisterCallback = nil -- extra safety, we shouldn't get this far if CBH is not found, but better an error later than an infinite recursion now lib.callbacks = CBH:New(lib) -- ok, CBH hopefully injected or new shiny RegisterCallback return lib.RegisterCallback(...) end end --- END CallbackHandler stuff lib:activate() lib = nil
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Altar_Room/npcs/Magicite.lua
23
1573
----------------------------------- -- Area: Altar Room -- NPC: Magicite -- Involved in Mission: Magicite -- @zone 152 -- @pos -344 25 43 ----------------------------------- package.loaded["scripts/zones/Altar_Room/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Altar_Room/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(player:getNation()) == 13 and player:hasKeyItem(MAGICITE_ORASTONE) == false) then if(player:getVar("MissionStatus") < 4) then player:startEvent(0x002c,1); -- play Lion part of the CS (this is first magicite) else player:startEvent(0x002c); -- don't play Lion part of the CS end else player:messageSpecial(THE_MAGICITE_GLOWS_OMINOUSLY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x002c) then player:setVar("MissionStatus",4); player:addKeyItem(MAGICITE_ORASTONE); player:messageSpecial(KEYITEM_OBTAINED,MAGICITE_ORASTONE); end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/dish_of_salsa.lua
35
1591
----------------------------------------- -- ID: 5299 -- Item: dish_of_salsa -- Food Effect: 3Min, All Races ----------------------------------------- -- Strength -1 -- Dexterity -1 -- Agility -1 -- Vitality -1 -- Intelligence -1 -- Mind -1 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,180,5299); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -1); target:addMod(MOD_DEX, -1); target:addMod(MOD_AGI, -1); target:addMod(MOD_VIT, -1); target:addMod(MOD_INT, -1); target:addMod(MOD_MND, -1); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -1); target:delMod(MOD_DEX, -1); target:delMod(MOD_AGI, -1); target:delMod(MOD_VIT, -1); target:delMod(MOD_INT, -1); target:delMod(MOD_MND, -1); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/harvesting.lua
2
5627
------------------------------------------------- -- Author: Ezekyel -- Harvesting functions -- Info from: -- http://wiki.ffxiclopedia.org/wiki/Harvesting ------------------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/status"); ------------------------------------------------- -- npcid and drop by zone ------------------------------------------------- -- Zone, {npcid,npcid,npcid,..} local npcid = {51,{16986711,16986712,16986713,16986714,16986715,16986716}, -- Wajaom Woodlands 52,{16990602,16990603,16990604,16990605,16990606,16990607}, -- Bhaflau Thickets 89,{17142543,17142544,17142545,17142546,17142547,17142548}, -- Grauberg [S] 95,{17167161,17167162,17167163,17167164,17167165,17167166}, -- West Sarutabaruta [S] 115,{17248853,17248854,17248855,17248856,17248857,17248858}, -- West Sarutabaruta 123,{17281620,17281621,17281622}, -- Yuhtunga Jungle 124,{17285672,17285673,17285674}, -- Yhoator Jungle 145,{17371604,17371605,17371606,17371607,17371608,17371609}}; -- Giddeus -- Zone, {itemid,drop rate,itemid,drop rate,..} local drop = {51,{0x05F2,0.1880,0x08BC,0.3410,0x08F7,0.4700,0x0874,0.5990,0x1124,0.6930,0x08DE,0.7750,0x0A55,0.8460,0x086C,0.9170,0x0735,0.9760,0x05F4,1.0000}, 52,{0x05F2,0.1520,0x08F7,0.3080,0x0874,0.4530,0x08BC,0.5650,0x086C,0.6720,0x08DE,0.7720,0x1124,0.8310,0x0735,0.8970,0x05F4,0.9410,0x03B7,0.9730,0x0A55,1.0000}, 89,{0x0341,0.2320,0x0735,0.4310,0x023D,0.5850,0x086B,0.6850,0x023C,0.7850,0x1613,0.8980,0x023F,1.0000}, 95,{0x05F2,0.1670,0x0341,0.3260,0x0342,0.4900,0x1613,0.5800,0x0735,0.6610,0x0343,0.7480,0x023D,0.8050,0x07BD,0.8610,0x05F4,0.9020,0x07BE,0.9350,0x023C,0.9620,0x023F,1.0000}, 115,{0x0341,0.1760,0x05F2,0.2840,0x0342,0.3960,0x0735,0.5050,0x0A99,0.6070,0x0343,0.6970,0x07BD,0.7470,0x11C1,0.8020,0x027B,0.8630,0x03B7,0.9010,0x023D,0.9390,0x023C,0.9620,0x0347,0.9810,0x023F,0.9920,0x05F4,1.0000}, 123,{0x1115,0.4000,0x1117,0.6000,0x1116,0.8000,0x115F,0.8700,0x1160,0.9400,0x1122,0.9700,0x07BF,1.0000}, 124,{0x1115,0.4000,0x1117,0.6000,0x1116,0.8000,0x115F,0.8700,0x1162,0.9400,0x1161,0.9700,0x07BF,1.0000}, 145,{0x0735,0.1410,0x05F2,0.2820,0x0A99,0.4230,0x0343,0.5430,0x0342,0.6480,0x0341,0.7320,0x027B,0.7940,0x11C1,0.8440,0x07BE,0.8870,0x03B7,0.9260,0x023F,0.9480,0x023C,0.9650,0x05F4,0.9760,0x0347,0.9930,0x023D,1.0000}}; -- Define array of Colored Rocks, Do not reorder this array or rocks. local rocks = {0x0301,0x0302,0x0303,0x0304,0x0305,0x0306,0x0308,0x0307}; function startHarvesting(player,zone,npc,trade,csid) if(trade:hasItemQty(1020,1) and trade:getItemCount() == 1) then broke = sickleBreak(player,trade); item = getHarvestingItem(player,zone); if(player:getFreeSlotsCount() == 0) then full = 1; else full = 0; end player:startEvent(csid,item,broke,full); if(item ~= 0 and full == 0) then player:addItem(item); SetServerVariable("[HARVESTING]Zone "..zone,GetServerVariable("[HARVESTING]Zone "..zone) + 1); end if(GetServerVariable("[HARVESTING]Zone "..zone) >= 3) then getNewHarvestingPositionNPC(player,npc,zone); end if(player:getQuestStatus(AHT_URHGAN,VANISHING_ACT) == QUEST_ACCEPTED and player:hasKeyItem(RAINBOW_BERRY) == false and broke ~= 1 and zone == 51)then player:addKeyItem(RAINBOW_BERRY); player:messageSpecial(KEYITEM_OBTAINED,RAINBOW_BERRY); end else player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020); end end ----------------------------------- -- Determine if Pickaxe breaks ----------------------------------- function sickleBreak(player,trade) local broke = 0; sicklebreak = math.random(); -------------------- -- Begin Gear Bonus -------------------- Body = player:getEquipID(SLOT_BODY); Legs = player:getEquipID(SLOT_LEGS); Feet = player:getEquipID(SLOT_FEET); if(Body == 14374 or Body == 14375) then sicklebreak = sicklebreak + 0.073; end if(Legs == 14297 or Legs == 14298) then sicklebreak = sicklebreak + 0.073; end if(Feet == 14176 or Feet == 14177) then sicklebreak = sicklebreak + 0.073; end if(sicklebreak < HARVESTING_BREAK_CHANCE) then broke = 1; player:tradeComplete(); end return broke; end ----------------------------------- -- Get an item ----------------------------------- function getHarvestingItem(player,zone) Rate = math.random(); for zon = 1, table.getn(drop), 2 do if(drop[zon] == zone) then for itemlist = 1, table.getn(drop[zon + 1]), 2 do if(Rate <= drop[zon + 1][itemlist + 1]) then item = drop[zon + 1][itemlist]; break; end end break; end end -------------------- -- Determine chance of no item mined -- Default rate is 50% -------------------- Rate = math.random(); if(Rate <= (1 - HARVESTING_RATE)) then item = 0; end return item; end ----------------------------------------- -- After 3 items he change the position ----------------------------------------- function getNewHarvestingPositionNPC(player,npc,zone) local newnpcid = npc:getID(); for u = 1, table.getn(npcid), 2 do if(npcid[u] == zone) then nbNPC = table.getn(npcid[u + 1]); while newnpcid == npc:getID() do newnpcid = math.random(1,nbNPC); newnpcid = npcid[u + 1][newnpcid]; end break; end end npc:setStatus(2); GetNPCByID(newnpcid):setStatus(0); SetServerVariable("[HARVESTING]Zone "..zone,0); end
gpl-3.0
sjznxd/luci-0.11-aa
applications/luci-asterisk/luasrc/model/cbi/asterisk/voicemail.lua
11
1730
--[[ LuCI - Lua Configuration Interface Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: voicemail.lua 4397 2009-03-30 19:29:37Z jow $ ]]-- local ast = require "luci.asterisk" cbimap = Map("asterisk", "Voicemail - Mailboxes") voicemail = cbimap:section(TypedSection, "voicemail", "Voicemail Boxes") voicemail.addremove = true voicemail.anonymous = true voicemail.template = "cbi/tblsection" context = voicemail:option(ListValue, "context", "Context") context:value("default") number = voicemail:option(Value, "number", "Mailbox Number", "Unique mailbox identifier") function number.write(self, s, val) if val and #val > 0 then local old = self:cfgvalue(s) self.map.uci:foreach("asterisk", "dialplanvoice", function(v) if v.voicebox == old then self.map:set(v['.name'], "voicebox", val) end end) Value.write(self, s, val) end end voicemail:option(Value, "name", "Ownername", "Human readable display name") voicemail:option(Value, "password", "Password", "Access protection") voicemail:option(Value, "email", "eMail", "Where to send voice messages") voicemail:option(Value, "page", "Pager", "Pager number") zone = voicemail:option(ListValue, "zone", "Timezone", "Used time format") zone.titleref = luci.dispatcher.build_url("admin/asterisk/voicemail/settings") cbimap.uci:foreach("asterisk", "voicezone", function(s) zone:value(s['.name']) end) function voicemail.remove(self, s) return ast.voicemail.remove(self.map:get(s, "number"), self.map.uci) end return cbimap
apache-2.0
FFXIOrgins/FFXIOrgins
scripts/globals/weaponskills/garland_of_bliss.lua
4
4733
----------------------------------- -- Garland Of Bliss -- Staff weapon skill -- Skill level: N/A -- Lowers target's defense. Duration of effect varies with TP. Nirvana: Aftermath effect varies with TP. -- Reduces enemy's defense by 12.5%. -- Available only after completing the Unlocking a Myth (Summoner) quest. -- Aligned with the Flame Gorget, Light Gorget & Aqua Gorget. -- Aligned with the Flame Belt, Light Belt & Aqua Belt. -- Element: Light -- Modifiers: MND:40% -- 100%TP 200%TP 300%TP -- 2.00 2.00 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 2; params.ftp200 = 2; params.ftp300 = 2; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 30) + 30; if(target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then target:addStatusEffect(EFFECT_DEFENSE_DOWN, 12.5, 0, duration); end end if((player:getEquipID(SLOT_MAIN) == 19005) and (player:getMainJob() == JOB_SMN)) then if(damage > 0) then -- AFTERMATH LV1 if ((player:getTP() >= 100) and (player:getTP() <= 110)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1); elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1); elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1); elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1); elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1); elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1); elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1); elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1); elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1); elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1); -- AFTERMATH LV2 elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1); elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1); elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1); elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1); elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1); elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1); elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1); elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1); elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1); elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1); -- AFTERMATH LV3 elseif ((player:getTP() == 300)) then player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1); end end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
mkacik/bcc
src/lua/bpf/builtins.lua
2
16003
--[[ Copyright 2016 Marek Vavrusa <mvavrusa@cloudflare.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] local ffi = require('ffi') local bit = require('bit') local cdef = require('bpf.cdef') local BPF, HELPER = ffi.typeof('struct bpf'), ffi.typeof('struct bpf_func_id') local const_width = { [1] = BPF.B, [2] = BPF.H, [4] = BPF.W, [8] = BPF.DW, } local const_width_type = { [1] = ffi.typeof('uint8_t'), [2] = ffi.typeof('uint16_t'), [4] = ffi.typeof('uint32_t'), [8] = ffi.typeof('uint64_t'), } -- Built-ins that will be translated into BPF instructions -- i.e. bit.bor(0xf0, 0x0f) becomes {'alu64, or, k', reg(0xf0), reg(0x0f), 0, 0} local builtins = { [bit.lshift] = 'LSH', [bit.rshift] = 'RSH', [bit.band] = 'AND', [bit.bnot] = 'NEG', [bit.bor] = 'OR', [bit.bxor] = 'XOR', [bit.arshift] = 'ARSH', -- Extensions and intrinsics } local function width_type(w) -- Note: ffi.typeof doesn't accept '?' as template return const_width_type[w] or ffi.typeof(string.format('uint8_t [%d]', w)) end builtins.width_type = width_type -- Byte-order conversions for little endian local function ntoh(x, w) if w then x = ffi.cast(const_width_type[w/8], x) end return bit.bswap(x) end local function hton(x, w) return ntoh(x, w) end builtins.ntoh = ntoh builtins.hton = hton builtins[ntoh] = function (e, dst, a, w) -- This is trickery, but TO_LE means cpu_to_le(), -- and we want exactly the opposite as network is always 'be' w = w or ffi.sizeof(e.V[a].type)*8 if w == 8 then return end -- NOOP assert(w <= 64, 'NYI: hton(a[, width]) - operand larger than register width') -- Allocate registers and execute e.vcopy(dst, a) e.emit(BPF.ALU + BPF.END + BPF.TO_BE, e.vreg(dst), 0, 0, w) end builtins[hton] = function (e, dst, a, w) w = w or ffi.sizeof(e.V[a].type)*8 if w == 8 then return end -- NOOP assert(w <= 64, 'NYI: hton(a[, width]) - operand larger than register width') -- Allocate registers and execute e.vcopy(dst, a) e.emit(BPF.ALU + BPF.END + BPF.TO_LE, e.vreg(dst), 0, 0, w) end -- Byte-order conversions for big endian are no-ops if ffi.abi('be') then ntoh = function (x, w) return w and ffi.cast(const_width_type[w/8], x) or x end hton = ntoh builtins[ntoh] = function(a, b, w) return end builtins[hton] = function(a, b, w) return end end -- Other built-ins local function xadd(a, b) error('NYI') end builtins.xadd = xadd builtins[xadd] = function (e, dst, a, b, off) assert(e.V[a].const.__dissector, 'xadd(a, b) called on non-pointer') local w = ffi.sizeof(e.V[a].const.__dissector) assert(w == 4 or w == 8, 'NYI: xadd() - 1 and 2 byte atomic increments are not supported') -- Allocate registers and execute e.vcopy(dst, a) local src_reg = e.vreg(b) local dst_reg = e.vreg(dst) e.emit(BPF.JMP + BPF.JEQ + BPF.K, dst_reg, 0, 1, 0) -- if (dst != NULL) e.emit(BPF.XADD + BPF.STX + const_width[w], dst_reg, src_reg, off or 0, 0) end local function probe_read() error('NYI') end builtins.probe_read = probe_read builtins[probe_read] = function (e, ret, dst, src, vtype, ofs) e.reg_alloc(e.tmpvar, 1) -- Load stack pointer to dst, since only load to stack memory is supported -- we have to use allocated stack memory or create a new allocation and convert -- to pointer type e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 10, 0, 0) if not e.V[dst].const or not e.V[dst].const.__base > 0 then builtins[ffi.new](e, dst, vtype) -- Allocate stack memory end e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[dst].const.__base) -- Set stack memory maximum size bound e.reg_alloc(e.tmpvar, 2) if not vtype then vtype = cdef.typename(e.V[dst].type) -- Dereference pointer type to pointed type for size calculation if vtype:sub(-1) == '*' then vtype = vtype:sub(0, -2) end end local w = ffi.sizeof(vtype) e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 2, 0, 0, w) -- Set source pointer if e.V[src].reg then e.reg_alloc(e.tmpvar, 3) -- Copy from original register e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 3, e.V[src].reg, 0, 0) else local src_reg = e.vreg(src, 3) e.reg_spill(src) -- Spill to avoid overwriting end if ofs and ofs > 0 then e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 3, 0, 0, ofs) end -- Call probe read helper ret = ret or e.tmpvar e.vset(ret) e.vreg(ret, 0, true, ffi.typeof('int32_t')) e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.probe_read) e.V[e.tmpvar].reg = nil -- Free temporary registers end builtins[ffi.cast] = function (e, dst, ct, x) assert(e.V[ct].const, 'ffi.cast(ctype, x) called with bad ctype') e.vcopy(dst, x) if not e.V[x].const then e.V[dst].type = ffi.typeof(e.V[ct].const) else e.V[dst].const.__dissector = ffi.typeof(e.V[ct].const) end -- Specific types also encode source of the data -- This is because BPF has different helpers for reading -- different data sources, so variables must track origins. -- struct pt_regs - source of the data is probe -- struct skb - source of the data is socket buffer -- struct X - source of the data is probe/tracepoint if ffi.typeof(e.V[ct].const) == ffi.typeof('struct pt_regs') then e.V[dst].source = 'probe' end end builtins[ffi.new] = function (e, dst, ct, x) if type(ct) == 'number' then ct = ffi.typeof(e.V[ct].const) -- Get ctype from variable end assert(not x, 'NYI: ffi.new(ctype, ...) - initializer is not supported') assert(not cdef.isptr(ct, true), 'NYI: ffi.new(ctype, ...) - ctype MUST NOT be a pointer') e.vset(dst, nil, ct) e.V[dst].const = {__base = e.valloc(ffi.sizeof(ct), true), __dissector = ct} end builtins[ffi.copy] = function (e,ret, dst, src) assert(cdef.isptr(e.V[dst].type), 'ffi.copy(dst, src) - dst MUST be a pointer type') assert(cdef.isptr(e.V[src].type), 'ffi.copy(dst, src) - src MUST be a pointer type') -- Specific types also encode source of the data -- struct pt_regs - source of the data is probe -- struct skb - source of the data is socket buffer if e.V[src].source == 'probe' then e.reg_alloc(e.tmpvar, 1) -- Load stack pointer to dst, since only load to stack memory is supported -- we have to either use spilled variable or allocated stack memory offset e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 10, 0, 0) if e.V[dst].spill then e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[dst].spill) elseif e.V[dst].const.__base then e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[dst].const.__base) else error('ffi.copy(dst, src) - can\'t get stack offset of dst') end -- Set stack memory maximum size bound local dst_tname = cdef.typename(e.V[dst].type) if dst_tname:sub(-1) == '*' then dst_tname = dst_tname:sub(0, -2) end e.reg_alloc(e.tmpvar, 2) e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 2, 0, 0, ffi.sizeof(dst_tname)) -- Set source pointer if e.V[src].reg then e.reg_alloc(e.tmpvar, 3) -- Copy from original register e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 3, e.V[src].reg, 0, 0) else local src_reg = e.vreg(src, 3) e.reg_spill(src) -- Spill to avoid overwriting end -- Call probe read helper e.vset(ret) e.vreg(ret, 0, true, ffi.typeof('int32_t')) e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.probe_read) e.V[e.tmpvar].reg = nil -- Free temporary registers elseif e.V[src].const and e.V[src].const.__map then error('NYI: ffi.copy(dst, src) - src is backed by BPF map') elseif e.V[src].const and e.V[src].const.__dissector then error('NYI: ffi.copy(dst, src) - src is backed by socket buffer') else -- TODO: identify cheap register move -- TODO: identify copy to/from stack error('NYI: ffi.copy(dst, src) - src is neither BPF map/socket buffer or probe') end end -- print(format, ...) builtin changes semantics from Lua print(...) -- the first parameter has to be format and only reduced set of conversion specificers -- is allowed: %d %u %x %ld %lu %lx %lld %llu %llx %p %s builtins[print] = function (e, ret, fmt, a1, a2, a3) -- Load format string and length e.reg_alloc(e.V[e.tmpvar], 1) e.reg_alloc(e.V[e.tmpvar+1], 1) if type(e.V[fmt].const) == 'string' then local src = e.V[fmt].const local len = #src + 1 local dst = e.valloc(len, src) -- TODO: this is materialize step e.V[fmt].const = {__base=dst} e.V[fmt].type = ffi.typeof('char ['..len..']') elseif e.V[fmt].const.__base then -- NOP else error('NYI: print(fmt, ...) - format variable is not literal/stack memory') end -- Prepare helper call e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 10, 0, 0) e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[fmt].const.__base) e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 2, 0, 0, ffi.sizeof(e.V[fmt].type)) if a1 then local args = {a1, a2, a3} assert(#args <= 3, 'print(fmt, ...) - maximum of 3 arguments supported') for i, arg in ipairs(args) do e.vcopy(e.tmpvar, arg) -- Copy variable e.vreg(e.tmpvar, 3+i-1) -- Materialize it in arg register end end -- Call helper e.vset(ret) e.vreg(ret, 0, true, ffi.typeof('int32_t')) -- Return is integer e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.trace_printk) e.V[e.tmpvar].reg = nil -- Free temporary registers end -- Implements bpf_perf_event_output(ctx, map, flags, var, vlen) on perf event map local function perf_submit(e, dst, map_var, src) -- Set R2 = map fd (indirect load) local map = e.V[map_var].const e.vcopy(e.tmpvar, map_var) e.vreg(e.tmpvar, 2, true, ffi.typeof('uint64_t')) e.LD_IMM_X(2, BPF.PSEUDO_MAP_FD, map.fd, ffi.sizeof('uint64_t')) -- Set R1 = ctx e.reg_alloc(e.tmpvar, 1) -- Spill anything in R1 (unnamed tmp variable) e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 6, 0, 0) -- CTX is always in R6, copy -- Set R3 = flags e.vset(e.tmpvar, nil, 0) -- BPF_F_CURRENT_CPU e.vreg(e.tmpvar, 3, false, ffi.typeof('uint64_t')) -- Set R4 = pointer to src on stack assert(e.V[src].const.__base, 'NYI: submit(map, var) - variable is not on stack') e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 4, 10, 0, 0) e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 4, 0, 0, -e.V[src].const.__base) -- Set R5 = src length e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 5, 0, 0, ffi.sizeof(e.V[src].type)) -- Set R0 = ret and call e.vset(dst) e.vreg(dst, 0, true, ffi.typeof('int32_t')) -- Return is integer e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.perf_event_output) e.V[e.tmpvar].reg = nil -- Free temporary registers end -- Implements bpf_get_stack_id() local function stack_id(e, ret, map_var, key) -- Set R2 = map fd (indirect load) local map = e.V[map_var].const e.vcopy(e.tmpvar, map_var) e.vreg(e.tmpvar, 2, true, ffi.typeof('uint64_t')) e.LD_IMM_X(2, BPF.PSEUDO_MAP_FD, map.fd, ffi.sizeof('uint64_t')) -- Set R1 = ctx e.reg_alloc(e.tmpvar, 1) -- Spill anything in R1 (unnamed tmp variable) e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 6, 0, 0) -- CTX is always in R6, copy -- Load flags in R2 (immediate value or key) local imm = e.V[key].const assert(tonumber(imm), 'NYI: stack_id(map, var), var must be constant number') e.reg_alloc(e.tmpvar, 3) -- Spill anything in R2 (unnamed tmp variable) e.LD_IMM_X(3, 0, imm, 8) -- Return R0 as signed integer e.vset(ret) e.vreg(ret, 0, true, ffi.typeof('int32_t')) e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.get_stackid) e.V[e.tmpvar].reg = nil -- Free temporary registers end -- table.insert(table, value) keeps semantics with the exception of BPF maps -- map `perf_event` -> submit inserted value builtins[table.insert] = function (e, dst, map_var, value) assert(e.V[map_var].const.__map, 'NYI: table.insert() supported only on BPF maps') return perf_submit(e, dst, map_var, value) end -- bpf_get_current_comm(buffer) - write current process name to byte buffer local function comm() error('NYI') end builtins[comm] = function (e, ret, dst) -- Set R1 = buffer assert(e.V[dst].const.__base, 'NYI: comm(buffer) - buffer variable is not on stack') e.reg_alloc(e.tmpvar, 1) -- Spill e.emit(BPF.ALU64 + BPF.MOV + BPF.X, 1, 10, 0, 0) e.emit(BPF.ALU64 + BPF.ADD + BPF.K, 1, 0, 0, -e.V[dst].const.__base) -- Set R2 = length e.reg_alloc(e.tmpvar, 2) -- Spill e.emit(BPF.ALU64 + BPF.MOV + BPF.K, 2, 0, 0, ffi.sizeof(e.V[dst].type)) -- Return is integer e.vset(ret) e.vreg(ret, 0, true, ffi.typeof('int32_t')) e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, HELPER.get_current_comm) e.V[e.tmpvar].reg = nil -- Free temporary registers end -- Math library built-ins math.log2 = function (x) error('NYI') end builtins[math.log2] = function (e, dst, x) -- Classic integer bits subdivison algorithm to find the position -- of the highest bit set, adapted for BPF bytecode-friendly operations. -- https://graphics.stanford.edu/~seander/bithacks.html -- r = 0 local r = e.vreg(dst, nil, true) e.emit(BPF.ALU64 + BPF.MOV + BPF.K, r, 0, 0, 0) -- v = x e.vcopy(e.tmpvar, x) local v = e.vreg(e.tmpvar, 2) if cdef.isptr(e.V[x].const) then -- No pointer arithmetics, dereference e.vderef(v, v, ffi.typeof('uint64_t')) end -- Invert value to invert all tests, otherwise we would need and+jnz e.emit(BPF.ALU64 + BPF.NEG + BPF.K, v, 0, 0, 0) -- v = ~v -- Unrolled test cases, converted masking to arithmetic as we don't have "if !(a & b)" -- As we're testing inverted value, we have to use arithmetic shift to copy MSB for i=4,0,-1 do local k = bit.lshift(1, i) e.emit(BPF.JMP + BPF.JGT + BPF.K, v, 0, 2, bit.bnot(bit.lshift(1, k))) -- if !upper_half(x) e.emit(BPF.ALU64 + BPF.ARSH + BPF.K, v, 0, 0, k) -- v >>= k e.emit(BPF.ALU64 + BPF.OR + BPF.K, r, 0, 0, k) -- r |= k end -- No longer constant, cleanup tmpvars e.V[dst].const = nil e.V[e.tmpvar].reg = nil end builtins[math.log10] = function (e, dst, x) -- Compute log2(x) and transform builtins[math.log2](e, dst, x) -- Relationship: log10(v) = log2(v) / log2(10) local r = e.V[dst].reg e.emit(BPF.ALU64 + BPF.ADD + BPF.K, r, 0, 0, 1) -- Compensate round-down e.emit(BPF.ALU64 + BPF.MUL + BPF.K, r, 0, 0, 1233) -- log2(10) ~ 1233>>12 e.emit(BPF.ALU64 + BPF.RSH + BPF.K, r, 0, 0, 12) end builtins[math.log] = function (e, dst, x) -- Compute log2(x) and transform builtins[math.log2](e, dst, x) -- Relationship: ln(v) = log2(v) / log2(e) local r = e.V[dst].reg e.emit(BPF.ALU64 + BPF.ADD + BPF.K, r, 0, 0, 1) -- Compensate round-down e.emit(BPF.ALU64 + BPF.MUL + BPF.K, r, 0, 0, 2839) -- log2(e) ~ 2839>>12 e.emit(BPF.ALU64 + BPF.RSH + BPF.K, r, 0, 0, 12) end -- Call-type helpers local function call_helper(e, dst, h) e.vset(dst) local dst_reg = e.vreg(dst, 0, true) e.emit(BPF.JMP + BPF.CALL, 0, 0, 0, h) e.V[dst].const = nil -- Target is not a function anymore end local function cpu() error('NYI') end local function rand() error('NYI') end local function time() error('NYI') end local function pid_tgid() error('NYI') end local function uid_gid() error('NYI') end -- Export helpers and builtin variants builtins.cpu = cpu builtins.time = time builtins.pid_tgid = pid_tgid builtins.uid_gid = uid_gid builtins.comm = comm builtins.perf_submit = perf_submit builtins.stack_id = stack_id builtins[cpu] = function (e, dst) return call_helper(e, dst, HELPER.get_smp_processor_id) end builtins[rand] = function (e, dst) return call_helper(e, dst, HELPER.get_prandom_u32) end builtins[time] = function (e, dst) return call_helper(e, dst, HELPER.ktime_get_ns) end builtins[pid_tgid] = function (e, dst) return call_helper(e, dst, HELPER.get_current_pid_tgid) end builtins[uid_gid] = function (e, dst) return call_helper(e, dst, HELPER.get_current_uid_gid) end builtins[perf_submit] = function (e, dst, map, value) return perf_submit(e, dst, map, value) end builtins[stack_id] = function (e, dst, map, key) return stack_id(e, dst, map, key) end return builtins
apache-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Port_Windurst/npcs/Kunchichi.lua
38
1409
----------------------------------- -- Area: Port Windurst -- NPC: Kunchichi -- Type: Standard NPC -- @pos -115.933 -4.25 109.533 240 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,15) == false) then player:startEvent(0x026f); else player:startEvent(0x00e4); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x026f) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",15,true); end end;
gpl-3.0
togolwb/skynet
lualib/http/internal.lua
95
2613
local table = table local type = type local M = {} local LIMIT = 8192 local function chunksize(readbytes, body) while true do local f,e = body:find("\r\n",1,true) if f then return tonumber(body:sub(1,f-1),16), body:sub(e+1) end if #body > 128 then -- pervent the attacker send very long stream without \r\n return end body = body .. readbytes() end end local function readcrln(readbytes, body) if #body >= 2 then if body:sub(1,2) ~= "\r\n" then return end return body:sub(3) else body = body .. readbytes(2-#body) if body ~= "\r\n" then return end return "" end end function M.recvheader(readbytes, lines, header) if #header >= 2 then if header:find "^\r\n" then return header:sub(3) end end local result local e = header:find("\r\n\r\n", 1, true) if e then result = header:sub(e+4) else while true do local bytes = readbytes() header = header .. bytes if #header > LIMIT then return end e = header:find("\r\n\r\n", -#bytes-3, true) if e then result = header:sub(e+4) break end if header:find "^\r\n" then return header:sub(3) end end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end function M.parseheader(lines, from, header) local name, value for i=from,#lines do local line = lines[i] if line:byte(1) == 9 then -- tab, append last line if name == nil then return end header[name] = header[name] .. line:sub(2) else name, value = line:match "^(.-):%s*(.*)" if name == nil or value == nil then return end name = name:lower() if header[name] then local v = header[name] if type(v) == "table" then table.insert(v, value) else header[name] = { v , value } end else header[name] = value end end end return header end function M.recvchunkedbody(readbytes, bodylimit, header, body) local result = "" local size = 0 while true do local sz sz , body = chunksize(readbytes, body) if not sz then return end if sz == 0 then break end size = size + sz if bodylimit and size > bodylimit then return end if #body >= sz then result = result .. body:sub(1,sz) body = body:sub(sz+1) else result = result .. body .. readbytes(sz - #body) body = "" end body = readcrln(readbytes, body) if not body then return end end local tmpline = {} body = M.recvheader(readbytes, tmpline, body) if not body then return end header = M.parseheader(tmpline,1,header) return result, header end return M
mit
fartoverflow/naev
dat/events/neutral/shipwreck.lua
11
2074
--[[ -- Shipwreck Event -- -- Creates a wrecked ship that asks for help. If the player boards it, the event switches to the Space Family mission. -- See dat/missions/neutral/spacefamily.lua -- -- 12/02/2010 - Added visibility/highlight options for use in bigsystems (Anatolis) --]] lang = naev.lang() if lang == "es" then -- not translated atm else -- default english -- Text broadcastmsg = "SOS. This is %s. We are shipwrecked. Requesting immediate assistance." shipname = "August" --The ship will have a unique name end function create () -- The shipwrech will be a random trader vessel. r = rnd.rnd() if r > 0.95 then ship = "Trader Gawain" elseif r > 0.8 then ship = "Trader Mule" elseif r > 0.5 then ship = "Trader Koala" else ship = "Trader Llama" end -- Create the derelict. angle = rnd.rnd() * 2 * math.pi dist = rnd.rnd(2000, 3000) -- place it a ways out pos = vec2.new( dist * math.cos(angle), dist * math.sin(angle) ) p = pilot.add(ship, "dummy", pos) for k,v in ipairs(p) do v:setFaction("Derelict") v:disable() v:rename("Shipwrecked " .. shipname) -- Added extra visibility for big systems (A.) v:setVisplayer( true ) v:setHilight( true ) end hook.timer(3000, "broadcast") -- Set hooks hook.pilot( p[1], "board", "rescue" ) hook.pilot( p[1], "death", "destroyevent" ) hook.enter("endevent") hook.land("endevent") end function broadcast() -- Ship broadcasts an SOS every 10 seconds, until boarded or destroyed. if not p[1]:exists() then return end p[1]:broadcast( string.format(broadcastmsg, shipname), true ) bctimer = hook.timer(15000, "broadcast") end function rescue() -- Player boards the shipwreck and rescues the crew, this spawns a new mission. hook.rm(bctimer) naev.missionStart("The Space Family") evt.finish(true) end function destroyevent () evt.finish(true) end function endevent () evt.finish() end
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/bowl_of_mushroom_soup.lua
35
1384
----------------------------------------- -- ID: 4419 -- Item: mushroom_soup -- Food Effect: 3hours, All Races ----------------------------------------- -- Magic Points 20 -- Strength -1 -- Mind 2 -- MP Recovered While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4419); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 20); target:addMod(MOD_STR, -1); target:addMod(MOD_MND, 2); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 20); target:delMod(MOD_STR, -1); target:delMod(MOD_MND, 2); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
MOSAVI17/Gbot
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
punisherbot/test
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
sjznxd/lc-20130127
modules/niu/luasrc/model/cbi/niu/network/etherwan.lua
50
5482
--[[ LuCI - Lua Configuration Interface Copyright 2009 Steven Barth <steven@midlink.org> Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local has_ipv6 = fs.access("/proc/net/ipv6_route") local has_pptp = fs.access("/usr/sbin/pptp") local has_pppd = fs.access("/usr/sbin/pppd") local has_pppoe = fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() local has_pppoa = fs.glob("/usr/lib/pppd/*/pppoatm.so")() m = Map("network", "Configure Ethernet Adapter for Internet Connection") s = m:section(NamedSection, "wan", "interface") s.addremove = false s:tab("general", translate("General Settings")) s:tab("expert", translate("Expert Settings")) p = s:taboption("general", ListValue, "proto", translate("Connection Protocol")) p.override_scheme = true p.default = "dhcp" p:value("dhcp", translate("Cable / Ethernet / DHCP")) if has_pppoe then p:value("pppoe", "DSL / PPPoE") end if has_pppoa then p:value("pppoa", "PPPoA") end if has_pptp then p:value("pptp", "PPTP") end p:value("static", translate("Static Ethernet")) ipaddr = s:taboption("general", Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) ipaddr.rmempty = true ipaddr:depends("proto", "static") nm = s:taboption("general", Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")) nm.rmempty = true nm:depends("proto", "static") nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") gw = s:taboption("general", Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) gw:depends("proto", "static") gw.rmempty = true bcast = s:taboption("expert", Value, "bcast", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Broadcast")) bcast:depends("proto", "static") if has_ipv6 then ip6addr = s:taboption("expert", Value, "ip6addr", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix")) ip6addr:depends("proto", "static") ip6gw = s:taboption("expert", Value, "ip6gw", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")) ip6gw:depends("proto", "static") end dns = s:taboption("expert", Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server")) dns:depends("peerdns", "") mtu = s:taboption("expert", Value, "mtu", "MTU") mtu.isinteger = true mac = s:taboption("expert", Value, "macaddr", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) srv = s:taboption("general", Value, "server", translate("<abbr title=\"Point-to-Point Tunneling Protocol\">PPTP</abbr>-Server")) srv:depends("proto", "pptp") srv.rmempty = true if has_pppd or has_pppoe or has_pppoa or has_pptp then user = s:taboption("general", Value, "username", translate("Username")) user.rmempty = true user:depends("proto", "pptp") user:depends("proto", "pppoe") user:depends("proto", "pppoa") pass = s:taboption("general", Value, "password", translate("Password")) pass.rmempty = true pass.password = true pass:depends("proto", "pptp") pass:depends("proto", "pppoe") pass:depends("proto", "pppoa") ka = s:taboption("expert", Value, "keepalive", translate("Keep-Alive"), translate("Number of failed connection tests to initiate automatic reconnect") ) ka.default = "5" ka:depends("proto", "pptp") ka:depends("proto", "pppoe") ka:depends("proto", "pppoa") demand = s:taboption("expert", Value, "demand", translate("Automatic Disconnect"), translate("Time (in seconds) after which an unused connection will be closed") ) demand:depends("proto", "pptp") demand:depends("proto", "pppoe") demand:depends("proto", "pppoa") end if has_pppoa then encaps = s:taboption("expert", ListValue, "encaps", translate("PPPoA Encapsulation")) encaps:depends("proto", "pppoa") encaps:value("", translate("-- Please choose --")) encaps:value("vc", "VC") encaps:value("llc", "LLC") vpi = s:taboption("expert", Value, "vpi", "VPI") vpi:depends("proto", "pppoa") vci = s:taboption("expert", Value, "vci", "VCI") vci:depends("proto", "pppoa") end if has_pptp or has_pppd or has_pppoe or has_pppoa or has_3g then --[[ defaultroute = s:taboption("expert", Flag, "defaultroute", translate("Replace default route"), translate("Let pppd replace the current default route to use the PPP interface after successful connect") ) defaultroute:depends("proto", "pppoa") defaultroute:depends("proto", "pppoe") defaultroute:depends("proto", "pptp") defaultroute.rmempty = false function defaultroute.cfgvalue(...) return ( AbstractValue.cfgvalue(...) or '1' ) end ]] peerdns = s:taboption("expert", Flag, "peerdns", translate("Use peer DNS"), translate("Configure the local DNS server to use the name servers adverticed by the PPP peer") ) peerdns:depends("proto", "pppoa") peerdns:depends("proto", "pppoe") peerdns:depends("proto", "pptp") peerdns.rmempty = false peerdns.default = "1" if has_ipv6 then ipv6 = s:taboption("expert", Flag, "ipv6", translate("Enable IPv6 on PPP link") ) ipv6:depends("proto", "pppoa") ipv6:depends("proto", "pppoe") ipv6:depends("proto", "pptp") end end return m
apache-2.0
sjznxd/luci-0.11-aa
modules/niu/luasrc/model/cbi/niu/network/etherwan.lua
50
5482
--[[ LuCI - Lua Configuration Interface Copyright 2009 Steven Barth <steven@midlink.org> Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local has_ipv6 = fs.access("/proc/net/ipv6_route") local has_pptp = fs.access("/usr/sbin/pptp") local has_pppd = fs.access("/usr/sbin/pppd") local has_pppoe = fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() local has_pppoa = fs.glob("/usr/lib/pppd/*/pppoatm.so")() m = Map("network", "Configure Ethernet Adapter for Internet Connection") s = m:section(NamedSection, "wan", "interface") s.addremove = false s:tab("general", translate("General Settings")) s:tab("expert", translate("Expert Settings")) p = s:taboption("general", ListValue, "proto", translate("Connection Protocol")) p.override_scheme = true p.default = "dhcp" p:value("dhcp", translate("Cable / Ethernet / DHCP")) if has_pppoe then p:value("pppoe", "DSL / PPPoE") end if has_pppoa then p:value("pppoa", "PPPoA") end if has_pptp then p:value("pptp", "PPTP") end p:value("static", translate("Static Ethernet")) ipaddr = s:taboption("general", Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) ipaddr.rmempty = true ipaddr:depends("proto", "static") nm = s:taboption("general", Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")) nm.rmempty = true nm:depends("proto", "static") nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") gw = s:taboption("general", Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) gw:depends("proto", "static") gw.rmempty = true bcast = s:taboption("expert", Value, "bcast", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Broadcast")) bcast:depends("proto", "static") if has_ipv6 then ip6addr = s:taboption("expert", Value, "ip6addr", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix")) ip6addr:depends("proto", "static") ip6gw = s:taboption("expert", Value, "ip6gw", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")) ip6gw:depends("proto", "static") end dns = s:taboption("expert", Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server")) dns:depends("peerdns", "") mtu = s:taboption("expert", Value, "mtu", "MTU") mtu.isinteger = true mac = s:taboption("expert", Value, "macaddr", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) srv = s:taboption("general", Value, "server", translate("<abbr title=\"Point-to-Point Tunneling Protocol\">PPTP</abbr>-Server")) srv:depends("proto", "pptp") srv.rmempty = true if has_pppd or has_pppoe or has_pppoa or has_pptp then user = s:taboption("general", Value, "username", translate("Username")) user.rmempty = true user:depends("proto", "pptp") user:depends("proto", "pppoe") user:depends("proto", "pppoa") pass = s:taboption("general", Value, "password", translate("Password")) pass.rmempty = true pass.password = true pass:depends("proto", "pptp") pass:depends("proto", "pppoe") pass:depends("proto", "pppoa") ka = s:taboption("expert", Value, "keepalive", translate("Keep-Alive"), translate("Number of failed connection tests to initiate automatic reconnect") ) ka.default = "5" ka:depends("proto", "pptp") ka:depends("proto", "pppoe") ka:depends("proto", "pppoa") demand = s:taboption("expert", Value, "demand", translate("Automatic Disconnect"), translate("Time (in seconds) after which an unused connection will be closed") ) demand:depends("proto", "pptp") demand:depends("proto", "pppoe") demand:depends("proto", "pppoa") end if has_pppoa then encaps = s:taboption("expert", ListValue, "encaps", translate("PPPoA Encapsulation")) encaps:depends("proto", "pppoa") encaps:value("", translate("-- Please choose --")) encaps:value("vc", "VC") encaps:value("llc", "LLC") vpi = s:taboption("expert", Value, "vpi", "VPI") vpi:depends("proto", "pppoa") vci = s:taboption("expert", Value, "vci", "VCI") vci:depends("proto", "pppoa") end if has_pptp or has_pppd or has_pppoe or has_pppoa or has_3g then --[[ defaultroute = s:taboption("expert", Flag, "defaultroute", translate("Replace default route"), translate("Let pppd replace the current default route to use the PPP interface after successful connect") ) defaultroute:depends("proto", "pppoa") defaultroute:depends("proto", "pppoe") defaultroute:depends("proto", "pptp") defaultroute.rmempty = false function defaultroute.cfgvalue(...) return ( AbstractValue.cfgvalue(...) or '1' ) end ]] peerdns = s:taboption("expert", Flag, "peerdns", translate("Use peer DNS"), translate("Configure the local DNS server to use the name servers adverticed by the PPP peer") ) peerdns:depends("proto", "pppoa") peerdns:depends("proto", "pppoe") peerdns:depends("proto", "pptp") peerdns.rmempty = false peerdns.default = "1" if has_ipv6 then ipv6 = s:taboption("expert", Flag, "ipv6", translate("Enable IPv6 on PPP link") ) ipv6:depends("proto", "pppoa") ipv6:depends("proto", "pppoe") ipv6:depends("proto", "pptp") end end return m
apache-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Windurst_Waters/npcs/Paku-Nakku.lua
36
1422
----------------------------------- -- Area: Windurst Waters -- NPC: Paku-Nakku -- Involved in Quest: Making the Grade -- Working 100% -- @zone = 238 -- @pos = 127 -6 165 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then player:startEvent(0x01c4); -- During Making the GRADE else player:startEvent(0x01af); -- Standard conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
JulianVolodia/awesome
lib/awful/remote.lua
11
1687
--------------------------------------------------------------------------- --- Remote control module allowing usage of awesome-client. -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @copyright 2009 Julien Danjou -- @release @AWESOME_VERSION@ -- @module awful.remote --------------------------------------------------------------------------- -- Grab environment we need require("awful.dbus") local load = loadstring or load -- v5.1 - loadstring, v5.2 - load local tostring = tostring local ipairs = ipairs local table = table local unpack = unpack or table.unpack -- v5.1: unpack, v5.2: table.unpack local dbus = dbus local type = type if dbus then dbus.connect_signal("org.naquadah.awesome.awful.Remote", function(data, code) if data.member == "Eval" then local f, e = load(code) if f then local results = { f() } local retvals = {} for _, v in ipairs(results) do local t = type(v) if t == "boolean" then table.insert(retvals, "b") table.insert(retvals, v) elseif t == "number" then table.insert(retvals, "d") table.insert(retvals, v) else table.insert(retvals, "s") table.insert(retvals, tostring(v)) end end return unpack(retvals) elseif e then return "s", e end end end) end -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Toraimarai_Canal/npcs/Treasure_Coffer.lua
3
3884
----------------------------------- -- Area: Toraimarai Canal -- NPC: Treasure Coffer -- Involved In Quest: Wild Card -- @zone 169 -- @pos 220 16 -50 ----------------------------------- package.loaded["scripts/zones/Toraimarai_Canal/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Toraimarai_Canal/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1057,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; local count = trade:getItemCount(); if(trade:hasItemQty(1057,1) and count == 1 and player:getVar("WildCard") == 2) then player:tradeComplete(); player:addKeyItem(JOKER_CARD); player:messageSpecial(KEYITEM_OBTAINED,JOKER_CARD); player:setVar("WildCard",3); elseif((trade:hasItemQty(1057,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and count == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local mJob = player:getMainJob(); local zone = player:getZone(); local listAF = getAFbyZone(zone); for nb = 1,table.getn(listAF),3 do if(player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then questItemNeeded = 2; break end end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if(questItemNeeded == 2) then for nb = 1,table.getn(listAF),3 do if(mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1057); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
msburgess3200/PERP
gamemodes/perp/gamemode/vgui/bank.lua
1
1517
local PANEL = {}; function PANEL:Init ( ) self.BankPlayerInventory = vgui.Create("perp_bank_", self); self.BankPlayerInventory = vgui.Create("perp_bank_inv", self); //self.ShopDescription = vgui.Create("perp2_shop_desc", self); //self.ShopStoreInventory = vgui.Create("perp2_shop_store", self); //self.ShopTitle = vgui.Create("perp2_shop_title", self); self:SetSkin("ugperp") end function PANEL:PerformLayout ( ) self.Rift = 45; local realScrH = ScrW() * (10 / 16); self:SetPos(0, (ScrH() - realScrH) * .5); self:SetSize(ScrW(), realScrH); local bufferSize = 5; // Block size calculations local availableWidth = (ScrW() * .5) - 2 - ((INVENTORY_WIDTH + 1) * bufferSize); local sizeOfBlock = availableWidth / INVENTORY_WIDTH; // Size of inventory panel local NeededW = bufferSize + (INVENTORY_HEIGHT * (bufferSize + sizeOfBlock)); local NeededH = bufferSize + (INVENTORY_WIDTH * (bufferSize + sizeOfBlock)); // Size of local WidthSplit = (ScrW() * .5 - 1 - bufferSize * 3) * .5; // Total width of shop screen local totalWidth = WidthSplit + NeededW + self.Rift; local totalHeight = NeededH; local x, y = ScrW() * .5 - totalWidth * .5, realScrH * .5 - totalHeight * .5; self.BankPlayerInventory:SetSize(NeededW, NeededH); self.BankPlayerInventory:SetPos(x, y); self.BankPlayerInventory.SizeOfBlock = sizeOfBlock; local HeightSplit = WidthSplit * .5 + bufferSize * 3 + (realScrH * .53) - NeededW; end function PANEL:Paint ( ) end vgui.Register("perp_bank", PANEL);
mit
sjznxd/luci-0.11-aa
applications/luci-diag-devinfo/luasrc/controller/luci_diag/devinfo_common.lua
76
5638
--[[ Luci diag - Diagnostics controller module (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module("luci.controller.luci_diag.devinfo_common", package.seeall) require("luci.i18n") require("luci.util") require("luci.sys") require("luci.cbi") require("luci.model.uci") local translate = luci.i18n.translate local DummyValue = luci.cbi.DummyValue local SimpleSection = luci.cbi.SimpleSection function index() return -- no-op end function run_processes(outnets, cmdfunc) i = next(outnets, nil) while (i) do outnets[i]["output"] = luci.sys.exec(cmdfunc(outnets, i)) i = next(outnets, i) end end function parse_output(devmap, outnets, haslink, type, mini, debug) local curnet = next(outnets, nil) while (curnet) do local output = outnets[curnet]["output"] local subnet = outnets[curnet]["subnet"] local ports = outnets[curnet]["ports"] local interface = outnets[curnet]["interface"] local netdevs = {} devlines = luci.util.split(output) if not devlines then devlines = {} table.insert(devlines, output) end local j = nil j = next(devlines, j) local found_a_device = false while (j) do if devlines[j] and ( devlines[j] ~= "" ) then found_a_device = true local devtable local row = {} devtable = luci.util.split(devlines[j], ' | ') row["ip"] = devtable[1] if (not mini) then row["mac"] = devtable[2] end if ( devtable[4] == 'unknown' ) then row["vendor"] = devtable[3] else row["vendor"] = devtable[4] end row["type"] = devtable[5] if (not mini) then row["model"] = devtable[6] end if (haslink) then row["config_page"] = devtable[7] end if (debug) then row["raw"] = devlines[j] end table.insert(netdevs, row) end j = next(devlines, j) end if not found_a_device then local row = {} row["ip"] = curnet if (not mini) then row["mac"] = "" end if (type == "smap") then row["vendor"] = luci.i18n.translate("No SIP devices") else row["vendor"] = luci.i18n.translate("No devices detected") end row["type"] = luci.i18n.translate("check other networks") if (not mini) then row["model"] = "" end if (haslink) then row["config_page"] = "" end if (debug) then row["raw"] = output end table.insert(netdevs, row) end local s if (type == "smap") then if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet .. " (" .. subnet .. ":" .. ports .. interfacestring .. ")") end s.template = "diag/smapsection" else if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet .. " (" .. subnet .. interfacestring .. ")") end end s:option(DummyValue, "ip", translate("IP Address")) if (not mini) then s:option(DummyValue, "mac", translate("MAC Address")) end s:option(DummyValue, "vendor", translate("Vendor")) s:option(DummyValue, "type", translate("Device Type")) if (not mini) then s:option(DummyValue, "model", translate("Model")) end if (haslink) then s:option(DummyValue, "config_page", translate("Link to Device")) end if (debug) then s:option(DummyValue, "raw", translate("Raw")) end curnet = next(outnets, curnet) end end function get_network_device(interface) local state = luci.model.uci.cursor_state() state:load("network") local dev return state:get("network", interface, "ifname") end function cbi_add_networks(field) uci.cursor():foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then field:value(section[".name"]) end end ) field.titleref = luci.dispatcher.build_url("admin", "network", "network") end function config_devinfo_scan(map, scannet) local o o = scannet:option(luci.cbi.Flag, "enable", translate("Enable")) o.optional = false o.rmempty = false o = scannet:option(luci.cbi.Value, "interface", translate("Interface")) o.optional = false luci.controller.luci_diag.devinfo_common.cbi_add_networks(o) local scansubnet scansubnet = scannet:option(luci.cbi.Value, "subnet", translate("Subnet")) scansubnet.optional = false o = scannet:option(luci.cbi.Value, "timeout", translate("Timeout"), translate("Time to wait for responses in seconds (default 10)")) o.optional = true o = scannet:option(luci.cbi.Value, "repeat_count", translate("Repeat Count"), translate("Number of times to send requests (default 1)")) o.optional = true o = scannet:option(luci.cbi.Value, "sleepreq", translate("Sleep Between Requests"), translate("Milliseconds to sleep between requests (default 100)")) o.optional = true end
apache-2.0
loic-fejoz/loic-fejoz-fabmoments
icesl-gallery/pythagoras-tree.lua
1
2790
--[[ The MIT License (MIT) Copyright (c) 2015 Loïc Fejoz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -- See http://en.wikipedia.org/wiki/L-system#Example_2:_Pythagoras_Tree phi = (1.0 + math.sqrt(5)) / 2.0 -- golden ratio --Context = {length = 140, angle = 0, n = 6, x = 0, y = 0, z = 0, delta = 45, ratio = 0.5} Context = {length = 140, angle = 0, n = 6, x = 0, y = 0, z = 0, delta = 60, ratio = 1.0/phi} function Ctx_print(ctx) print('{length=' .. ctx.length .. ', angle=' .. ctx.angle .. ', n = ' .. ctx.n .. ', x = ' .. ctx.x .. ', y = ' .. ctx.y .. ', z = ' .. ctx.z .. '}') end function left(ctx) return { length = ctx.length * ctx.ratio, angle = ctx.angle - ctx.delta, n = ctx.n - 1, x = ctx.x + ctx.length/2.0 * sin(ctx.angle), y = 0, z = ctx.z + ctx.length/2.0 * cos(ctx.angle), delta = ctx.delta, ratio = ctx.ratio } end function right(ctx) return { length = ctx.length * ctx.ratio, angle = ctx.angle + ctx.delta, n = ctx.n - 1, x = ctx.x + ctx.length/2.0 * sin(ctx.angle), y = 0, z = ctx.z + ctx.length/2.0 * cos(ctx.angle), delta = ctx.delta, ratio = ctx.ratio } end function tree(ctx) if ctx.n == 0 then return translate(ctx.x, ctx.y, ctx.z) * rotate(0, ctx.angle, 0) * merge{ cylinder(ctx.length / 25.0, ctx.length), translate(0, 0, ctx.length) * sphere(0.2 / phi * ctx.length) } else local s1 = translate(ctx.x, ctx.y, ctx.z) * rotate(0, ctx.angle, 0) * cone(ctx.length / 25.0, ctx.length / 25.0 * ctx.ratio, ctx.length/2) local c1 = left(ctx) local c2 = right(ctx) local s3 = tree(c2) local s2 = tree(c1) return merge{s1, s2, s3} end end emit(tree(Context))
mit
adamsumm/SMBRNN
Torch/sample.lua
2
5737
--[[ This file samples characters from a trained model Code is based on implementation in https://github.com/oxford-cs-ml-2015/practical6 ]]-- require 'torch' require 'nn' require 'nngraph' require 'optim' require 'lfs' require 'util.OneHot' require 'util.misc' cmd = torch.CmdLine() cmd:text() cmd:text('Sample from a character-level language model') cmd:text() cmd:text('Options') -- required: cmd:argument('-model','model checkpoint to use for sampling') -- optional parameters cmd:option('-seed',123,'random number generator\'s seed') cmd:option('-sample',1,' 0 to use max at each timestep, 1 to sample at each timestep') cmd:option('-primetext',"",'used as a prompt to "seed" the state of the LSTM using a given sequence, before we sample.') cmd:option('-length',2000,'number of characters to sample') cmd:option('-temperature',1,'temperature of sampling') cmd:option('-gpuid',0,'which gpu to use. -1 = use CPU') cmd:option('-opencl',0,'use OpenCL (instead of CUDA)') cmd:option('-verbose',1,'set to 0 to ONLY print the sampled text, no diagnostics') cmd:text() -- parse input params opt = cmd:parse(arg) -- gated print: simple utility function wrapping a print function gprint(str) if opt.verbose == 1 then print(str) end end -- check that cunn/cutorch are installed if user wants to use the GPU if opt.gpuid >= 0 and opt.opencl == 0 then local ok, cunn = pcall(require, 'cunn') local ok2, cutorch = pcall(require, 'cutorch') if not ok then gprint('package cunn not found!') end if not ok2 then gprint('package cutorch not found!') end if ok and ok2 then gprint('using CUDA on GPU ' .. opt.gpuid .. '...') cutorch.setDevice(opt.gpuid + 1) -- note +1 to make it 0 indexed! sigh lua cutorch.manualSeed(opt.seed) else gprint('Falling back on CPU mode') opt.gpuid = -1 -- overwrite user setting end end -- check that clnn/cltorch are installed if user wants to use OpenCL if opt.gpuid >= 0 and opt.opencl == 1 then local ok, cunn = pcall(require, 'clnn') local ok2, cutorch = pcall(require, 'cltorch') if not ok then print('package clnn not found!') end if not ok2 then print('package cltorch not found!') end if ok and ok2 then print('using OpenCL on GPU ' .. opt.gpuid .. '...') cltorch.setDevice(opt.gpuid + 1) -- note +1 to make it 0 indexed! sigh lua torch.manualSeed(opt.seed) else gprint('Falling back on CPU mode') opt.gpuid = -1 -- overwrite user setting end end torch.manualSeed(opt.seed) -- load the model checkpoint if not lfs.attributes(opt.model, 'mode') then gprint('Error: File ' .. opt.model .. ' does not exist. Are you sure you didn\'t forget to prepend cv/ ?') end checkpoint = torch.load(opt.model) protos = checkpoint.protos protos.rnn:evaluate() -- put in eval mode so that dropout works properly -- initialize the vocabulary (and its inverted version) local vocab = checkpoint.vocab local ivocab = {} for c,i in pairs(vocab) do ivocab[i] = c end -- initialize the rnn state to all zeros gprint('creating an ' .. checkpoint.opt.model .. '...') local current_state current_state = {} for L = 1,checkpoint.opt.num_layers do -- c and h for all layers local h_init = torch.zeros(1, checkpoint.opt.rnn_size) if opt.gpuid >= 0 and opt.opencl == 0 then h_init = h_init:cuda() end if opt.gpuid >= 0 and opt.opencl == 1 then h_init = h_init:cl() end table.insert(current_state, h_init:clone()) if checkpoint.opt.model == 'lstm' then table.insert(current_state, h_init:clone()) end end state_size = #current_state -- do a few seeded timesteps local seed_text = opt.primetext if string.len(seed_text) > 0 then gprint('seeding with ' .. seed_text) gprint('--------------------------') for c in seed_text:gmatch'.' do prev_char = torch.Tensor{vocab[c]} io.write(ivocab[prev_char[1]]) if opt.gpuid >= 0 and opt.opencl == 0 then prev_char = prev_char:cuda() end if opt.gpuid >= 0 and opt.opencl == 1 then prev_char = prev_char:cl() end local lst = protos.rnn:forward{prev_char, unpack(current_state)} -- lst is a list of [state1,state2,..stateN,output]. We want everything but last piece current_state = {} for i=1,state_size do table.insert(current_state, lst[i]) end prediction = lst[#lst] -- last element holds the log probabilities end else -- fill with uniform probabilities over characters (? hmm) gprint('missing seed text, using uniform probability over first character') gprint('--------------------------') prediction = torch.Tensor(1, #ivocab):fill(1)/(#ivocab) if opt.gpuid >= 0 and opt.opencl == 0 then prediction = prediction:cuda() end if opt.gpuid >= 0 and opt.opencl == 1 then prediction = prediction:cl() end end -- start sampling/argmaxing for i=1, opt.length do -- log probabilities from the previous timestep if opt.sample == 0 then -- use argmax local _, prev_char_ = prediction:max(2) prev_char = prev_char_:resize(1) else -- use sampling prediction:div(opt.temperature) -- scale by temperature local probs = torch.exp(prediction):squeeze() probs:div(torch.sum(probs)) -- renormalize so probs sum to one prev_char = torch.multinomial(probs:float(), 1):resize(1):float() end -- forward the rnn for next character local lst = protos.rnn:forward{prev_char, unpack(current_state)} current_state = {} for i=1,state_size do table.insert(current_state, lst[i]) end prediction = lst[#lst] -- last element holds the log probabilities io.write(ivocab[prev_char[1]]) end io.write('\n') io.flush()
mit
sadegh1996/sword_antispam
plugins/weather.lua
8
1444
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) local url = BASE_URL url = url..'?q='..location url = url..'&units=metric' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Yogyakarta' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Yogyakarta is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
gpl-2.0
joshimoo/Algorithm-Implementations
Caesar_Cipher/Lua/Yonaba/caesar_cipher_test.lua
26
1202
-- Tests for caesar_cipher.lua local caesar = require 'caesar_cipher' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Ciphering test', function() assert(caesar.cipher('abcd',1) == 'bcde') assert(caesar.cipher('WXYZ',2) == 'YZAB') assert(caesar.cipher('abcdefghijklmnopqrstuvwxyz',3) == 'defghijklmnopqrstuvwxyzabc') assert(caesar.cipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ',4) == 'EFGHIJKLMNOPQRSTUVWXYZABCD') end) run('Deciphering test', function() assert(caesar.decipher('bcde',1) == 'abcd') assert(caesar.decipher('YZAB',2) == 'WXYZ') assert(caesar.decipher('defghijklmnopqrstuvwxyzabc',3) == 'abcdefghijklmnopqrstuvwxyz') assert(caesar.decipher('EFGHIJKLMNOPQRSTUVWXYZABCD',4) == 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
sadegh1996/sword_antispam
libs/JSON.lua
13
36868
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release -- -- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- -- -- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- ||\\ //|| //\\ || //|| //\\ // || || // -- || \\ // || // \\ || // || // \\ // || || // -- || \\ // || // \\ || // || // \\ || || || // -- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || // -- || \\ // || // \\ || // || // \\ || || || || \\ -- || \\ // || // \\ || // || // \\ \\ || || || \\ -- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\ -- -- -- ||-_-_-_- || || || //-_-_-_-_-_- -- || || || || || // -- ||_-_-_|| || || || // -- || || || || \\ -- || || \\ // \\ -- || || \\ // // -- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-// -- --By @ali_ghoghnoos --@telemanager_ch
gpl-2.0
sjznxd/lc-20130127
applications/luci-statistics/luasrc/model/cbi/luci_statistics/email.lua
78
1934
--[[ Luci configuration model for statistics - collectd email plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("E-Mail Plugin Configuration"), translate( "The email plugin creates a unix socket which can be used " .. "to transmit email-statistics to a running collectd daemon. " .. "This plugin is primarily intended to be used in conjunction " .. "with Mail::SpamAssasin::Plugin::Collectd but can be used in " .. "other ways as well." )) -- collectd_email config section s = m:section( NamedSection, "collectd_email", "luci_statistics" ) -- collectd_email.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_email.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile", translate("Socket file") ) socketfile.default = "/var/run/collect-email.sock" socketfile:depends( "enable", 1 ) -- collectd_email.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup", translate("Socket group") ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_email.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) -- collectd_email.maxconns (MaxConns) maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") ) maxconns.default = 5 maxconns.isinteger = true maxconns.rmempty = true maxconns.optional = true maxconns:depends( "enable", 1 ) return m
apache-2.0
Gael-de-Sailly/minetest-minetestforfun-server
mods/pipeworks/init.lua
8
3709
-- Pipeworks mod by Vanessa Ezekowitz - 2013-07-13 -- -- This mod supplies various steel pipes and plastic pneumatic tubes -- and devices that they can connect to. -- -- License: WTFPL -- pipeworks = {} local DEBUG = false pipeworks.worldpath = minetest.get_worldpath() pipeworks.modpath = minetest.get_modpath("pipeworks") dofile(pipeworks.modpath.."/default_settings.txt") -- Read the external config file if it exists. local worldsettingspath = pipeworks.worldpath.."/pipeworks_settings.txt" local worldsettingsfile = io.open(worldsettingspath, "r") if worldsettingsfile then worldsettingsfile:close() dofile(worldsettingspath) end -- Random variables pipeworks.expect_infinite_stacks = true if minetest.get_modpath("unified_inventory") or not minetest.setting_getbool("creative_mode") then pipeworks.expect_infinite_stacks = false end pipeworks.meseadjlist={{x=0,y=0,z=1},{x=0,y=0,z=-1},{x=0,y=1,z=0},{x=0,y=-1,z=0},{x=1,y=0,z=0},{x=-1,y=0,z=0}} pipeworks.rules_all = {{x=0, y=0, z=1},{x=0, y=0, z=-1},{x=1, y=0, z=0},{x=-1, y=0, z=0}, {x=0, y=1, z=1},{x=0, y=1, z=-1},{x=1, y=1, z=0},{x=-1, y=1, z=0}, {x=0, y=-1, z=1},{x=0, y=-1, z=-1},{x=1, y=-1, z=0},{x=-1, y=-1, z=0}, {x=0, y=1, z=0}, {x=0, y=-1, z=0}} pipeworks.mesecons_rules={{x=0,y=0,z=1},{x=0,y=0,z=-1},{x=1,y=0,z=0},{x=-1,y=0,z=0},{x=0,y=1,z=0},{x=0,y=-1,z=0}} pipeworks.liquid_texture = "default_water.png" -- Helper functions function pipeworks.fix_image_names(table, replacement) local outtable={} for i in ipairs(table) do outtable[i]=string.gsub(table[i], "_XXXXX", replacement) end return outtable end function pipeworks.add_node_box(t, b) if not t or not b then return end for i in ipairs(b) do table.insert(t, b[i]) end end function pipeworks.may_configure(pos, player) local name = player:get_player_name() local meta = minetest.get_meta(pos) local owner = meta:get_string("owner") if owner ~= "" then -- wielders and filters return owner == name end return not minetest.is_protected(pos, name) end function pipeworks.replace_name(tbl,tr,name) local ntbl={} for key,i in pairs(tbl) do if type(i)=="string" then ntbl[key]=string.gsub(i,tr,name) elseif type(i)=="table" then ntbl[key]=pipeworks.replace_name(i,tr,name) else ntbl[key]=i end end return ntbl end ------------------------------------------- -- Load the various other parts of the mod dofile(pipeworks.modpath.."/common.lua") dofile(pipeworks.modpath.."/models.lua") dofile(pipeworks.modpath.."/autoplace_pipes.lua") dofile(pipeworks.modpath.."/autoplace_tubes.lua") dofile(pipeworks.modpath.."/luaentity.lua") dofile(pipeworks.modpath.."/item_transport.lua") dofile(pipeworks.modpath.."/flowing_logic.lua") dofile(pipeworks.modpath.."/crafts.lua") dofile(pipeworks.modpath.."/tube_registration.lua") dofile(pipeworks.modpath.."/routing_tubes.lua") dofile(pipeworks.modpath.."/sorting_tubes.lua") dofile(pipeworks.modpath.."/vacuum_tubes.lua") dofile(pipeworks.modpath.."/signal_tubes.lua") dofile(pipeworks.modpath.."/decorative_tubes.lua") dofile(pipeworks.modpath.."/filter-injector.lua") dofile(pipeworks.modpath.."/trashcan.lua") dofile(pipeworks.modpath.."/wielder.lua") if pipeworks.enable_pipes then dofile(pipeworks.modpath.."/pipes.lua") end if pipeworks.enable_teleport_tube then dofile(pipeworks.modpath.."/teleport_tube.lua") end if pipeworks.enable_pipe_devices then dofile(pipeworks.modpath.."/devices.lua") end if pipeworks.enable_redefines then dofile(pipeworks.modpath.."/compat.lua") end if pipeworks.enable_autocrafter then dofile(pipeworks.modpath.."/autocrafter.lua") end minetest.register_alias("pipeworks:pipe", "pipeworks:pipe_110000_empty") minetest.log("Pipeworks loaded!")
unlicense
FFXIOrgins/FFXIOrgins
scripts/globals/mobskills/Chains_of_Arrogance.lua
5
1180
--------------------------------------------- -- Chains of Apathy -- --------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/keyitems"); require("/scripts/zones/Empyreal_Paradox/TextIDs"); --------------------------------------------- function OnMobSkillCheck(target,mob,skill) local targets = mob:getEnmityList(); for i,v in pairs(targets) do if (v:isPC()) then local race = v:getRace() if (race == 3 or race == 4) and not v:hasKeyItem(LIGHT_OF_MEA) then mob:showText(mob, PROMATHIA_TEXT + 1); return 0; end end end return 1; end; function OnMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_TERROR; local power = 30; local duration = 30; if target:isPC() and ((target:getRace() == 3 or target:getRace() == 4) and not target:hasKeyItem(LIGHT_OF_MEA)) then skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration)); else skill:setMsg(MSG_NO_EFFECT); end return typeEffect; end;
gpl-3.0
LuaDist2/hotswap-ev
bench/bench-http.lua
8
1194
local gettime = require "socket".gettime local n = require "n" local hotswap = require "hotswap.http" { encode = function (t) if next (t) == nil or next (t, next (t)) ~= nil then return end local k, v = next (t) return { url = "http://127.0.0.1:8080/lua/" .. k, method = "GET", headers = { ["If-None-Match"] = type (v) == "table" and v.etag or nil, ["Lua-Module" ] = k, }, } end, decode = function (t) local module = t.request.headers ["Lua-Module"] if t.code == 200 then return { [module] = { lua = t.body, etag = t.headers.etag, }, } elseif t.code == 304 then return { [module] = {}, } elseif t.code == 404 then return {} else assert (false) end end, } assert (os.execute [[ rm -rf ./nginx/*.log ./nginx/*.pid /usr/sbin/nginx -p ./nginx/ -c nginx.conf ]]) local start = gettime () for _ = 1, n do local _ = hotswap.require "toload" end local finish = gettime () print (math.floor (n / (finish - start)), "requires/second") assert (os.execute [[ kill -QUIT $(cat ./nginx/nginx.pid) ]])
mit
sjznxd/lc-20130127
libs/httpclient/luasrc/httpclient.lua
41
9111
--[[ LuCI - Lua Development Framework Copyright 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require "nixio.util" local nixio = require "nixio" local ltn12 = require "luci.ltn12" local util = require "luci.util" local table = require "table" local http = require "luci.http.protocol" local date = require "luci.http.protocol.date" local type, pairs, ipairs, tonumber = type, pairs, ipairs, tonumber local unpack = unpack module "luci.httpclient" function chunksource(sock, buffer) buffer = buffer or "" return function() local output local _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n") while not count and #buffer <= 1024 do local newblock, code = sock:recv(1024 - #buffer) if not newblock then return nil, code end buffer = buffer .. newblock _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n") end count = tonumber(count, 16) if not count then return nil, -1, "invalid encoding" elseif count == 0 then return nil elseif count + 2 <= #buffer - endp then output = buffer:sub(endp+1, endp+count) buffer = buffer:sub(endp+count+3) return output else output = buffer:sub(endp+1, endp+count) buffer = "" if count - #output > 0 then local remain, code = sock:recvall(count-#output) if not remain then return nil, code end output = output .. remain count, code = sock:recvall(2) else count, code = sock:recvall(count+2-#buffer+endp) end if not count then return nil, code end return output end end end function request_to_buffer(uri, options) local source, code, msg = request_to_source(uri, options) local output = {} if not source then return nil, code, msg end source, code = ltn12.pump.all(source, (ltn12.sink.table(output))) if not source then return nil, code end return table.concat(output) end function request_to_source(uri, options) local status, response, buffer, sock = request_raw(uri, options) if not status then return status, response, buffer elseif status ~= 200 and status ~= 206 then return nil, status, buffer end if response.headers["Transfer-Encoding"] == "chunked" then return chunksource(sock, buffer) else return ltn12.source.cat(ltn12.source.string(buffer), sock:blocksource()) end end -- -- GET HTTP-resource -- function request_raw(uri, options) options = options or {} local pr, auth, host, port, path if uri:find("@") then pr, auth, host, port, path = uri:match("(%w+)://(.+)@([%w-.]+):?([0-9]*)(.*)") else pr, host, port, path = uri:match("(%w+)://([%w-.]+):?([0-9]*)(.*)") end if not host then return nil, -1, "unable to parse URI" end if pr ~= "http" and pr ~= "https" then return nil, -2, "protocol not supported" end port = #port > 0 and port or (pr == "https" and 443 or 80) path = #path > 0 and path or "/" options.depth = options.depth or 10 local headers = options.headers or {} local protocol = options.protocol or "HTTP/1.1" headers["User-Agent"] = headers["User-Agent"] or "LuCI httpclient 0.1" if headers.Connection == nil then headers.Connection = "close" end if auth and not headers.Authorization then headers.Authorization = "Basic " .. nixio.bin.b64encode(auth) end local sock, code, msg = nixio.connect(host, port) if not sock then return nil, code, msg end sock:setsockopt("socket", "sndtimeo", options.sndtimeo or 15) sock:setsockopt("socket", "rcvtimeo", options.rcvtimeo or 15) if pr == "https" then local tls = options.tls_context or nixio.tls() sock = tls:create(sock) local stat, code, error = sock:connect() if not stat then return stat, code, error end end -- Pre assemble fixes if protocol == "HTTP/1.1" then headers.Host = headers.Host or host end if type(options.body) == "table" then options.body = http.urlencode_params(options.body) end if type(options.body) == "string" then headers["Content-Length"] = headers["Content-Length"] or #options.body headers["Content-Type"] = headers["Content-Type"] or "application/x-www-form-urlencoded" options.method = options.method or "POST" end if type(options.body) == "function" then options.method = options.method or "POST" end -- Assemble message local message = {(options.method or "GET") .. " " .. path .. " " .. protocol} for k, v in pairs(headers) do if type(v) == "string" or type(v) == "number" then message[#message+1] = k .. ": " .. v elseif type(v) == "table" then for i, j in ipairs(v) do message[#message+1] = k .. ": " .. j end end end if options.cookies then for _, c in ipairs(options.cookies) do local cdo = c.flags.domain local cpa = c.flags.path if (cdo == host or cdo == "."..host or host:sub(-#cdo) == cdo) and (cpa == path or cpa == "/" or cpa .. "/" == path:sub(#cpa+1)) and (not c.flags.secure or pr == "https") then message[#message+1] = "Cookie: " .. c.key .. "=" .. c.value end end end message[#message+1] = "" message[#message+1] = "" -- Send request sock:sendall(table.concat(message, "\r\n")) if type(options.body) == "string" then sock:sendall(options.body) elseif type(options.body) == "function" then local res = {options.body(sock)} if not res[1] then sock:close() return unpack(res) end end -- Create source and fetch response local linesrc = sock:linesource() local line, code, error = linesrc() if not line then sock:close() return nil, code, error end local protocol, status, msg = line:match("^([%w./]+) ([0-9]+) (.*)") if not protocol then sock:close() return nil, -3, "invalid response magic: " .. line end local response = { status = line, headers = {}, code = 0, cookies = {}, uri = uri } line = linesrc() while line and line ~= "" do local key, val = line:match("^([%w-]+)%s?:%s?(.*)") if key and key ~= "Status" then if type(response.headers[key]) == "string" then response.headers[key] = {response.headers[key], val} elseif type(response.headers[key]) == "table" then response.headers[key][#response.headers[key]+1] = val else response.headers[key] = val end end line = linesrc() end if not line then sock:close() return nil, -4, "protocol error" end -- Parse cookies if response.headers["Set-Cookie"] then local cookies = response.headers["Set-Cookie"] for _, c in ipairs(type(cookies) == "table" and cookies or {cookies}) do local cobj = cookie_parse(c) cobj.flags.path = cobj.flags.path or path:match("(/.*)/?[^/]*") if not cobj.flags.domain or cobj.flags.domain == "" then cobj.flags.domain = host response.cookies[#response.cookies+1] = cobj else local hprt, cprt = {}, {} -- Split hostnames and save them in reverse order for part in host:gmatch("[^.]*") do table.insert(hprt, 1, part) end for part in cobj.flags.domain:gmatch("[^.]*") do table.insert(cprt, 1, part) end local valid = true for i, part in ipairs(cprt) do -- If parts are different and no wildcard if hprt[i] ~= part and #part ~= 0 then valid = false break -- Wildcard on invalid position elseif hprt[i] ~= part and #part == 0 then if i ~= #cprt or (#hprt ~= i and #hprt+1 ~= i) then valid = false break end end end -- No TLD cookies if valid and #cprt > 1 and #cprt[2] > 0 then response.cookies[#response.cookies+1] = cobj end end end end -- Follow response.code = tonumber(status) if response.code and options.depth > 0 then if response.code == 301 or response.code == 302 or response.code == 307 and response.headers.Location then local nuri = response.headers.Location or response.headers.location if not nuri then return nil, -5, "invalid reference" end if not nuri:find("https?://") then nuri = pr .. "://" .. host .. ":" .. port .. nuri end options.depth = options.depth - 1 if options.headers then options.headers.Host = nil end sock:close() return request_raw(nuri, options) end end return response.code, response, linesrc(true), sock end function cookie_parse(cookiestr) local key, val, flags = cookiestr:match("%s?([^=;]+)=?([^;]*)(.*)") if not key then return nil end local cookie = {key = key, value = val, flags = {}} for fkey, fval in flags:gmatch(";%s?([^=;]+)=?([^;]*)") do fkey = fkey:lower() if fkey == "expires" then fval = date.to_unix(fval:gsub("%-", " ")) end cookie.flags[fkey] = fval end return cookie end function cookie_create(cookie) local cookiedata = {cookie.key .. "=" .. cookie.value} for k, v in pairs(cookie.flags) do if k == "expires" then v = date.to_http(v):gsub(", (%w+) (%w+) (%w+) ", ", %1-%2-%3 ") end cookiedata[#cookiedata+1] = k .. ((#v > 0) and ("=" .. v) or "") end return table.concat(cookiedata, "; ") end
apache-2.0
Gael-de-Sailly/minetest-minetestforfun-server
minetestforfun_game/mods/screwdriver/init.lua
6
4233
screwdriver = {} local function nextrange(x, max) x = x + 1 if x > max then x = 0 end return x end screwdriver.ROTATE_FACE = 1 screwdriver.ROTATE_AXIS = 2 screwdriver.disallow = function(pos, node, user, mode, new_param2) return false end screwdriver.rotate_simple = function(pos, node, user, mode, new_param2) if mode ~= screwdriver.ROTATE_FACE then return false end end local USES = 200 local USES_perfect = 10000 -- Handles rotation screwdriver.handler = function(itemstack, user, pointed_thing, mode, uses) if pointed_thing.type ~= "node" then return end local pos = pointed_thing.under if minetest.is_protected(pos, user:get_player_name()) then minetest.record_protection_violation(pos, user:get_player_name()) return end local node = minetest.get_node(pos) local ndef = minetest.registered_nodes[node.name] -- verify node is facedir (expected to be rotatable) if not ndef or ndef.paramtype2 ~= "facedir" then return end -- Compute param2 local rotationPart = node.param2 % 32 -- get first 4 bits local preservePart = node.param2 - rotationPart local axisdir = math.floor(rotationPart / 4) local rotation = rotationPart - axisdir * 4 if mode == screwdriver.ROTATE_FACE then rotationPart = axisdir * 4 + nextrange(rotation, 3) elseif mode == screwdriver.ROTATE_AXIS then rotationPart = nextrange(axisdir, 5) * 4 end local new_param2 = preservePart + rotationPart local should_rotate = true if ndef and ndef.on_rotate then -- Node provides a handler, so let the handler decide instead if the node can be rotated -- Copy pos and node because callback can modify it local result = ndef.on_rotate(vector.new(pos), {name = node.name, param1 = node.param1, param2 = node.param2}, user, mode, new_param2) if result == false then -- Disallow rotation return elseif result == true then should_rotate = false end else if not ndef or not ndef.paramtype2 == "facedir" or ndef.on_rotate == false or (ndef.drawtype == "nodebox" and not ndef.node_box.type == "fixed") or node.param2 == nil then return end if ndef.can_dig and not ndef.can_dig(pos, user) then return end end if should_rotate then node.param2 = new_param2 minetest.swap_node(pos, node) end if not minetest.setting_getbool("creative_mode") and minetest.registered_tools["screwdriver:screwdriver_perfect"] then itemstack:add_wear(65535 / (USES_perfect - 1)) elseif not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535 / (USES - 1)) end return itemstack end -- Screwdriver minetest.register_tool("screwdriver:screwdriver", { description = "Screwdriver (left-click rotates face, right-click rotates axis)", inventory_image = "screwdriver.png", on_use = function(itemstack, user, pointed_thing) screwdriver.handler(itemstack, user, pointed_thing, screwdriver.ROTATE_FACE, 200) return itemstack end, on_place = function(itemstack, user, pointed_thing) screwdriver.handler(itemstack, user, pointed_thing, screwdriver.ROTATE_AXIS) return itemstack end, }) -- Perfect Screwdriver (en mithril à 10 000 utilisations) minetest.register_tool("screwdriver:screwdriver_perfect", { description = "Perfect Screwdriver (left-click rotates face, right-click rotates axis)", inventory_image = "screwdriver_perfect.png", on_use = function(itemstack, user, pointed_thing) screwdriver.handler(itemstack, user, pointed_thing, screwdriver.ROTATE_FACE, 10000) return itemstack end, on_place = function(itemstack, user, pointed_thing) screwdriver.handler(itemstack, user, pointed_thing, screwdriver.ROTATE_AXIS, 10000) return itemstack end, }) minetest.register_craft({ output = "screwdriver:screwdriver", recipe = { {"default:steel_ingot"}, {"group:stick"} } }) minetest.register_craft({ output = "screwdriver:screwdriver_perfect", recipe = { {"default:mithril_ingot"}, {"group:stick"} } }) minetest.register_alias("screwdriver:screwdriver1", "screwdriver:screwdriver") minetest.register_alias("screwdriver:screwdriver2", "screwdriver:screwdriver") minetest.register_alias("screwdriver:screwdriver3", "screwdriver:screwdriver") minetest.register_alias("screwdriver:screwdriver4", "screwdriver:screwdriver")
unlicense
FFXIOrgins/FFXIOrgins
scripts/zones/Aht_Urhgan_Whitegate/npcs/Tafeesa.lua
34
1032
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Tafeesa -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x028F); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
xToken/CompMod
lua/CompMod/TechData/NewTechData.lua
1
29608
-- Natural Selection 2 Competitive Mod -- Source located at - https://github.com/xToken/CompMod -- lua\CompMod\TechData\NewTechData.lua -- - Dragon -- This file contains all the updated tech data. In mostly one place to make my life easier! function BuildCompModTechDataUpdates() local newTechTable = { } local techIdUpdates = { } -- New Tech Data table.insert(newTechTable, { [kTechDataId] = kTechId.FlamethrowerUpgrade1, [kTechDataCostKey] = kFlamethrowerUpgrade1Cost, [kTechDataResearchTimeKey] = kFlamethrowerUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_FT_1", [kTechDataTooltipInfo] = "MARINE_FT_1_TOOLTIP", [kTechDataDescription] = "EVT_FT_LEVEL_1_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 191 }) table.insert(newTechTable, { [kTechDataId] = kTechId.ShotgunUpgrade1, [kTechDataCostKey] = kShotgunUpgrade1Cost, [kTechDataResearchTimeKey] = kShotgunUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_SHOTGUN_1", [kTechDataTooltipInfo] = "MARINE_SHOTGUN_1_TOOLTIP", [kTechDataDescription] = "EVT_SG_LEVEL_1_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 192 }) table.insert(newTechTable, { [kTechDataId] = kTechId.ShotgunUpgrade2, [kTechDataCostKey] = kShotgunUpgrade2Cost, [kTechDataResearchTimeKey] = kShotgunUpgrade2ResearchTime, [kTechDataDisplayName] = "MARINE_SHOTGUN_2", [kTechDataTooltipInfo] = "MARINE_SHOTGUN_2_TOOLTIP", [kTechDataDescription] = "EVT_SG_LEVEL_2_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 192 }) table.insert(newTechTable, { [kTechDataId] = kTechId.MGUpgrade1, [kTechDataCostKey] = kMGUpgrade1Cost, [kTechDataResearchTimeKey] = kMGUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_MG_1", [kTechDataTooltipInfo] = "MARINE_MG_1_TOOLTIP", [kTechDataDescription] = "EVT_MG_LEVEL_1_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 193 }) table.insert(newTechTable, { [kTechDataId] = kTechId.MGUpgrade2, [kTechDataCostKey] = kMGUpgrade2Cost, [kTechDataResearchTimeKey] = kMGUpgrade2ResearchTime, [kTechDataDisplayName] = "MARINE_MG_2", [kTechDataTooltipInfo] = "MARINE_MG_2_TOOLTIP", [kTechDataDescription] = "EVT_MG_LEVEL_2_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 193 }) table.insert(newTechTable, { [kTechDataId] = kTechId.GLUpgrade1, [kTechDataCostKey] = kGLUpgrade1Cost, [kTechDataResearchTimeKey] = kGLUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_GL_1", [kTechDataTooltipInfo] = "MARINE_GL_1_TOOLTIP", [kTechDataDescription] = "EVT_GL_LEVEL_1_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 194 }) table.insert(newTechTable, { [kTechDataId] = kTechId.JetpackUpgrade1, [kTechDataCostKey] = kJetpackUpgrade1Cost, [kTechDataResearchTimeKey] = kJetpackUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_JP_1", [kTechDataTooltipInfo] = "MARINE_JP_1_TOOLTIP", [kTechDataDescription] = "EVT_JP_LEVEL_1_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 197 }) table.insert(newTechTable, { [kTechDataId] = kTechId.ExoUpgrade1, [kTechDataCostKey] = kExoUpgrade1Cost, [kTechDataResearchTimeKey] = kExoUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_EXO_1", [kTechDataTooltipInfo] = "MARINE_EXO_1_TOOLTIP", [kTechDataDescription] = "EVT_EXO_LEVEL_1_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 198 }) table.insert(newTechTable, { [kTechDataId] = kTechId.ExoUpgrade2, [kTechDataCostKey] = kExoUpgrade2Cost, [kTechDataResearchTimeKey] = kExoUpgrade2ResearchTime, [kTechDataDisplayName] = "MARINE_EXO_2", [kTechDataTooltipInfo] = "MARINE_EXO_2_TOOLTIP", [kTechDataDescription] = "EVT_EXO_LEVEL_2_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataImplemented] = false, [kTechDataButtonID] = 25 }) table.insert(newTechTable, { [kTechDataId] = kTechId.MinigunUpgrade1, [kTechDataCostKey] = kMinigunUpgrade1Cost, [kTechDataResearchTimeKey] = kMinigunUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_MINIGUN_1", [kTechDataTooltipInfo] = "MARINE_MINIGUN_1_TOOLTIP", [kTechDataDescription] = "EVT_MINIGUN_LEVEL_1_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataImplemented] = false, [kTechDataButtonID] = 84 }) table.insert(newTechTable, { [kTechDataId] = kTechId.MinigunUpgrade2, [kTechDataCostKey] = kMinigunUpgrade2Cost, [kTechDataResearchTimeKey] = kMinigunUpgrade2ResearchTime, [kTechDataDisplayName] = "MARINE_MINIGUN_2", [kTechDataTooltipInfo] = "MARINE_MINIGUN_2_TOOLTIP", [kTechDataDescription] = "EVT_MINIGUN_LEVEL_2_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataImplemented] = false, [kTechDataButtonID] = 84 }) table.insert(newTechTable, { [kTechDataId] = kTechId.RailgunUpgrade1, [kTechDataCostKey] = kRailgunUpgrade1Cost, [kTechDataResearchTimeKey] = kRailgunUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_RAILGUN_1", [kTechDataTooltipInfo] = "MARINE_RAILGUN_1_TOOLTIP", [kTechDataDescription] = "EVT_RAILGUN_LEVEL_2_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataImplemented] = false, [kTechDataButtonID] = 116 }) table.insert(newTechTable, { [kTechDataId] = kTechId.ARCUpgrade1, [kTechDataCostKey] = kARCUpgrade1Cost, [kTechDataResearchTimeKey] = kARCUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_ARC_1", [kTechDataTooltipInfo] = "MARINE_ARC_1_TOOLTIP", [kTechDataButtonID] = 195 }) table.insert(newTechTable, { [kTechDataId] = kTechId.ARCUpgrade2, [kTechDataCostKey] = kARCUpgrade2Cost, [kTechDataResearchTimeKey] = kARCUpgrade2ResearchTime, [kTechDataDisplayName] = "MARINE_ARC_2", [kTechDataTooltipInfo] = "MARINE_ARC_2_TOOLTIP", [kTechDataButtonID] = 32 }) table.insert(newTechTable, { [kTechDataId] = kTechId.SentryUpgrade1, [kTechDataCostKey] = kSentryUpgrade1Cost, [kTechDataResearchTimeKey] = kSentryUpgrade1ResearchTime, [kTechDataDisplayName] = "MARINE_SENTRY_1", [kTechDataTooltipInfo] = "MARINE_SENTRY_1_TOOLTIP", [kTechDataImplemented] = false, [kTechDataButtonID] = 5 }) table.insert(newTechTable, { [kTechDataId] = kTechId.StructureMenu, [kTechDataDisplayName] = "BUILD_STRUCTURES", [kTechDataTooltipInfo] = "BUILD_STRUCTURES_TOOLTIP", [kTechDataButtonID] = 157 }) table.insert(newTechTable, { [kTechDataId] = kTechId.AdvancedStructureMenu, [kTechDataDisplayName] = "BUILD_ADV_STRUCTURES", [kTechDataTooltipInfo] = "BUILD_ADV_STRUCTURES_TOOLTIP", [kTechDataButtonID] = 11 }) table.insert(newTechTable, { [kTechDataId] = kTechId.OffensiveTraits, [kTechDataCostKey] = kOffensiveTraitCost, [kTechDataResearchTimeKey] = kOffensiveTraitResearchTime, [kTechDataDisplayName] = "OFFENSE_TRAITS", [kTechDataTooltipInfo] = "OFFENSE_TRAITS_TOOLTIP", [kTechDataDescription] = "EVT_OFFENSIVE_TRAITS_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 23 }) table.insert(newTechTable, { [kTechDataId] = kTechId.DefensiveTraits, [kTechDataCostKey] = kDefensiveTraitCost, [kTechDataResearchTimeKey] = kDefensiveTraitResearchTime, [kTechDataDisplayName] = "DEFENSE_TRAITS", [kTechDataTooltipInfo] = "DEFENSE_TRAITS_TOOLTIP", [kTechDataDescription] = "EVT_DEFENSIVE_TRAITS_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 22 }) table.insert(newTechTable, { [kTechDataId] = kTechId.MovementTraits, [kTechDataCostKey] = kMovementTraitCost, [kTechDataResearchTimeKey] = kMovementTraitResearchTime, [kTechDataDisplayName] = "MOVEMENT_TRAITS", [kTechDataTooltipInfo] = "MOVEMENT_TRAITS_TOOLTIP", [kTechDataDescription] = "EVT_MOVEMENT_TRAITS_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 11 }) table.insert(newTechTable, { [kTechDataId] = kTechId.AdditionalTraitSlot1, [kTechDataCostKey] = kAdditionalTraitSlot1Cost, [kTechDataResearchTimeKey] = kAdditionalTraitSlot1ResearchTime, [kTechDataDisplayName] = "ADDITIONAL_TRAIT_SLOT", [kTechDataTooltipInfo] = "ADDITIONAL_TRAIT_SLOT_TOOLTIP", [kTechDataDescription] = "EVT_ADDITIONAL_TRAIT_1_SLOT_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 70 }) table.insert(newTechTable, { [kTechDataId] = kTechId.AdditionalTraitSlot2, [kTechDataCostKey] = kAdditionalTraitSlot2Cost, [kTechDataResearchTimeKey] = kAdditionalTraitSlot2ResearchTime, [kTechDataDisplayName] = "ADDITIONAL_TRAIT_SLOT_2", [kTechDataTooltipInfo] = "ADDITIONAL_TRAIT_SLOT_2_TOOLTIP", [kTechDataDescription] = "EVT_ADDITIONAL_TRAIT_2_SLOT_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 65 }) table.insert(newTechTable, { [kTechDataId] = kTechId.HealingRoost, [kTechDataCostKey] = kHealingRoostCost, [kTechDataResearchTimeKey] = kHealingRoostResearchTime, [kTechDataDisplayName] = "HEALING_ROOST", [kTechDataTooltipInfo] = "HEALING_ROOST_TOOLTIP", [kTechDataDescription] = "EVT_HEALING_ROOST_RESEARCHED", [kTechDataNotifyPlayers] = true, [kTechDataButtonID] = 166 }) table.insert(newTechTable, { [kTechDataId] = kTechId.ParasiteCloud, [kTechDataCooldown] = kParasiteCloudCooldown, [kTechDataMapName] = ParasiteCloud.kMapName, [kTechDataDisplayName] = "PARASITE_CLOUD", [kTechDataCostKey] = kParasiteCloudCost, [kTechDataTooltipInfo] = "PARASITE_CLOUD_TOOLTIP", [kVisualRange] = ParasiteCloud.kRadius, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataIgnorePathingMesh] = true, [kTechDataAllowStacking] = true, [kTechDataModel] = BoneWall.kModelName, [kTechDataButtonID] = 70 }) table.insert(newTechTable, { [kTechDataId] = kTechId.TeleportStructure, [kTechIDShowEnables] = false, [kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_STRUCTURE", [kTechDataTooltipInfo] = "ECHO_TOOLTIP", [kTechDataCollideWithWorldOnly] = true, [kTechDataIgnorePathingMesh] = true, [kTechDataAllowStacking] = true, [kTechDataModel] = BoneWall.kModelName, [kVisualRange] = 0.5, [kTechDataButtonID] = 40, [kCommanderSelectRadius] = 0.375, [kTechDataRequiresSecondPlacement] = true }) table.insert(newTechTable, { [kTechDataId] = kTechId.TeleportEmbryo, [kTechIDShowEnables] = false, [kTechDataGhostModelClass] = "TeleportAlienGhostModel", [kTechDataDisplayName] = "ECHO_EMBRYO", [kTechDataCostKey] = kEchoEmbryoCost, [kTechDataRequiresInfestation] = false, [kTechDataModel] = Egg.kModelName, [kTechDataTooltipInfo] = "ECHO_TOOLTIP", [kTechDataCollideWithWorldOnly] = true, [kTechDataImplemented] = false, [kTechDataRequiresSecondPlacement] = true }) table.insert(newTechTable, { [kTechDataId] = kTechId.Shell2, [kTechDataBioMass] = kShellBiomass, [kTechDataHint] = "SHELL_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Shell.kMapName, [kTechDataDisplayName] = "SHELL", [kTechDataCostKey] = kTwoShellsCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kShellBuildTime, [kTechDataModel] = Shell.kModelName, [kTechDataMaxHealth] = kShellHealth, [kTechDataMaxArmor] = kShellArmor, [kTechDataPointValue] = kShellPointValue, [kTechDataTooltipInfo] = "SHELL_TOOLTIP", [kTechDataGrows] = true, [kTechDataNotifyPlayers] = true, [kTechDataObstacleRadius] = 0.75, [kTechDataButtonID] = 148 }) table.insert(newTechTable, { [kTechDataId] = kTechId.Shell3, [kTechDataBioMass] = kShellBiomass, [kTechDataHint] = "SHELL_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Shell.kMapName, [kTechDataDisplayName] = "SHELL", [kTechDataCostKey] = kThreeShellsCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kShellBuildTime, [kTechDataModel] = Shell.kModelName, [kTechDataMaxHealth] = kShellHealth, [kTechDataMaxArmor] = kShellArmor, [kTechDataPointValue] = kShellPointValue, [kTechDataTooltipInfo] = "SHELL_TOOLTIP", [kTechDataGrows] = true, [kTechDataNotifyPlayers] = true, [kTechDataObstacleRadius] = 0.75, [kTechDataButtonID] = 149 }) table.insert(newTechTable, { [kTechDataId] = kTechId.Spur2, [kTechDataBioMass] = kSpurBiomass, [kTechDataHint] = "SPUR_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Spur.kMapName, [kTechDataDisplayName] = "SPUR", [kTechDataCostKey] = kTwoSpursCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kSpurBuildTime, [kTechDataModel] = Spur.kModelName, [kTechDataMaxHealth] = kSpurHealth, [kTechDataMaxArmor] = kSpurArmor, [kTechDataPointValue] = kSpurPointValue, [kTechDataTooltipInfo] = "SPUR_TOOLTIP", [kTechDataGrows] = true, [kTechDataNotifyPlayers] = true, [kTechDataObstacleRadius] = 0.75, [kTechDataButtonID] = 144 }) table.insert(newTechTable, { [kTechDataId] = kTechId.Spur3, [kTechDataBioMass] = kSpurBiomass, [kTechDataHint] = "SPUR_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Spur.kMapName, [kTechDataDisplayName] = "SPUR", [kTechDataCostKey] = kThreeSpursCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kSpurBuildTime, [kTechDataModel] = Spur.kModelName, [kTechDataMaxHealth] = kSpurHealth, [kTechDataMaxArmor] = kSpurArmor, [kTechDataPointValue] = kSpurPointValue, [kTechDataTooltipInfo] = "SPUR_TOOLTIP", [kTechDataGrows] = true, [kTechDataNotifyPlayers] = true, [kTechDataObstacleRadius] = 0.75, [kTechDataButtonID] = 145 }) table.insert(newTechTable, { [kTechDataId] = kTechId.Veil2, [kTechDataBioMass] = kVeilBiomass, [kTechDataHint] = "VEIL_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Veil.kMapName, [kTechDataDisplayName] = "VEIL", [kTechDataCostKey] = kTwoVeilsCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kVeilBuildTime, [kTechDataModel] = Veil.kModelName, [kTechDataMaxHealth] = kVeilHealth, [kTechDataMaxArmor] = kVeilArmor, [kTechDataPointValue] = kVeilPointValue, [kTechDataTooltipInfo] = "VEIL_TOOLTIP", [kTechDataGrows] = true, [kTechDataNotifyPlayers] = true, [kTechDataObstacleRadius] = 0.5, [kTechDataButtonID] = 146 }) table.insert(newTechTable, { [kTechDataId] = kTechId.Veil3, [kTechDataBioMass] = kVeilBiomass, [kTechDataHint] = "VEIL_HINT", [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = Veil.kMapName, [kTechDataDisplayName] = "VEIL", [kTechDataCostKey] = kThreeVeilsCost, [kTechDataRequiresInfestation] = true, [kTechDataHotkey] = Move.C, [kTechDataBuildTime] = kVeilBuildTime, [kTechDataModel] = Veil.kModelName, [kTechDataMaxHealth] = kVeilHealth, [kTechDataMaxArmor] = kVeilArmor, [kTechDataPointValue] = kVeilPointValue, [kTechDataTooltipInfo] = "VEIL_TOOLTIP", [kTechDataGrows] = true, [kTechDataNotifyPlayers] = true, [kTechDataObstacleRadius] = 0.5, [kTechDataButtonID] = 147 }) table.insert(newTechTable, { [kTechDataId] = kTechId.InfestedNode, [kTechDataHint] = "INFEST_POWER_NODE_HINT", [kTechDataDisplayName] = "INFEST_POWER_NODE", [kTechDataTooltipInfo] = "INFEST_POWER_NODE_TOOLTIP", [kTechDataIgnorePathingMesh] = true, [kTechDataSpawnBlock] = true, [kTechDataCollideWithWorldOnly] = true, [kTechDataAllowStacking] = true, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataMapName] = InfestedNode.kMapName, [kTechDataCostKey] = kInfestPowerNodeCost, [kTechDataBuildTime] = kInfestPowerNodeBuildTime, [kTechDataModel] = InfestedNode.kModelName, [kTechDataMaxHealth] = kInfestedPowerPointHealth, [kTechDataMaxArmor] = kInfestedPowerPointArmor, [kStructureAttachClass] = "PowerPoint", [kTechDataPointValue] = kInfestedPowerPointValue, [kTechDataHotkey] = Move.E, [kTechDataButtonID] = 168, }) table.insert(newTechTable, { [kTechDataId] = kTechId.PowerNode, [kTechDataHint] = "POWER_NODE_HINT", [kTechDataDisplayName] = "POWER_NODE", [kTechDataTooltipInfo] = "POWER_NODE_TOOLTIP", [kTechDataIgnorePathingMesh] = true, [kTechDataSpawnBlock] = true, [kTechDataCollideWithWorldOnly] = true, [kTechDataAllowStacking] = true, [kTechDataGhostModelClass] = "MarineGhostModel", [kTechDataMapName] = PowerNode.kMapName, [kTechDataCostKey] = kPowerNodeCost, [kTechDataBuildTime] = kPowerPointBuildTime, [kTechDataModel] = PowerNode.kModelName, [kTechDataMaxHealth] = kPowerPointHealth, [kTechDataMaxArmor] = kPowerPointArmor, [kStructureAttachClass] = "PowerPoint", [kTechDataPointValue] = kPowerPointPointValue, [kTechDataHotkey] = Move.E, [kTechDataButtonID] = 93, }) -- Existing tech updates below! table.insert(techIdUpdates, { [kTechDataId] = kTechId.AdvancedArmory, [kTechIDShowEnables] = false, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.PrototypeLab, [kTechIDShowEnables] = false, [kTechDataSupply] = kPrototypeLabSupply, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Observatory, [kTechDataSupply] = kObservatorySupply, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.PhaseGate, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.ARCRoboticsFactory, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.RoboticsFactory, [kTechDataSupply] = kRoboticsFactorySupply, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.ArmsLab, [kTechDataSupply] = kArmsLabSupply, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Armory, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.InfantryPortal, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Extractor, [kTechDataRequiresPower] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Harvester, [kTechDataRequiresInfestation] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Crag, [kTechDataRequiresInfestation] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Shift, [kTechDataRequiresInfestation] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Shade, [kTechDataRequiresInfestation] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Veil, [kTechDataNotifyPlayers] = true, [kTechDataSupply] = kVeilSupply, [kTechDataRequiresInfestation] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Spur, [kTechDataNotifyPlayers] = true, [kTechDataSupply] = kSpurSupply, [kTechDataRequiresInfestation] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Shell, [kTechDataNotifyPlayers] = true, [kTechDataSupply] = kShellSupply, [kTechDataRequiresInfestation] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.NutrientMist, [kTechDataRequiresInfestation] = false, [kCommanderSelectRadius] = 0.25 }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportHarvester, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportHydra, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportWhip, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportTunnel, [kTechDataRequiresSecondPlacement] = true, [kTechDataImplemented] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportCrag, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportShade, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportShift, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportVeil, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportSpur, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportShell, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportHive, [kTechDataImplemented] = true, [kTechDataMaxExtents] = Vector(2, 1, 2), [kTechDataCollideWithWorldOnly] = false, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.TeleportEgg, [kTechDataRequiresSecondPlacement] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Hive, [kTechDataBioMass] = 0 }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Egg, [kTechDataRequiresInfestation] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Drifter, [kTechDataBuildTime] = kDrifterBuildTime, [kTechDataResearchTimeKey] = kDrifterBuildTime, [kTechDataCooldown] = kDrifterCooldown }) --[[ table.insert(techIdUpdates, { [kTechDataId] = kTechId.NanoShieldTech, [kTechDataImplemented] = false }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.PowerSurgeTech, [kTechDataImplemented] = false }) --]] table.insert(techIdUpdates, { [kTechDataId] = kTechId.DropHeavyMachineGun, [kStructureAttachId] = { kTechId.Armory, kTechId.AdvancedArmory }, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DropGrenadeLauncher, [kStructureAttachId] = { kTechId.Armory, kTechId.AdvancedArmory }, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DropFlamethrower, [kStructureAttachId] = { kTechId.Armory, kTechId.AdvancedArmory }, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DropShotgun, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DropWelder, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DropMines, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DropJetpack, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.GrenadeLauncher, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Flamethrower, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Shotgun, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DropExosuit, [kStructureAttachId] = kTechId.RoboticsFactory, [kStructureAttachRequiresPower] = false, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Carapace, [kTechDataCategory] = kTechId.DefensiveTraits }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Regeneration, [kTechDataCategory] = kTechId.DefensiveTraits }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Aura, [kTechDataCategory] = kTechId.OffensiveTraits }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Celerity, [kTechDataCategory] = kTechId.MovementTraits }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Adrenaline, [kTechDataCategory] = kTechId.MovementTraits }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Crush, [kTechDataCategory] = kTechId.OffensiveTraits }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.ShiftEnergize, --[kTechDataCooldown] = kShiftEnergizeCooldown, --[kTechDataCostKey] = kShiftEnergizeCost, [kTechDataOneAtATime] = true, }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Weapons1, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Weapons2, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Weapons3, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Armor1, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Armor2, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Armor3, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.JetpackTech, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.MinesTech, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.GrenadeTech, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DualMinigunExosuit, [kTechDataButtonID] = 84 }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.DualRailgunExosuit, [kTechDataButtonID] = 116 }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.LayMines, [kTechDataButtonID] = 8 }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.NanoArmor, [kTechDataButtonID] = 196 }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Leap, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Xenocide, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.GorgeTunnelTech, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.BileBomb, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Spores, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Umbra, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.MetabolizeEnergy, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.MetabolizeHealth, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Stab, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Charge, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.BoneShield, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Stomp, [kTechDataNotifyPlayers] = true }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.HealWave, [kTechDataCooldown] = 0, [kTechDataCostKey] = 0 }) table.insert(techIdUpdates, { [kTechDataId] = kTechId.Cyst, [kTechDataBuildRequiresMethod] = nil, [kTechDataGhostModelClass] = "AlienGhostModel", [kTechDataSupply] = kCystSupply, [kTechDataGrows] = true }) return newTechTable, techIdUpdates end
mit
sajadaltaiee/Raobot
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Messael/Firewolf
old/firewolf 2.4 concept.lua
5
3960
-- Variables local event_exitWebsite = "test_exitWebsiteEvent" local event_waitForLoad = "test_waitForLoadEvent" local noQuitPrefix = ":fn2:" -- -------- Override os.pullEvent local oldpullevent = os.pullEvent local oldEnv = {} local env = {} local api = {} local pullevent = function(data) while true do -- Pull raw local e, p1, p2, p3, p4, p5 = os.pullEventRaw() -- Exit website if needed if e == event_exitWebsite and data:sub(1, noQuitPrefix:len()) ~= noQuitPrefix then error() -- Exit app (Control-T was pressed) elseif e == "terminate" then error() end -- Pass data to website if data and e == data then return e, p1, p2, p3, p4, p5 else return e, p1, p2, p3, p4, p5 end end end -- Prompt from Firewolf with no special exit (event_exitWebsite catcher) api.prompt = function(list) for _, v in pairs(list) do if v.bg then term.setBackgroundColor(v.bg) end if v.tc then term.setTextColor(v.tc) end if v[2] == -1 then v[2] = math.ceil((w + 1)/2 - (v[1]:len() + 6)/2) end term.setCursorPos(v[2], v[3]) write("[- " .. v[1]) term.setCursorPos(v[2] + v[1]:len() + 3, v[3]) write(" -]") end while true do local e, but, x, y = os.pullEvent() if e == "mouse_click" then for _, v in pairs(list) do if x >= v[2] and x <= v[2] + v[1]:len() + 5 and y == v[3] then return v[1] end end end end end api.test = function() print("test") end for k, v in pairs(getfenv(0)) do env[k] = v end for k, v in pairs(getfenv(1)) do env[k] = v end for k, v in pairs(env) do oldEnv[k] = v end for k, v in pairs(api) do env[k] = v end env["os"]["pullEvent"] = pullevent setfenv(1, env) -- -------- Test Website -- Test website with no special exit (event_exitWebsite) local function testSite() while true do print("Hello this is a test website with a prompt that loops over and over again") print("\nThe prompt is the same from Firewolf, but without a special exit feature when you press control") local opt = prompt({{"Testing 1", 3, 10}, {"Testing 2", 3, 11}, {"CRASH THIS SITE", 3, 12}}) print("\n\n You clicked: " .. opt) sleep(1.5) term.clear() term.setCursorPos(1, 1) -- Crash the site to see the error message if opt == "CRASH THIS SITE" then print(nil .. "") end end end -- -------- Loading websites local function websites() while true do -- Clear screen term.clear() term.setCursorPos(1, 1) -- Run the website and catch any errors -- If the site is in the testSite function local _, err = pcall(testSite) -- If the site is in the testsite.lua file --[[local f = io.open("/testsite.lua", "r") local a = f:read("*a") f:close() local fn, err = loadstring(a) if not(err) then setfenv(fn, env) _, err = pcall(fn) end]] if err then -- Print error print("D: " .. err) print("\nYou may now browse normally!") end -- Wait for page reload oldpullevent(event_waitForLoad) end end -- -------- Address Bar local function addressBar() while true do local e, but = oldpullevent() if e == "key" and (but == 29 or but == 157) then -- Exit the website os.queueEvent(event_exitWebsite) -- Clear term.clear() term.setCursorPos(1, 1) -- Read new letters (reset os.pullEvent to avoid quitting) write("rdnt://") os.pullEvent = oldpullevent -- Use noQuitPrefix in modRead instead local web = read() os.pullEvent = pullevent -- If exit if web == "exit" then -- Simulate Control-T os.queueEvent("terminate") return end -- Print entered site print("You entered the website: " .. web) sleep(1.5) -- Load site os.queueEvent(event_waitForLoad) end end end -- -------- Main -- Clear term.clear() term.setCursorPos(1, 1) -- Start the main functions pcall(function() parallel.waitForAll(websites, addressBar) end) -- Print exit message term.clear() term.setCursorPos(1, 1) print("Exited!") setfenv(1, oldEnv) os.pullEvent = oldpullevent
mit
togolwb/skynet
service/launcher.lua
51
3199
local skynet = require "skynet" local core = require "skynet.core" require "skynet.manager" -- import manager apis local string = string local services = {} local command = {} local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK) local function handle_to_address(handle) return tonumber("0x" .. string.sub(handle , 2)) end local NORET = {} function command.LIST() local list = {} for k,v in pairs(services) do list[skynet.address(k)] = v end return list end function command.STAT() local list = {} for k,v in pairs(services) do local stat = skynet.call(k,"debug","STAT") list[skynet.address(k)] = stat end return list end function command.KILL(_, handle) handle = handle_to_address(handle) skynet.kill(handle) local ret = { [skynet.address(handle)] = tostring(services[handle]) } services[handle] = nil return ret end function command.MEM() local list = {} for k,v in pairs(services) do local kb, bytes = skynet.call(k,"debug","MEM") list[skynet.address(k)] = string.format("%.2f Kb (%s)",kb,v) end return list end function command.GC() for k,v in pairs(services) do skynet.send(k,"debug","GC") end return command.MEM() end function command.REMOVE(_, handle, kill) services[handle] = nil local response = instance[handle] if response then -- instance is dead response(not kill) -- return nil to caller of newservice, when kill == false instance[handle] = nil end -- don't return (skynet.ret) because the handle may exit return NORET end local function launch_service(service, ...) local param = table.concat({...}, " ") local inst = skynet.launch(service, param) local response = skynet.response() if inst then services[inst] = service .. " " .. param instance[inst] = response else response(false) return end return inst end function command.LAUNCH(_, service, ...) launch_service(service, ...) return NORET end function command.LOGLAUNCH(_, service, ...) local inst = launch_service(service, ...) if inst then core.command("LOGON", skynet.address(inst)) end return NORET end function command.ERROR(address) -- see serivce-src/service_lua.c -- init failed local response = instance[address] if response then response(false) instance[address] = nil end services[address] = nil return NORET end function command.LAUNCHOK(address) -- init notice local response = instance[address] if response then response(true, address) instance[address] = nil end return NORET end -- for historical reasons, launcher support text command (for C service) skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, unpack = skynet.tostring, dispatch = function(session, address , cmd) if cmd == "" then command.LAUNCHOK(address) elseif cmd == "ERROR" then command.ERROR(address) else error ("Invalid text command " .. cmd) end end, } skynet.dispatch("lua", function(session, address, cmd , ...) cmd = string.upper(cmd) local f = command[cmd] if f then local ret = f(address, ...) if ret ~= NORET then skynet.ret(skynet.pack(ret)) end else skynet.ret(skynet.pack {"Unknown command"} ) end end) skynet.start(function() end)
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm3.lua
15
1199
----------------------------------- -- Area: Alzadaal Undersea Ruins -- NPC: ??? (Spawn Armed Gears(ZNM T3)) -- @pos -42 -4 -169 72 ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(2574,1) and trade:getItemCount() == 1) then -- Trade Ferrite player:tradeComplete(); SpawnMob(17072178,180):updateEnmity(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
msburgess3200/PERP
gamemodes/perp/entities/weapons/weapon_perp_binoculars/shared.lua
1
2586
if SERVER then AddCSLuaFile("shared.lua") end if CLIENT then SWEP.PrintName = "Binoculars" SWEP.Slot = 2 SWEP.SlotPos = 1 SWEP.DrawAmmo = false SWEP.DrawCrosshair = false end SWEP.Author = "RedMist" SWEP.Instructions = "Left Click: Zoom" SWEP.Contact = "" SWEP.Purpose = "" SWEP.ViewModelFlip = false SWEP.Spawnable = false SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = 0 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = 0 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "" SWEP.ViewModel = "models/weapons/v_perpculars.mdl" SWEP.WorldModel = "models/perp2/w_fists.mdl"; SWEP.curZoom = 1; SWEP.ZoomIn = Sound("perp2/binoculars/in.wav"); SWEP.ZoomMax = Sound("perp2/binoculars/max.wav"); SWEP.ZoomOut = Sound("perp2/binoculars/out.wav"); function SWEP:Initialize() self:SetWeaponHoldType("normal") end function SWEP:CanPrimaryAttack ( ) return (self:GetNextPrimaryFire() <= CurTime()); end SWEP.CanSecondaryAttack = SWEP.CanPrimaryFire; local zoomSteps = {70, 35, 20, 5}; local soundsToPlay = {SWEP.ZoomOut, SWEP.ZoomIn, SWEP.ZoomIn, SWEP.ZoomMax}; function SWEP:PrimaryAttack ( Player ) if (!self:CanPrimaryAttack()) then return; end self:SetNextPrimaryFire(CurTime() + .5); self:SetNextSecondaryFire(CurTime() + .5); local curStep = self.curZoom if (zoomSteps[curStep + 1]) then self.curZoom = curStep + 1; else self.curZoom = 1; end self.Owner:SetFOV(zoomSteps[self.curZoom], 0); if CLIENT then return end if (self.curZoom == 1) then self.Owner:DrawViewModel(true); else self.Owner:DrawViewModel(false); end self.Owner:SetPrivateInt("zoom", self.curZoom); end SWEP.SecondaryAttack = SWEP.PrimaryAttack; function SWEP:Think ( ) if (SERVER) then return; end local curZoom = self.Owner:GetPrivateInt("zoom", 1); self.lastZoom = self.lastZoom or 1; if (self.lastZoom != curZoom) then self.lastZoom = curZoom; if (soundsToPlay[curZoom]) then self:EmitSound(soundsToPlay[curZoom]); end self.Owner:SetFOV(zoomSteps[curZoom], 0); if (curZoom == 1) then RunConsoleCommand("pp_mat_overlay", "0"); else RunConsoleCommand("pp_mat_overlay_texture", "effects/combine_binocoverlay.vmt"); RunConsoleCommand("pp_mat_overlay", "1"); end end end function SWEP:Holster ( ) self.Owner:SetFOV(0, 0); self.curZoom = 1; if CLIENT then self.lastZoom = 1; RunConsoleCommand("pp_mat_overlay", "0"); else self.Owner:DrawViewModel(true); end return true; end function SWEP:Reload ( ) end
mit
nehz/busted
busted/init.lua
1
2784
local function init(busted) local block = require 'busted.block'(busted) local file = function(file) busted.wrap(file.run) busted.publish({ 'file', 'start' }, file.name) block.execute('file', file) busted.publish({ 'file', 'end' }, file.name) end local describe = function(describe) local parent = busted.context.parent(describe) busted.publish({ 'describe', 'start' }, describe, parent) block.execute('describe', describe) busted.publish({ 'describe', 'end' }, describe, parent) end local it = function(element) local parent = busted.context.parent(element) local finally if not element.env then element.env = {} end block.rejectAll(element) element.env.finally = function(fn) finally = fn end element.env.pending = function(msg) busted.pending(msg) end local pass, ancestor = block.execAll('before_each', parent, true) if pass then local status = busted.status('success') busted.publish({ 'test', 'start' }, element, parent) status:update(busted.safe('it', element.run, element)) if finally then block.reject('pending', element) status:update(busted.safe('finally', finally, element)) end busted.publish({ 'test', 'end' }, element, parent, tostring(status)) end block.dexecAll('after_each', ancestor, true) end local pending = function(element) local parent = busted.context.parent(element) busted.publish({ 'test', 'start' }, element, parent) busted.publish({ 'test', 'end' }, element, parent, 'pending') end busted.register('file', file) busted.register('describe', describe) busted.register('it', it) busted.register('pending', pending) busted.register('setup') busted.register('teardown') busted.register('before_each') busted.register('after_each') busted.alias('context', 'describe') busted.alias('spec', 'it') busted.alias('test', 'it') local assert = require 'luassert' local spy = require 'luassert.spy' local mock = require 'luassert.mock' local stub = require 'luassert.stub' busted.export('assert', assert) busted.export('spy', spy) busted.export('mock', mock) busted.export('stub', stub) busted.exportApi('publish', busted.publish) busted.exportApi('subscribe', busted.subscribe) busted.exportApi('unsubscribe', busted.unsubscribe) busted.replaceErrorWithFail(assert) busted.replaceErrorWithFail(assert.is_true) return busted end return setmetatable({}, { __call = function(self, busted) init(busted) return setmetatable(self, { __index = function(self, key) return busted.modules[key] end, __newindex = function(self, key, value) error('Attempt to modify busted') end }) end })
mit
sajadaltaiee/Raobot
plugins/supergroup.lua
1
78795
--Begin supergrpup.lua --Check members #Add supergroup local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "Promote me to admin first!") end for k,v in pairs(result) do local member_id = v.peer_id if member_id ~= our_id then -- SuperGroup configuration data[tostring(msg.to.id)] = { group_type = 'SuperGroup', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.title, '_', ' '), lock_arabic = 'no', lock_link = "no", flood = 'yes', lock_spam = 'yes', lock_sticker = 'no', member = 'no', public = 'no', lock_rtl = 'no', lock_contacts = 'no', strict = 'no' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) local text = 'تفعل البوت بكروبك\n\n بعد شتريد هاا هاا😉🐸🐔' return reply_msg(msg.id, text, ok_cb, false) end end end --Check Members #rem supergroup local function check_member_superrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'ليش عطلوتني بالمجموعة😢\n\n والله فقير خوش بوت😢🙏🏻' return reply_msg(msg.id, text, ok_cb, false) end end end --Function to Add supergroup local function superadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg}) end --Function to remove supergroup local function superrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg}) end --Get and output admins and bots in supergroup local function callback(cb_extra, success, result) local i = 1 local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ") local member_type = cb_extra.member_type local text = member_type.." for "..chat_name..":\n" for k,v in pairsByKeys(result) do if not v.first_name then name = " " else vname = v.first_name:gsub("‮", "") name = vname:gsub("_", " ") end text = text.."\n"..i.." - "..name.."["..v.peer_id.."]" i = i + 1 end send_large_msg(cb_extra.receiver, text) end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="Info for SuperGroup: ["..result.title.."]\n\n" local admin_num = "Admin count: "..result.admins_count.."\n" local user_num = "User count: "..result.participants_count.."\n" local kicked_num = "Kicked user count: "..result.kicked_count.."\n" local channel_id = "ID: "..result.peer_id.."\n" if result.username then channel_username = "Username: @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "Members for "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n" local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then name = name.." @"..v.username end text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n" i = i + 1 end local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false) --send_large_msg(cb_extra.receiver, text) end local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'المجموعة 👥 [ '..string.gsub(group_name, '_', ' ')..' ] تم ✅ صناعتها بنجاح 😚👋🏿\n\n بواسطه المطور🔰 : @'..msg.from.username end end --Begin supergroup locks local function lock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return "الروابط مقفولة لتلح✋🏻🔒💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return "تم قفل الروابط 🔒✅💯\n\n بواسطة : @"..msg.from.username end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return "الروابط مفتوحه لتلح🔓✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return "تم فتح الروابط 🔓✅💯\n\n بواسطة : @"..msg.from.username end end local function lock_group_spam(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "Owners only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return "السبام مقفول لتلح 🔒✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return "تم قفل السبام 🔒✅💯\n\n بواسطة : @"..msg.from.username end end local function unlock_group_spam(msg, data, target) if not is_momod(msg) then return end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return "السبام مفتوح لتلح🔓✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return "تم فتح السبام 🔓✅💯\n\n بواسطة : @"..msg.from.username end end local function lock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return "التكرار مقفول لتلح🔒✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return "تم قفل التكرار🔒✅💯\n\n بواسطة : @"..msg.from.username end end local function unlock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return "التكرار مفتوح لتلح 🔓✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return "تم فتح التكرار🔓✅💯\n\n بواسطة : @"..msg.from.username end end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return "اللغة العربية مقفولة لتلح🔒✅💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return "تم قفل اللغة العربية🔒✅💯\n\n بواسطة : @"..msg.from.username end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return "اللغة العربية مفتوحه لتلح🔓✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return "تم فتح اللغة العربية 🔓✅💯\n\n بواسطة : @"..msg.from.username end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return "الاضافة مقفولة لتلح🔒✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return "تم قفل الاضافة🔒✅💯\n\n بواسطة : @"..msg.from.username end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return "الاضافة مفتوحه لتلح 🔓✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return "تم فتح الاضافة 🔓✅💯\n\n بواسطة : @"..msg.from.username end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return "اضافة الجماعه مقفوله لتلح🔒✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return "تم قفل اضافة الجماعه🔒✅💯\n\n بواسطة : @"..msg.from.username end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return "اضافة الجماعه مفتوحه لتلح🔓✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return "تم فتح اضافة الجماعه🔓✅💯\n\n بواسطة : @"..msg.from.username end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return "الملصقات مقفولة لتلح🔒✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return "تم قفل الملصقات🔒✅💯\n\n بواسطة : @"..msg.from.username end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return "الملصقات مفتوحه لتلح 🔓✋🏻💯\n\n بواسطة : @"..msg.from.username else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return "تم فتح الملصقات 🔓✅💯\n\n بواسطة : @"..msg.from.username end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return 'Contact posting is already locked' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact posting has been locked' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return 'Contact posting is already unlocked' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact posting has been unlocked' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'yes' then return 'Settings are already strictly enforced' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'no' then return 'Settings are not strictly enforced' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings will not be strictly enforced' end end --End supergroup locks --'Set supergroup rules' function local function set_rulesmod(msg, data, target) if not is_momod(msg) then return end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'SuperGroup rules set' end --'Get supergroup rules' function local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local group_name = data[tostring(msg.to.id)]['settings']['set_name'] local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ") return rules end --Set supergroup to public or not public function local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings:\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nFlood sensitivity : "..NUM_MSG_MAX.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict return text end local function promote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) end local function demote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) end local function promote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return send_large_msg(receiver, 'SuperGroup is not added.') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been promoted.') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been demoted.') end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'SuperGroup is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end -- Start by reply actions function get_message_callback(extra, success, result) local get_cmd = extra.get_cmd local msg = extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if get_cmd == "id" and not result.action then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]") id1 = send_large_msg(channel, result.from.peer_id) elseif get_cmd == 'id' and result.action then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id else user_id = result.peer_id end local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]") id1 = send_large_msg(channel, user_id) end elseif get_cmd == "idfrom" then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]") id2 = send_large_msg(channel, result.fwd_from.peer_id) elseif get_cmd == 'channel_block' and not result.action then local member_id = result.from.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end --savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply") kick_user(member_id, channel_id) elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then local user_id = result.action.user.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.") kick_user(user_id, channel_id) elseif get_cmd == "del" then delete_msg(result.id, ok_cb, false) savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply") elseif get_cmd == "وضع مشرف" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." set as an admin" else text = "[ "..user_id.." ]set as an admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "تنزيل مشرف" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id if is_admin2(result.from.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." has been demoted from admin" else text = "[ "..user_id.." ] has been demoted from admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "setowner" then local group_owner = data[tostring(result.to.peer_id)]['set_owner'] if group_owner then local channel_id = 'channel#id'..result.to.peer_id if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(channel_id, user, ok_cb, false) end local user_id = "user#id"..result.from.peer_id channel_set_admin(channel_id, user_id, ok_cb, false) data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply") if result.from.username then text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as owner" else text = "[ "..result.from.peer_id.." ] added as owner" end send_large_msg(channel_id, text) end elseif get_cmd == "promote" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") promote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == "demote" then local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id --local user = "user#id"..result.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..user_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_demote(channel_id, user, ok_cb, false) elseif get_cmd == 'mute_user' then if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end if action == 'chat_add_user_link' then if result.from then user_id = result.from.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = msg.to.id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] removed from the muted user list") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") end end end -- End by reply actions --By ID actions local function cb_user_info(extra, success, result) local receiver = extra.receiver local user_id = result.peer_id local get_cmd = extra.get_cmd local data = load_data(_config.moderation.data) --[[if get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" else text = "[ "..result.peer_id.." ] has been set as an admin" end send_large_msg(receiver, text)]] if get_cmd == "تنزيل مشرف" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "You can't demote global admins!") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] has been demoted from admin" send_large_msg(receiver, text) end elseif get_cmd == "promote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "demote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "res" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "id" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "promote" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "demote" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "تنزيل مشرف" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel if is_admin2(result.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been demoted from admin" send_large_msg(channel_id, text) end local receiver = extra.channel local user_id = result.peer_id demote_admin(receiver, member_username, user_id) elseif get_cmd == 'mute_user' then local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end end --End resolve username actions --Begin non-channel_invite username actions local function in_channel_cb(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local msg = cb_extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(cb_extra.msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local member = cb_extra.username local memberid = cb_extra.user_id if member then text = 'No user @'..member..' in this SuperGroup.' else text = 'No user ['..memberid..'] in this SuperGroup.' end if get_cmd == "channel_block" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = v.peer_id local channel_id = cb_extra.msg.to.id local sender = cb_extra.msg.from.id if user_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(user_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end if v.username then text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") else text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") end kick_user(user_id, channel_id) end end elseif get_cmd == "وضع مشرف" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = "user#id"..v.peer_id local channel_id = "channel#id"..cb_extra.msg.to.id channel_set_admin(channel_id, user_id, ok_cb, false) if v.username then text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) end elseif get_cmd == 'وضع مشرف' then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..v.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(v.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username") if result.username then text = member_username.." ["..v.peer_id.."] added as owner" else text = "["..v.peer_id.."] added as owner" end end elseif memberid and vusername ~= member and vpeer_id ~= memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end data[tostring(channel)]['set_owner'] = tostring(memberid) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username") text = "["..memberid.."] added as owner" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Run function local function run(msg, matches) if msg.to.type == 'chat' then if matches[1] == 'خارقة' then if not is_admin1(msg) then return end local receiver = get_receiver(msg) chat_upgrade(receiver, ok_cb, false) end elseif msg.to.type == 'channel'then if matches[1] == 'خارقة' then if not is_admin1(msg) then return end return "المجموعة خارقة وداعت حبنه😑💔" end end if msg.to.type == 'channel' then local support_id = msg.from.id local receiver = get_receiver(msg) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local data = load_data(_config.moderation.data) if matches[1] == 'ويق' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then return reply_msg(msg.id, 'البوت مفعل بكروبك😒\n\n كافي ملحه ملح💔😒', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1] == 'بيق' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if matches[1] == "group info" then if not is_owner(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info") channel_info(receiver, callback_info, {receiver = receiver, msg = msg}) end if matches[1] == "الادمنية" then if not is_owner(msg) and not is_support(msg.from.id) then return end member_type = 'Admins' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list") admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "owner" then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your SuperGroup" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "SuperGroup owner is ["..group_owner..']' end if matches[1] == "المشريفن" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) -- channel_get_admins(receiver,callback, {receiver = receiver}) end if matches[1] == "البوتات" and is_momod(msg) then member_type = 'Bots' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list") channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == 'الرابط خاص' then if not is_momod(msg) then return "👌🏻لتلعَب بكَيفك فقَطَ المدير او الاداري يحَق لهَ✔️" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "❓يرجئ ارسال [/تغير الرابط] لانشاء رابط المجموعه👍🏻✔️" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, "⁉️ رابط مجموعة 👥 "..msg.to.title..'\n'..group_link) return "تم ارسال الرابط الى الخاص 😚👍" end if matches[1] == 'صنع مجموعه' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if matches[1] == "ايدي الاعضاء" and not matches[2] and is_momod(msg) then local user_id = msg.from.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list") channel_get_users(receiver, callback_who, {receiver = receiver}) end if matches[1] == "kicked" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list") channel_get_kicked(receiver, callback_kicked, {receiver = receiver}) end if matches[1] == 'del' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'del', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1] == 'بلوك' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'channel_block', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'بلوك' and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif msg.text:match("@[%a%d]") then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'id' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'id' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") return "SuperGroup ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1] == 'مغادرة' then if msg.to.type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme") channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if matches[1] == 'رابط جديد' and is_momod(msg)then local function callback_link (extra , success, result) local receiver = get_receiver(msg) if success == 0 then send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_link, false) end if matches[1] == 'تغير الرابط' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return 'ارسلي رابط الكروب حتى اجدده❤️👍\n\n واذا متعرف روح ع اضافة الاعضاء واضافة باستخدام رابط الدعوه\n\n انسخ الرابط ودزه🐸👌🏼' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "تم تجديد الرابط✅" end end if matches[1] == 'الرابط' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "اول شي لازم دز امر | تغير الرابط |\n\n وراها اكدر اطلعلك الرابط💞😁" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "رابط ارقى كروب😍❤️👇🏻:\n"..group_link end if matches[1] == "invite" and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1] == 'res' and is_owner(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'res' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username) resolve_username(username, callbackres, cbres_extra) end --[[if matches[1] == 'kick' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) end]] if matches[1] == 'وضع مشرف' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'وضع مشرف', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'وضع مشرف' and string.match(matches[2], '^%d+$') then --[[] local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'setadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]] local get_cmd = 'وضع مشرف' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'وضع مشرف' and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channel = get_receiver(msg), get_cmd = 'setadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'وضع مشرف' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'تنزيل مشرف' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'تنزيل مشرف', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'تنزيل مشرف' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'تنزيل مشرف' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'تنزيل مشرف' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'تنزيل مشرف' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username) resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'وضع مشرف' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setowner', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'وضع مشرف' and string.match(matches[2], '^%d+$') then --[[ local group_owner = data[tostring(msg.to.id)]['set_owner'] if group_owner then local receiver = get_receiver(msg) local user_id = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user_id, ok_cb, false) end local user = "user#id"..matches[2] channel_set_admin(receiver, user, ok_cb, false) data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2]) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = "[ "..matches[2].." ] added as owner" return text end]] local get_cmd = 'setowner' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'وضع مشرف' and not string.match(matches[2], '^%d+$') then local get_cmd = 'setowner' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'وضع مدير' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'وضع مدير' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'وضع مدير' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'mp' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_set_mod(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'md' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'تنزيل مدير' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/support/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'تنزيل مدير' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demote' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == "وضع الاسم" and is_momod(msg) then local receiver = get_receiver(msg) local set_name = string.gsub(matches[2], '_', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2]) rename_channel(receiver, set_name, ok_cb, false) end if msg.service and msg.action.type == 'chat_rename' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title) data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title save_data(_config.moderation.data, data) end if matches[1] == "وضع وصف" and is_momod(msg) then local receiver = get_receiver(msg) local about_text = matches[2] local data_cat = 'description' local target = msg.to.id data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text) channel_set_about(receiver, about_text, ok_cb, false) return "Description has been set.\n\nSelect the chat again to see the changes." end if matches[1] == "وضع معرف" and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.") elseif success == 0 then send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.") end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1] == 'وضع قوانين' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]") return set_rulesmod(msg, data, target) end if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo") load_photo(msg.id, set_supergroup_photo, msg) return end end if matches[1] == 'وضع صورة' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo") return "ارسل صورة حتى احفضها🤖" end if matches[1] == 'clean' then if not is_momod(msg) then return end if not is_momod(msg) then return "Only owner can clean" end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator(s) in this SuperGroup 🔅' end for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") return 'Modlist has been cleaned 🔅' end if matches[2] == 'القوانين' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "Rules have not been set 🔅" end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") return 'Rules have been cleaned 🔅' end if matches[2] == 'about' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'About is not set' end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") channel_set_about(receiver, about_text, ok_cb, false) return "About has been cleaned" end if matches[2] == 'نلصم' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "Mutelist Cleaned" end if matches[2] == 'username' and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username cleaned.") elseif success == 0 then send_large_msg(receiver, "Failed to clean SuperGroup username.") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end end if matches[1] == 'قفل' and is_momod(msg) then local target = msg.to.id if matches[2] == 'الروابط' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'السبام' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'التكرار' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(msg, data, target) end if matches[2] == 'العربية' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'الاضافة' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2]:lower() == 'اضافة الاعضاء' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'الملصقات' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end end if matches[1] == 'فتح' and is_momod(msg) then local target = msg.to.id if matches[2] == 'الروابط' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'السبام' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'التكرار' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(msg, data, target) end if matches[2] == 'العربية' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic") return unlock_group_arabic(msg, data, target) end if matches[2] == 'الاضافة' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2]:lower() == 'اضافة الاعضاء' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'الملصقات' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end end if matches[1] == 'وضع التكرار' then if not is_momod(msg) then return end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Flood has been set to: '..matches[2] end if matches[1] == 'public' and is_momod(msg) then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public") return unset_public_membermod(msg, data, target) end end if matches[1] == 'قفل' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'الصوتيات' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "تم قفل الصوتيات🔒✅💯\n\n بواسطة : @"..msg.from.username else return "الصوتيات مقفولة لتلح 🔒✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الصور' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "تم قفل الصور🔒✅💯\n\n بواسطة : @"..msg.from.username else return "الصور مقفولة لتلح 🔒✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الفيديو' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "تم قفل الفيديوهات🔒✅💯\n\n بواسطة : @"..msg.from.username else return "الفيديوهات مقفولة لتلح🔒✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الصور المتحركة' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "تم قفل الصور المتحركه🔒✅💯\n\n بواسطة : @"..msg.from.username else return "الصور المحتركه مقفولة لتلح 🔒✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الملفات' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "تم قفل ارسال ملفات🔒✅💯\n\n بواسطة : @"..msg.from.username else return "منع ارسال الملفات مقفول لتلح🔒✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الدردشة' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "تم قفل الدردشة🔒✅💯\n\n بواسطة : @"..msg.from.username else return "الدردشة مقفولة لتلح 🔒✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الكل' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "تم قفل الجميع🔇🔕🔒\n\n بواسطة : @"..msg.from.username else return "الجميع مقفول لتلح 🔕🔇🔒💯\n\n بواسطة : @"..msg.from.username end end end if matches[1] == 'فتح' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'الصوتيات' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "تم فتح الصوتيات🔓✅💯\n\n بواسطة : @"..msg.from.username else return "الصوتيات مفتوحه لتلح 🔓✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الصور' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "تم فتح الصور🔓✅💯\n\n بواسطة : @"..msg.from.username else return "الصور مفتوحه لتلح 🔓✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الفيديو' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "تم فتح الفيديوهات 🔓✅💯\n\n بواسطة : @"..msg.from.username else return "الفيديوهات مفتوحه لتلح🔓✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الصور المتحركة' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "تم فتح الصور المتحركه🔓✅💯\n\n بواسطة : @"..msg.from.username else return "الصور المتحركه مفتوحه لتلح🔓✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الملفات' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "تم فتح ارسال الملفات🔓✅💯\n\n بواسطة : @"..msg.from.username else return "ارسال الملفات مفتوحه لتلح🔓✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الدردشة' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message") unmute(chat_id, msg_type) return "تم فتح الدردشة 🔓✅💯\n\n بواسطة : @"..msg.from.username else return "الدردشة مفتوحه لتلح🔓✋🏻💯\n\n بواسطة : @"..msg.from.username end end if matches[2] == 'الكل' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "تم فتح الكل 🔓✅💯\n\n بواسطة : @"..msg.from.username else return "الكل مفتوح لتلح 🔓✅✅\n\n بواسطة : @"..msg.from.username end end end if matches[1] == "نلصم" and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg}) elseif matches[1] == "نلصم" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list") return "["..user_id.."] removed from the muted users list" elseif is_owner(msg) then mute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list") return "["..user_id.."] added to the muted user list" end elseif matches[1] == "نلصم" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg}) end end if matches[1] == "الاعدادات" and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "الاعدادات" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'اعدادات الكروب' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ") return show_supergroup_settingsmod(msg, target) end if matches[1] == 'القوانين' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'helpppp' and not is_owner(msg) then text = "Message /superhelp to @Teleseed in private for SuperGroup help" reply_msg(msg.id, text, ok_cb, false) elseif matches[1] == 'help' and is_owner(msg) then local name_log = user_print_name(msg.from) savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end if matches[1] == 'peer_id' and is_admin1(msg)then text = msg.to.peer_id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end if matches[1] == 'msg.to.id' and is_admin1(msg) then text = msg.to.id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end --Admin Join Service Message if msg.service then local action = msg.action.type if action == 'chat_add_user_link' then if is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.from.id) and not is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup") channel_set_mod(receiver, user, ok_cb, false) end end if action == 'chat_add_user' then if is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_mod(receiver, user, ok_cb, false) end end end if matches[1] == 'msg.to.peer_id' then post_large_msg(receiver, msg.to.peer_id) end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^(ويق)$", "^(بيق)$", "^([Mm]ove) (.*)$", "^(group info)$", "^(الادمنية)$", "^([Oo]wner)$", "^(modlist)$", "^(البوتات)$", "^(ايدي الاعضاء)$", "^([Kk]icked)$", "^(بلوك) (.*)", "^(بلوك)", "^(خارقة)$", --"^([Ii][Dd])$", --"^([Ii][Dd]) (.*)$", "^(مغادرة)$", "^(kicked) (.*)$", "^(رابط جديد)$", "^(تغير الرابط)$", "^(الرابط)$", "^([Rr]es) (.*)$", "^(وضع ادمن) (.*)$", "^(وضع ادمن)", "^(تنزيل مشرف) (.*)$", "^(تنزيل مشرف)", "^(وضع مشرف) (.*)$", "^(وضع مشرف)$", "^(وضع مدير) (.*)$", "^(وضع مدير)", "^(تنزيل مدير) (.*)$", "^(تنزيل مدير)", "^(وضع الاسم) (.*)$", "^(الرابط خاص)$", "^(صنع مجموعه) (.*)$", "^(وضع وصف) (.*)$", "^(وضع قوانين) (.*)$", "^(وضع صورة)$", "^(وضع معرف) (.*)$", "^([Dd]el)$", "^(قفل) (.*)$", "^(فتح) (.*)$", "^(قفل) ([^%s]+)$", "^(فتح) ([^%s]+)$", "^(نلصم)$", "^(نلصم) (.*)$", "^([Pp]ublic) (.*)$", "^(اعدادات الكروب)$", "^(القوانين)$", "^(وضع التكرار) (%d+)$", "^([Cc]lean) (.*)$", "^([Hh])$", "^(الاعدادات)$", "^([Mm]utelist)$", "(mp) (.*)", "(md) (.*)", "^(https://telegram.me/joinchat/%S+)$", "msg.to.peer_id", "%[(الملفات)%]", "%[(الصور)%]", "%[(الفيديد)%]", "%[(الصوتيات)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process } --End supergrpup.lua --By @A7mEd_B98
gpl-2.0
zhouxiaoxiaoxujian/skynet
lualib/skynet/datasheet/dump.lua
20
6547
--[[ file format document : int32 strtbloffset int32 n int32*n index table table*n strings table: int32 array int32 dict int8*(array+dict) type (align 4) value*array kvpair*dict kvpair: string k value v value: (union) int32 integer float real int32 boolean int32 table index int32 string offset type: (enum) 0 nil 1 integer 2 real 3 boolean 4 table 5 string ]] local ctd = {} local math = math local table = table local string = string function ctd.dump(root) local doc = { table_n = 0, table = {}, strings = {}, offset = 0, } local function dump_table(t) local index = doc.table_n + 1 doc.table_n = index doc.table[index] = false -- place holder local array_n = 0 local array = {} local kvs = {} local types = {} local function encode(v) local t = type(v) if t == "table" then local index = dump_table(v) return '\4', string.pack("<i4", index-1) elseif t == "number" then if math.tointeger(v) and v <= 0x7FFFFFFF and v >= -(0x7FFFFFFF+1) then return '\1', string.pack("<i4", v) else return '\2', string.pack("<f",v) end elseif t == "boolean" then if v then return '\3', "\0\0\0\1" else return '\3', "\0\0\0\0" end elseif t == "string" then local offset = doc.strings[v] if not offset then offset = doc.offset doc.offset = offset + #v + 1 doc.strings[v] = offset table.insert(doc.strings, v) end return '\5', string.pack("<I4", offset) else error ("Unsupport value " .. tostring(v)) end end for i,v in ipairs(t) do types[i], array[i] = encode(v) array_n = i end for k,v in pairs(t) do if type(k) == "string" then local _, kv = encode(k) local tv, ev = encode(v) table.insert(types, tv) table.insert(kvs, kv .. ev) else local ik = math.tointeger(k) assert(ik and ik > 0 and ik <= array_n) end end -- encode table local typeset = table.concat(types) local align = string.rep("\0", (4 - #typeset & 3) & 3) local tmp = { string.pack("<i4i4", array_n, #kvs), typeset, align, table.concat(array), table.concat(kvs), } doc.table[index] = table.concat(tmp) return index end dump_table(root) -- encode document local index = {} local offset = 0 for i, v in ipairs(doc.table) do index[i] = string.pack("<I4", offset) offset = offset + #v end local tmp = { string.pack("<I4", 4 + 4 + 4 * doc.table_n + offset), string.pack("<I4", doc.table_n), table.concat(index), table.concat(doc.table), table.concat(doc.strings, "\0"), "\0", } return table.concat(tmp) end function ctd.undump(v) local stringtbl, n = string.unpack("<I4I4",v) local index = { string.unpack("<" .. string.rep("I4", n), v, 9) } local header = 4 + 4 + 4 * n + 1 stringtbl = stringtbl + 1 local tblidx = {} local function decode(n) local toffset = index[n+1] + header local array, dict = string.unpack("<I4I4", v, toffset) local types = { string.unpack(string.rep("B", (array+dict)), v, toffset + 8) } local offset = ((array + dict + 8 + 3) & ~3) + toffset local result = {} local function value(t) local off = offset offset = offset + 4 if t == 1 then -- integer return (string.unpack("<i4", v, off)) elseif t == 2 then -- float return (string.unpack("<f", v, off)) elseif t == 3 then -- boolean return string.unpack("<i4", v, off) ~= 0 elseif t == 4 then -- table local tindex = (string.unpack("<I4", v, off)) return decode(tindex) elseif t == 5 then -- string local sindex = string.unpack("<I4", v, off) return (string.unpack("z", v, stringtbl + sindex)) else error (string.format("Invalid data at %d (%d)", off, t)) end end for i=1,array do table.insert(result, value(types[i])) end for i=1,dict do local sindex = string.unpack("<I4", v, offset) offset = offset + 4 local key = string.unpack("z", v, stringtbl + sindex) result[key] = value(types[array + i]) end tblidx[result] = n return result end return decode(0), tblidx end local function diffmap(last, current) local lastv, lasti = ctd.undump(last) local curv, curi = ctd.undump(current) local map = {} -- new(current index):old(last index) local function comp(lastr, curr) local old = lasti[lastr] local new = curi[curr] map[new] = old for k,v in pairs(lastr) do if type(v) == "table" then local newv = curr[k] if type(newv) == "table" then comp(v, newv) end end end end comp(lastv, curv) return map end function ctd.diff(last, current) local map = diffmap(last, current) local stringtbl, n = string.unpack("<I4I4",current) local _, lastn = string.unpack("<I4I4",last) local existn = 0 for k,v in pairs(map) do existn = existn + 1 end local newn = lastn for i = 0, n-1 do if not map[i] then map[i] = newn newn = newn + 1 end end -- remap current local index = { string.unpack("<" .. string.rep("I4", n), current, 9) } local header = 4 + 4 + 4 * n + 1 local function remap(n) local toffset = index[n+1] + header local array, dict = string.unpack("<I4I4", current, toffset) local types = { string.unpack(string.rep("B", (array+dict)), current, toffset + 8) } local hlen = (array + dict + 8 + 3) & ~3 local hastable = false for _, v in ipairs(types) do if v == 4 then -- table hastable = true break end end if not hastable then return string.sub(current, toffset, toffset + hlen + (array + dict * 2) * 4 - 1) end local offset = hlen + toffset local pat = "<" .. string.rep("I4", array + dict * 2) local values = { string.unpack(pat, current, offset) } for i = 1, array do if types[i] == 4 then -- table values[i] = map[values[i]] end end for i = 1, dict do if types[i + array] == 4 then -- table values[array + i * 2] = map[values[array + i * 2]] end end return string.sub(current, toffset, toffset + hlen - 1) .. string.pack(pat, table.unpack(values)) end -- rebuild local oldindex = { string.unpack("<" .. string.rep("I4", n), current, 9) } local index = {} for i = 1, newn do index[i] = 0xffffffff end for i = 0, #map do index[map[i]+1] = oldindex[i+1] end local tmp = { string.pack("<I4I4", stringtbl + (newn - n) * 4, newn), -- expand index table string.pack("<" .. string.rep("I4", newn), table.unpack(index)), } for i = 0, n - 1 do table.insert(tmp, remap(i)) end table.insert(tmp, string.sub(current, stringtbl+1)) return table.concat(tmp) end return ctd
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Inner_Horutoto_Ruins/npcs/_5c0_.lua
36
1765
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Mahogany Door -- Involved In Quest: Making Headlines -- Working 100% -- Unable to find EventID for Making Headlines quest. Used dialog ID instead. ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ function testflag(set,flag) return (set % (2*flag) >= flag) end MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); if (MakingHeadlines == 1) then prog = player:getVar("QuestMakingHeadlines_var"); if (testflag(tonumber(prog),16) == false and testflag(tonumber(prog),8) == true) then player:messageSpecial(7208,1,WINDURST_WOODS_SCOOP); -- Confirm Story player:setVar("QuestMakingHeadlines_var",prog+16); else player:startEvent(0x002c); -- "The door is firmly shut" end else player:startEvent(0x002c); -- "The door is firmly shut" end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
msburgess3200/PERP
gamemodes/perp/gamemode/sv_modules/job_medic.lua
1
3760
GM.JobPaydayInfo[TEAM_MEDIC] = {"as a paycheck for being a paramedic.", 100}; GM.JobEquips[TEAM_MEDIC] = function ( Player ) Player:Give("weapon_perp_paramedic_defib"); Player:Give("weapon_perp_paramedic_health"); end function GM.Medic_Join ( Player ) if (Player:HasBlacklist(GAMEMODE.teamToBlacklist[TEAM_MEDIC])) then return; end if (!Player:NearNPC(13)) then return; end if (Player:Team() != TEAM_CITIZEN) then return; end if (Player.RunningForMayor) then return; end if (Player:GetNetworkedBool("warrent", false)) then return; end if (team.NumPlayers(TEAM_MEDIC) >= GAMEMODE.MaximumParamedic) then return; end if (Player:GetTimePlayed() < GAMEMODE.RequiredTime_Paramedic * 60 * 60 && !Player:IsBronze()) then return end Player:SetTeam(TEAM_MEDIC); Player:RemoveCar(); for k, v in pairs(player.GetAll()) do umsg.Start("removebadid", Player) umsg.Short(Player:GetCarUsed()); // Fuel Left umsg.End() end GAMEMODE.JobEquips[TEAM_MEDIC](Player); Player.JobModel = JOB_MODELS[TEAM_MEDIC][Player:GetSex()][Player:GetFace()] or JOB_MODELS[TEAM_MEDIC][SEX_MALE][1]; Player:SetModel(Player.JobModel); Player:StripMains(); end concommand.Add("perp_m_j", GM.Medic_Join); function GM.Medic_Quit ( Player ) if (!Player:NearNPC(13)) then return; end GAMEMODE.Medic_Leave(Player); end concommand.Add("perp_m_q", GM.Medic_Quit); function GM.Medic_Leave ( Player ) Player:SetTeam(TEAM_CITIZEN); Player:StripWeapon("weapon_perp_paramedic_defib"); Player:StripWeapon("weapon_perp_paramedic_health"); Player:RemoveCar(); Player.JobModel = nil; Player:SetModel(Player.PlayerModel); Player:EquipMains() end function GM.Medic_SpawnCar ( Player ) if (Player:Team() != TEAM_MEDIC) then return; end if (!Player:NearNPC(13)) then return; end local numFireCars = 0; for k, v in pairs(ents.FindByClass("prop_vehicle_jeep")) do if (v.vehicleTable && v.vehicleTable.RequiredClass == TEAM_MEDIC && v:GetNetworkedEntity("owner", nil) != Player) then numFireCars = numFireCars + 1; end end if (!Player:IsBronze() && numFireCars >= GAMEMODE.MaxAmbulances) then return; end GAMEMODE.SpawnVehicle(Player, "w", {1, 1, 0, 0}) end concommand.Add("perp_m_c", GM.Medic_SpawnCar); function GM.Medic_DoDefib ( Player, Cmd, Args ) if (!Player) then return; end if (!Args[1]) then return; end // if (Player:Team() != TEAM_MEDIC) then return; end // Removed to make godstick revive function properly. local theirUniqueID = Args[1]; local toHeal; for k, v in pairs(player.GetAll()) do if (v:UniqueID() == theirUniqueID) then toHeal = v; end end if (!toHeal) then return; end if (toHeal:Alive()) then return; end if (Player:GetPos():Distance(toHeal.DeathPos) > 500) then return; end toHeal.RequiredDefib = toHeal.RequiredDefib - 1; if (toHeal.RequiredDefib > 0) then return; end toHeal.DontFixCripple = true; toHeal:Spawn(); toHeal:Notify("You have been revived by a medic."); toHeal:SetPos(toHeal.DeathPos); Player:GiveCash(50); Player:Notify("You have earned $50 for respawning a player."); Player:GiveExperience(SKILL_FIRST_AID, 10); end concommand.Add("perp_m_h", GM.Medic_DoDefib); function GM.Medic_FinishPlayer ( Player, Cmd, Args ) if (!Player) then return; end if (!Args[1]) then return; end local theirUniqueID = Args[1]; local toHeal; for k, v in pairs(player.GetAll()) do if (v:UniqueID() == theirUniqueID) then toHeal = v; end end if (!toHeal) then return; end if (toHeal:Alive()) then return; end if (Player:GetPos():Distance(toHeal.DeathPos) > 500) then return; end Player.DontFixCripple = nil; toHeal:Spawn(); toHeal:Notify("You have been finished off by a bullet to the head."); end concommand.Add("perp_m_k", GM.Medic_FinishPlayer);
mit
daofeng2015/luci
libs/luci-lib-nixio/docsrc/nixio.File.lua
173
4457
--- Large File Object. -- Large file operations are supported up to 52 bits if the Lua number type is -- double (default). -- @cstyle instance module "nixio.File" --- Write to the file descriptor. -- @class function -- @name File.write -- @usage <strong>Warning:</strong> It is not guaranteed that all data -- in the buffer is written at once especially when dealing with pipes. -- You have to check the return value - the number of bytes actually written - -- or use the safe IO functions in the high-level IO utility module. -- @usage Unlike standard Lua indexing the lowest offset and default is 0. -- @param buffer Buffer holding the data to be written. -- @param offset Offset to start reading the buffer from. (optional) -- @param length Length of chunk to read from the buffer. (optional) -- @return number of bytes written --- Read from a file descriptor. -- @class function -- @name File.read -- @usage <strong>Warning:</strong> It is not guaranteed that all requested data -- is read at once especially when dealing with pipes. -- You have to check the return value - the length of the buffer actually read - -- or use the safe IO functions in the high-level IO utility module. -- @usage The length of the return buffer is limited by the (compile time) -- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default). -- Any read request greater than that will be safely truncated to this value. -- @param length Amount of data to read (in Bytes). -- @return buffer containing data successfully read --- Reposition read / write offset of the file descriptor. -- The seek will be done either from the beginning of the file or relative -- to the current position or relative to the end. -- @class function -- @name File.seek -- @usage This function calls lseek(). -- @param offset File Offset -- @param whence Starting point [<strong>"set"</strong>, "cur", "end"] -- @return new (absolute) offset position --- Return the current read / write offset of the file descriptor. -- @class function -- @name File.tell -- @usage This function calls lseek() with offset 0 from the current position. -- @return offset position --- Synchronizes the file with the storage device. -- Returns when the file is successfully written to the disk. -- @class function -- @name File.sync -- @usage This function calls fsync() when data_only equals false -- otherwise fdatasync(), on Windows _commit() is used instead. -- @usage fdatasync() is only supported by Linux and Solaris. For other systems -- the <em>data_only</em> parameter is ignored and fsync() is always called. -- @param data_only Do not synchronize the metadata. (optional, boolean) -- @return true --- Apply or test a lock on the file. -- @class function -- @name File.lock -- @usage This function calls lockf() on POSIX and _locking() on Windows. -- @usage The "lock" command is blocking, "tlock" is non-blocking, -- "ulock" unlocks and "test" only tests for the lock. -- @usage The "test" command is not available on Windows. -- @usage Locks are by default advisory on POSIX, but mandatory on Windows. -- @param command Locking Command ["lock", "tlock", "ulock", "test"] -- @param length Amount of Bytes to lock from current offset (optional) -- @return true --- Get file status and attributes. -- @class function -- @name File.stat -- @param field Only return a specific field, not the whole table (optional) -- @usage This function calls fstat(). -- @return Table containing: <ul> -- <li>atime = Last access timestamp</li> -- <li>blksize = Blocksize (POSIX only)</li> -- <li>blocks = Blocks used (POSIX only)</li> -- <li>ctime = Creation timestamp</li> -- <li>dev = Device ID</li> -- <li>gid = Group ID</li> -- <li>ino = Inode</li> -- <li>modedec = Mode converted into a decimal number</li> -- <li>modestr = Mode as string as returned by `ls -l`</li> -- <li>mtime = Last modification timestamp</li> -- <li>nlink = Number of links</li> -- <li>rdev = Device ID (if special file)</li> -- <li>size = Size in bytes</li> -- <li>type = ["reg", "dir", "chr", "blk", "fifo", "lnk", "sock"]</li> -- <li>uid = User ID</li> -- </ul> --- Close the file descriptor. -- @class function -- @name File.close -- @return true --- Get the number of the filedescriptor. -- @class function -- @name File.fileno -- @return file descriptor number --- (POSIX) Set the blocking mode of the file descriptor. -- @class function -- @name File.setblocking -- @param blocking (boolean) -- @return true
apache-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Port_San_dOria/npcs/Dabbio.lua
38
1036
----------------------------------- -- Area: Port San d'Oria -- NPC: Dabbio -- Type: Standard NPC -- @zone: 232 -- @pos -7.819 -15 -106.990 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02d2); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
hb9cwp/snabbswitch
lib/ljsyscall/syscall/linux/c.lua
10
40227
-- This sets up the table of C functions -- this should be generated ideally, as it is the ABI spec --[[ Note a fair number are being deprecated, see include/uapi/asm-generic/unistd.h under __ARCH_WANT_SYSCALL_NO_AT, __ARCH_WANT_SYSCALL_NO_FLAGS, and __ARCH_WANT_SYSCALL_DEPRECATED Some of these we already don't use, but some we do, eg use open not openat etc. ]] local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select local abi = require "syscall.abi" local ffi = require "ffi" local bit = require "syscall.bit" require "syscall.linux.ffi" local voidp = ffi.typeof("void *") local function void(x) return ffi.cast(voidp, x) end -- basically all types passed to syscalls are int or long, so we do not need to use nicely named types, so we can avoid importing t. local int, long = ffi.typeof("int"), ffi.typeof("long") local uint, ulong = ffi.typeof("unsigned int"), ffi.typeof("unsigned long") local h = require "syscall.helpers" local err64 = h.err64 local errpointer = h.errpointer local i6432, u6432 = bit.i6432, bit.u6432 local arg64, arg64u if abi.le then arg64 = function(val) local v2, v1 = i6432(val) return v1, v2 end arg64u = function(val) local v2, v1 = u6432(val) return v1, v2 end else arg64 = function(val) return i6432(val) end arg64u = function(val) return u6432(val) end end -- _llseek very odd, preadv local function llarg64u(val) return u6432(val) end local function llarg64(val) return i6432(val) end local C = {} local nr = require("syscall.linux.nr") local zeropad = nr.zeropad local sys = nr.SYS local socketcalls = nr.socketcalls local u64 = ffi.typeof("uint64_t") -- TODO could make these return errno here, also are these best casts? local syscall_long = ffi.C.syscall -- returns long local function syscall(...) return tonumber(syscall_long(...)) end -- int is default as most common local function syscall_uint(...) return uint(syscall_long(...)) end local function syscall_void(...) return void(syscall_long(...)) end local function syscall_off(...) return u64(syscall_long(...)) end -- off_t local longstype = ffi.typeof("long[?]") local function longs(...) local n = select('#', ...) local ll = ffi.new(longstype, n) for i = 1, n do ll[i - 1] = ffi.cast(long, select(i, ...)) end return ll end -- now for the system calls -- use 64 bit fileops on 32 bit always. As may be missing will use syscalls directly if abi.abi32 then if zeropad then function C.truncate(path, length) local len1, len2 = arg64u(length) return syscall(sys.truncate64, path, int(0), long(len1), long(len2)) end function C.ftruncate(fd, length) local len1, len2 = arg64u(length) return syscall(sys.ftruncate64, int(fd), int(0), long(len1), long(len2)) end function C.readahead(fd, offset, count) local off1, off2 = arg64u(offset) return syscall(sys.readahead, int(fd), int(0), long(off1), long(off2), ulong(count)) end function C.pread(fd, buf, size, offset) local off1, off2 = arg64(offset) return syscall_long(sys.pread64, int(fd), void(buf), ulong(size), int(0), long(off1), long(off2)) end function C.pwrite(fd, buf, size, offset) local off1, off2 = arg64(offset) return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(size), int(0), long(off1), long(off2)) end else function C.truncate(path, length) local len1, len2 = arg64u(length) return syscall(sys.truncate64, path, long(len1), long(len2)) end function C.ftruncate(fd, length) local len1, len2 = arg64u(length) return syscall(sys.ftruncate64, int(fd), long(len1), long(len2)) end function C.readahead(fd, offset, count) local off1, off2 = arg64u(offset) return syscall(sys.readahead, int(fd), long(off1), long(off2), ulong(count)) end function C.pread(fd, buf, size, offset) local off1, off2 = arg64(offset) return syscall_long(sys.pread64, int(fd), void(buf), ulong(size), long(off1), long(off2)) end function C.pwrite(fd, buf, size, offset) local off1, off2 = arg64(offset) return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(size), long(off1), long(off2)) end end -- note statfs,fstatfs pass size of struct on 32 bit only function C.statfs(path, buf) return syscall(sys.statfs64, void(path), uint(ffi.sizeof(buf)), void(buf)) end function C.fstatfs(fd, buf) return syscall(sys.fstatfs64, int(fd), uint(ffi.sizeof(buf)), void(buf)) end -- Note very odd split 64 bit arguments even on 64 bit platform. function C.preadv(fd, iov, iovcnt, offset) local off1, off2 = llarg64(offset) return syscall_long(sys.preadv, int(fd), void(iov), int(iovcnt), long(off2), long(off1)) end function C.pwritev(fd, iov, iovcnt, offset) local off1, off2 = llarg64(offset) return syscall_long(sys.pwritev, int(fd), void(iov), int(iovcnt), long(off2), long(off1)) end -- lseek is a mess in 32 bit, use _llseek syscall to get clean result. -- TODO move this to syscall.lua local off1 = ffi.typeof("uint64_t[1]") function C.lseek(fd, offset, whence) local result = off1() local off1, off2 = llarg64(offset) local ret = syscall(sys._llseek, int(fd), long(off1), long(off2), void(result), uint(whence)) if ret == -1 then return err64 end return result[0] end function C.sendfile(outfd, infd, offset, count) return syscall_long(sys.sendfile64, int(outfd), int(infd), void(offset), ulong(count)) end -- on 32 bit systems mmap uses off_t so we cannot tell what ABI is. Use underlying mmap2 syscall function C.mmap(addr, length, prot, flags, fd, offset) local pgoffset = bit.rshift(offset, 12) return syscall_void(sys.mmap2, void(addr), ulong(length), int(prot), int(flags), int(fd), uint(pgoffset)) end else -- 64 bit function C.truncate(path, length) return syscall(sys.truncate, void(path), ulong(length)) end function C.ftruncate(fd, length) return syscall(sys.ftruncate, int(fd), ulong(length)) end function C.readahead(fd, offset, count) return syscall(sys.readahead, int(fd), ulong(offset), ulong(count)) end function C.pread(fd, buf, count, offset) return syscall_long(sys.pread64, int(fd), void(buf), ulong(count), ulong(offset)) end function C.pwrite(fd, buf, count, offset) return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(count), ulong(offset)) end function C.statfs(path, buf) return syscall(sys.statfs, void(path), void(buf)) end function C.fstatfs(fd, buf) return syscall(sys.fstatfs, int(fd), void(buf)) end function C.preadv(fd, iov, iovcnt, offset) return syscall_long(sys.preadv, int(fd), void(iov), long(iovcnt), ulong(offset)) end function C.pwritev(fd, iov, iovcnt, offset) return syscall_long(sys.pwritev, int(fd), void(iov), long(iovcnt), ulong(offset)) end function C.lseek(fd, offset, whence) return syscall_off(sys.lseek, int(fd), ulong(offset), int(whence)) end function C.sendfile(outfd, infd, offset, count) return syscall_long(sys.sendfile, int(outfd), int(infd), void(offset), ulong(count)) end function C.mmap(addr, length, prot, flags, fd, offset) return syscall_void(sys.mmap, void(addr), ulong(length), int(prot), int(flags), int(fd), ulong(offset)) end end -- glibc caches pid, but this fails to work eg after clone(). function C.getpid() return syscall(sys.getpid) end -- underlying syscalls function C.exit_group(status) return syscall(sys.exit_group, int(status)) end -- void return really function C.exit(status) return syscall(sys.exit, int(status)) end -- void return really C._exit = C.exit_group -- standard method -- clone interface provided is not same as system one, and is less convenient function C.clone(flags, signal, stack, ptid, tls, ctid) return syscall(sys.clone, int(flags), void(stack), void(ptid), void(tls), void(ctid)) -- technically long end -- getdents is not provided by glibc. Musl has weak alias so not visible. function C.getdents(fd, buf, size) return syscall(sys.getdents64, int(fd), buf, uint(size)) end -- glibc has request as an unsigned long, kernel is unsigned int, other libcs are int, so use syscall directly function C.ioctl(fd, request, arg) return syscall(sys.ioctl, int(fd), uint(request), void(arg)) end -- getcwd in libc may allocate memory and has inconsistent return value, so use syscall function C.getcwd(buf, size) return syscall(sys.getcwd, void(buf), ulong(size)) end -- nice in libc may or may not return old value, syscall never does; however nice syscall may not exist if sys.nice then function C.nice(inc) return syscall(sys.nice, int(inc)) end end -- avoid having to set errno by calling getpriority directly and adjusting return values function C.getpriority(which, who) return syscall(sys.getpriority, int(which), int(who)) end -- uClibc only provides a version of eventfd without flags, and we cannot detect this function C.eventfd(initval, flags) return syscall(sys.eventfd2, uint(initval), int(flags)) end -- Musl always returns ENOSYS for these function C.sched_getscheduler(pid) return syscall(sys.sched_getscheduler, int(pid)) end function C.sched_setscheduler(pid, policy, param) return syscall(sys.sched_setscheduler, int(pid), int(policy), void(param)) end local sys_fadvise64 = sys.fadvise64_64 or sys.fadvise64 if abi.abi64 then if sys.stat then function C.stat(path, buf) return syscall(sys.stat, path, void(buf)) end end if sys.lstat then function C.lstat(path, buf) return syscall(sys.lstat, path, void(buf)) end end function C.fstat(fd, buf) return syscall(sys.fstat, int(fd), void(buf)) end function C.fstatat(fd, path, buf, flags) return syscall(sys.fstatat, int(fd), path, void(buf), int(flags)) end function C.fadvise64(fd, offset, len, advise) return syscall(sys_fadvise64, int(fd), ulong(offset), ulong(len), int(advise)) end function C.fallocate(fd, mode, offset, len) return syscall(sys.fallocate, int(fd), uint(mode), ulong(offset), ulong(len)) end else function C.stat(path, buf) return syscall(sys.stat64, path, void(buf)) end function C.lstat(path, buf) return syscall(sys.lstat64, path, void(buf)) end function C.fstat(fd, buf) return syscall(sys.fstat64, int(fd), void(buf)) end function C.fstatat(fd, path, buf, flags) return syscall(sys.fstatat64, int(fd), path, void(buf), int(flags)) end if zeropad then function C.fadvise64(fd, offset, len, advise) local off1, off2 = arg64u(offset) local len1, len2 = arg64u(len) return syscall(sys_fadvise64, int(fd), 0, uint(off1), uint(off2), uint(len1), uint(len2), int(advise)) end else function C.fadvise64(fd, offset, len, advise) local off1, off2 = arg64u(offset) local len1, len2 = arg64u(len) return syscall(sys_fadvise64, int(fd), uint(off1), uint(off2), uint(len1), uint(len2), int(advise)) end end function C.fallocate(fd, mode, offset, len) local off1, off2 = arg64u(offset) local len1, len2 = arg64u(len) return syscall(sys.fallocate, int(fd), uint(mode), uint(off1), uint(off2), uint(len1), uint(len2)) end end -- native Linux aio not generally supported by libc, only posix API function C.io_setup(nr_events, ctx) return syscall(sys.io_setup, uint(nr_events), void(ctx)) end function C.io_destroy(ctx) return syscall(sys.io_destroy, ulong(ctx)) end function C.io_cancel(ctx, iocb, result) return syscall(sys.io_cancel, ulong(ctx), void(iocb), void(result)) end function C.io_getevents(ctx, min, nr, events, timeout) return syscall(sys.io_getevents, ulong(ctx), long(min), long(nr), void(events), void(timeout)) end function C.io_submit(ctx, iocb, nr) return syscall(sys.io_submit, ulong(ctx), long(nr), void(iocb)) end -- mq functions in -rt for glibc, plus syscalls differ slightly function C.mq_open(name, flags, mode, attr) return syscall(sys.mq_open, void(name), int(flags), uint(mode), void(attr)) end function C.mq_unlink(name) return syscall(sys.mq_unlink, void(name)) end function C.mq_getsetattr(mqd, new, old) return syscall(sys.mq_getsetattr, int(mqd), void(new), void(old)) end function C.mq_timedsend(mqd, msg_ptr, msg_len, msg_prio, abs_timeout) return syscall(sys.mq_timedsend, int(mqd), void(msg_ptr), ulong(msg_len), uint(msg_prio), void(abs_timeout)) end function C.mq_timedreceive(mqd, msg_ptr, msg_len, msg_prio, abs_timeout) return syscall(sys.mq_timedreceive, int(mqd), void(msg_ptr), ulong(msg_len), void(msg_prio), void(abs_timeout)) end if sys.mknod then function C.mknod(pathname, mode, dev) return syscall(sys.mknod, pathname, uint(mode), uint(dev)) end end function C.mknodat(fd, pathname, mode, dev) return syscall(sys.mknodat, int(fd), pathname, uint(mode), uint(dev)) end -- pivot_root is not provided by glibc, is provided by Musl function C.pivot_root(new_root, put_old) return syscall(sys.pivot_root, new_root, put_old) end -- setns not in some glibc versions function C.setns(fd, nstype) return syscall(sys.setns, int(fd), int(nstype)) end -- prlimit64 not in my ARM glibc function C.prlimit64(pid, resource, new_limit, old_limit) return syscall(sys.prlimit64, int(pid), int(resource), void(new_limit), void(old_limit)) end -- sched_setaffinity and sched_getaffinity not in Musl at the moment, use syscalls. Could test instead. function C.sched_getaffinity(pid, len, mask) return syscall(sys.sched_getaffinity, int(pid), uint(len), void(mask)) end function C.sched_setaffinity(pid, len, mask) return syscall(sys.sched_setaffinity, int(pid), uint(len), void(mask)) end -- sched_setparam and sched_getparam in Musl return ENOSYS, probably as they work on threads not processes. function C.sched_getparam(pid, param) return syscall(sys.sched_getparam, int(pid), void(param)) end function C.sched_setparam(pid, param) return syscall(sys.sched_setparam, int(pid), void(param)) end -- in librt for glibc but use syscalls instead of loading another library function C.clock_nanosleep(clk_id, flags, req, rem) return syscall(sys.clock_nanosleep, int(clk_id), int(flags), void(req), void(rem)) end function C.clock_getres(clk_id, ts) return syscall(sys.clock_getres, int(clk_id), void(ts)) end function C.clock_settime(clk_id, ts) return syscall(sys.clock_settime, int(clk_id), void(ts)) end -- glibc will not call this with a null path, which is needed to implement futimens in Linux function C.utimensat(fd, path, times, flags) return syscall(sys.utimensat, int(fd), void(path), void(times), int(flags)) end -- not in Android Bionic function C.linkat(olddirfd, oldpath, newdirfd, newpath, flags) return syscall(sys.linkat, int(olddirfd), void(oldpath), int(newdirfd), void(newpath), int(flags)) end function C.symlinkat(oldpath, newdirfd, newpath) return syscall(sys.symlinkat, void(oldpath), int(newdirfd), void(newpath)) end function C.readlinkat(dirfd, pathname, buf, bufsiz) return syscall(sys.readlinkat, int(dirfd), void(pathname), void(buf), ulong(bufsiz)) end function C.inotify_init1(flags) return syscall(sys.inotify_init1, int(flags)) end function C.adjtimex(buf) return syscall(sys.adjtimex, void(buf)) end function C.epoll_create1(flags) return syscall(sys.epoll_create1, int(flags)) end if sys.epoll_wait then function C.epoll_wait(epfd, events, maxevents, timeout) return syscall(sys.epoll_wait, int(epfd), void(events), int(maxevents), int(timeout)) end end function C.swapon(path, swapflags) return syscall(sys.swapon, void(path), int(swapflags)) end function C.swapoff(path) return syscall(sys.swapoff, void(path)) end function C.timerfd_create(clockid, flags) return syscall(sys.timerfd_create, int(clockid), int(flags)) end function C.timerfd_settime(fd, flags, new_value, old_value) return syscall(sys.timerfd_settime, int(fd), int(flags), void(new_value), void(old_value)) end function C.timerfd_gettime(fd, curr_value) return syscall(sys.timerfd_gettime, int(fd), void(curr_value)) end function C.splice(fd_in, off_in, fd_out, off_out, len, flags) return syscall(sys.splice, int(fd_in), void(off_in), int(fd_out), void(off_out), ulong(len), uint(flags)) end function C.tee(src, dest, len, flags) return syscall(sys.tee, int(src), int(dest), ulong(len), uint(flags)) end function C.vmsplice(fd, iovec, cnt, flags) return syscall(sys.vmsplice, int(fd), void(iovec), ulong(cnt), uint(flags)) end -- TODO note that I think these may be incorrect on 32 bit platforms, and strace is buggy if sys.sync_file_range then if abi.abi64 then function C.sync_file_range(fd, pos, len, flags) return syscall(sys.sync_file_range, int(fd), long(pos), long(len), uint(flags)) end else if zeropad then -- only on mips function C.sync_file_range(fd, pos, len, flags) local pos1, pos2 = arg64(pos) local len1, len2 = arg64(len) -- TODO these args appear to be reversed but is this mistaken/endianness/also true elsewhere? strace broken... return syscall(sys.sync_file_range, int(fd), 0, long(pos2), long(pos1), long(len2), long(len1), uint(flags)) end else function C.sync_file_range(fd, pos, len, flags) local pos1, pos2 = arg64(pos) local len1, len2 = arg64(len) return syscall(sys.sync_file_range, int(fd), long(pos1), long(pos2), long(len1), long(len2), uint(flags)) end end end elseif sys.sync_file_range2 then -- only on 32 bit platforms function C.sync_file_range(fd, pos, len, flags) local pos1, pos2 = arg64(pos) local len1, len2 = arg64(len) return syscall(sys.sync_file_range2, int(fd), uint(flags), long(pos1), long(pos2), long(len1), long(len2)) end end -- TODO this should be got from somewhere more generic -- started moving into linux/syscall.lua som explicit (see signalfd) but needs some more cleanups local sigset_size = 8 if abi.arch == "mips" or abi.arch == "mipsel" then sigset_size = 16 end local function sigmasksize(sigmask) local size = 0 if sigmask then size = sigset_size end return ulong(size) end function C.epoll_pwait(epfd, events, maxevents, timeout, sigmask) return syscall(sys.epoll_pwait, int(epfd), void(events), int(maxevents), int(timeout), void(sigmask), sigmasksize(sigmask)) end function C.ppoll(fds, nfds, timeout_ts, sigmask) return syscall(sys.ppoll, void(fds), ulong(nfds), void(timeout_ts), void(sigmask), sigmasksize(sigmask)) end function C.signalfd(fd, mask, size, flags) return syscall(sys.signalfd4, int(fd), void(mask), ulong(size), int(flags)) end -- adding more function C.dup(oldfd) return syscall(sys.dup, int(oldfd)) end if sys.dup2 then function C.dup2(oldfd, newfd) return syscall(sys.dup2, int(oldfd), int(newfd)) end end function C.dup3(oldfd, newfd, flags) return syscall(sys.dup3, int(oldfd), int(newfd), int(flags)) end if sys.chmod then function C.chmod(path, mode) return syscall(sys.chmod, void(path), uint(mode)) end end function C.fchmod(fd, mode) return syscall(sys.fchmod, int(fd), uint(mode)) end function C.umask(mode) return syscall(sys.umask, uint(mode)) end if sys.access then function C.access(path, mode) return syscall(sys.access, void(path), uint(mode)) end end function C.getppid() return syscall(sys.getppid) end function C.getuid() return syscall(sys.getuid) end function C.geteuid() return syscall(sys.geteuid) end function C.getgid() return syscall(sys.getgid) end function C.getegid() return syscall(sys.getegid) end function C.getresuid(ruid, euid, suid) return syscall(sys.getresuid, void(ruid), void(euid), void(suid)) end function C.getresgid(rgid, egid, sgid) return syscall(sys.getresgid, void(rgid), void(egid), void(sgid)) end function C.setuid(id) return syscall(sys.setuid, uint(id)) end function C.setgid(id) return syscall(sys.setgid, uint(id)) end function C.setresuid(ruid, euid, suid) return syscall(sys.setresuid, uint(ruid), uint(euid), uint(suid)) end function C.setresgid(rgid, egid, sgid) return syscall(sys.setresgid, uint(rgid), uint(egid), uint(sgid)) end function C.setreuid(uid, euid) return syscall(sys.setreuid, uint(uid), uint(euid)) end function C.setregid(gid, egid) return syscall(sys.setregid, uint(gid), uint(egid)) end function C.flock(fd, operation) return syscall(sys.flock, int(fd), int(operation)) end function C.getrusage(who, usage) return syscall(sys.getrusage, int(who), void(usage)) end if sys.rmdir then function C.rmdir(path) return syscall(sys.rmdir, void(path)) end end function C.chdir(path) return syscall(sys.chdir, void(path)) end function C.fchdir(fd) return syscall(sys.fchdir, int(fd)) end if sys.chown then function C.chown(path, owner, group) return syscall(sys.chown, void(path), uint(owner), uint(group)) end end function C.fchown(fd, owner, group) return syscall(sys.fchown, int(fd), uint(owner), uint(group)) end function C.lchown(path, owner, group) return syscall(sys.lchown, void(path), uint(owner), uint(group)) end if sys.open then function C.open(pathname, flags, mode) return syscall(sys.open, void(pathname), int(flags), uint(mode)) end end function C.openat(dirfd, pathname, flags, mode) return syscall(sys.openat, int(dirfd), void(pathname), int(flags), uint(mode)) end if sys.creat then function C.creat(pathname, mode) return syscall(sys.creat, void(pathname), uint(mode)) end end function C.close(fd) return syscall(sys.close, int(fd)) end function C.read(fd, buf, count) return syscall_long(sys.read, int(fd), void(buf), ulong(count)) end function C.write(fd, buf, count) return syscall_long(sys.write, int(fd), void(buf), ulong(count)) end function C.readv(fd, iov, iovcnt) return syscall_long(sys.readv, int(fd), void(iov), long(iovcnt)) end function C.writev(fd, iov, iovcnt) return syscall_long(sys.writev, int(fd), void(iov), long(iovcnt)) end if sys.readlink then function C.readlink(path, buf, bufsiz) return syscall_long(sys.readlink, void(path), void(buf), ulong(bufsiz)) end end if sys.rename then function C.rename(oldpath, newpath) return syscall(sys.rename, void(oldpath), void(newpath)) end end function C.renameat(olddirfd, oldpath, newdirfd, newpath) return syscall(sys.renameat, int(olddirfd), void(oldpath), int(newdirfd), void(newpath)) end if sys.renameat2 then function C.renameat2(olddirfd, oldpath, newdirfd, newpath, flags) return syscall(sys.renameat2, int(olddirfd), void(oldpath), int(newdirfd), void(newpath), int(flags)) end end if sys.unlink then function C.unlink(pathname) return syscall(sys.unlink, void(pathname)) end end function C.unlinkat(dirfd, pathname, flags) return syscall(sys.unlinkat, int(dirfd), void(pathname), int(flags)) end function C.prctl(option, arg2, arg3, arg4, arg5) return syscall(sys.prctl, int(option), ulong(arg2), ulong(arg3), ulong(arg4), ulong(arg5)) end if abi.arch ~= "mips" and abi.arch ~= "mipsel" and sys.pipe then -- mips uses old style dual register return calling convention that we cannot use function C.pipe(pipefd) return syscall(sys.pipe, void(pipefd)) end end function C.pipe2(pipefd, flags) return syscall(sys.pipe2, void(pipefd), int(flags)) end function C.pause() return syscall(sys.pause) end function C.remap_file_pages(addr, size, prot, pgoff, flags) return syscall(sys.remap_file_pages, void(addr), ulong(size), int(prot), long(pgoff), int(flags)) end if sys.fork then function C.fork() return syscall(sys.fork) end end function C.kill(pid, sig) return syscall(sys.kill, int(pid), int(sig)) end if sys.mkdir then function C.mkdir(pathname, mode) return syscall(sys.mkdir, void(pathname), uint(mode)) end end function C.fsync(fd) return syscall(sys.fsync, int(fd)) end function C.fdatasync(fd) return syscall(sys.fdatasync, int(fd)) end function C.sync() return syscall(sys.sync) end function C.syncfs(fd) return syscall(sys.syncfs, int(fd)) end if sys.link then function C.link(oldpath, newpath) return syscall(sys.link, void(oldpath), void(newpath)) end end if sys.symlink then function C.symlink(oldpath, newpath) return syscall(sys.symlink, void(oldpath), void(newpath)) end end function C.epoll_ctl(epfd, op, fd, event) return syscall(sys.epoll_ctl, int(epfd), int(op), int(fd), void(event)) end function C.uname(buf) return syscall(sys.uname, void(buf)) end function C.getsid(pid) return syscall(sys.getsid, int(pid)) end function C.getpgid(pid) return syscall(sys.getpgid, int(pid)) end function C.setpgid(pid, pgid) return syscall(sys.setpgid, int(pid), int(pgid)) end if sys.getpgrp then function C.getpgrp() return syscall(sys.getpgrp) end end function C.setsid() return syscall(sys.setsid) end function C.chroot(path) return syscall(sys.chroot, void(path)) end function C.mount(source, target, filesystemtype, mountflags, data) return syscall(sys.mount, void(source), void(target), void(filesystemtype), ulong(mountflags), void(data)) end function C.umount(target) return syscall(sys.umount, void(target)) end function C.umount2(target, flags) return syscall(sys.umount2, void(target), int(flags)) end function C.listxattr(path, list, size) return syscall_long(sys.listxattr, void(path), void(list), ulong(size)) end function C.llistxattr(path, list, size) return syscall_long(sys.llistxattr, void(path), void(list), ulong(size)) end function C.flistxattr(fd, list, size) return syscall_long(sys.flistxattr, int(fd), void(list), ulong(size)) end function C.setxattr(path, name, value, size, flags) return syscall(sys.setxattr, void(path), void(name), void(value), ulong(size), int(flags)) end function C.lsetxattr(path, name, value, size, flags) return syscall(sys.lsetxattr, void(path), void(name), void(value), ulong(size), int(flags)) end function C.fsetxattr(fd, name, value, size, flags) return syscall(sys.fsetxattr, int(fd), void(name), void(value), ulong(size), int(flags)) end function C.getxattr(path, name, value, size) return syscall_long(sys.getxattr, void(path), void(name), void(value), ulong(size)) end function C.lgetxattr(path, name, value, size) return syscall_long(sys.lgetxattr, void(path), void(name), void(value), ulong(size)) end function C.fgetxattr(fd, name, value, size) return syscall_long(sys.fgetxattr, int(fd), void(name), void(value), ulong(size)) end function C.removexattr(path, name) return syscall(sys.removexattr, void(path), void(name)) end function C.lremovexattr(path, name) return syscall(sys.lremovexattr, void(path), void(name)) end function C.fremovexattr(fd, name) return syscall(sys.fremovexattr, int(fd), void(name)) end function C.inotify_add_watch(fd, pathname, mask) return syscall(sys.inotify_add_watch, int(fd), void(pathname), uint(mask)) end function C.inotify_rm_watch(fd, wd) return syscall(sys.inotify_rm_watch, int(fd), int(wd)) end function C.unshare(flags) return syscall(sys.unshare, int(flags)) end function C.reboot(magic, magic2, cmd) return syscall(sys.reboot, int(magic), int(magic2), int(cmd)) end function C.sethostname(name, len) return syscall(sys.sethostname, void(name), ulong(len)) end function C.setdomainname(name, len) return syscall(sys.setdomainname, void(name), ulong(len)) end function C.getitimer(which, curr_value) return syscall(sys.getitimer, int(which), void(curr_value)) end function C.setitimer(which, new_value, old_value) return syscall(sys.setitimer, int(which), void(new_value), void(old_value)) end function C.sched_yield() return syscall(sys.sched_yield) end function C.acct(filename) return syscall(sys.acct, void(filename)) end function C.munmap(addr, length) return syscall(sys.munmap, void(addr), ulong(length)) end function C.faccessat(dirfd, path, mode, flags) return syscall(sys.faccessat, int(dirfd), void(path), uint(mode), int(flags)) end function C.fchmodat(dirfd, path, mode, flags) return syscall(sys.fchmodat, int(dirfd), void(path), uint(mode), int(flags)) end function C.mkdirat(dirfd, pathname, mode) return syscall(sys.mkdirat, int(dirfd), void(pathname), uint(mode)) end function C.fchownat(dirfd, pathname, owner, group, flags) return syscall(sys.fchownat, int(dirfd), void(pathname), uint(owner), uint(group), int(flags)) end function C.setpriority(which, who, prio) return syscall(sys.setpriority, int(which), int(who), int(prio)) end function C.sched_get_priority_min(policy) return syscall(sys.sched_get_priority_min, int(policy)) end function C.sched_get_priority_max(policy) return syscall(sys.sched_get_priority_max, int(policy)) end function C.sched_rr_get_interval(pid, tp) return syscall(sys.sched_rr_get_interval, int(pid), void(tp)) end if sys.poll then function C.poll(fds, nfds, timeout) return syscall(sys.poll, void(fds), int(nfds), int(timeout)) end end function C.msync(addr, length, flags) return syscall(sys.msync, void(addr), ulong(length), int(flags)) end function C.madvise(addr, length, advice) return syscall(sys.madvise, void(addr), ulong(length), int(advice)) end function C.mlock(addr, len) return syscall(sys.mlock, void(addr), ulong(len)) end function C.munlock(addr, len) return syscall(sys.munlock, void(addr), ulong(len)) end function C.mlockall(flags) return syscall(sys.mlockall, int(flags)) end function C.munlockall() return syscall(sys.munlockall) end function C.capget(hdrp, datap) return syscall(sys.capget, void(hdrp), void(datap)) end function C.capset(hdrp, datap) return syscall(sys.capset, void(hdrp), void(datap)) end function C.sysinfo(info) return syscall(sys.sysinfo, void(info)) end function C.execve(filename, argv, envp) return syscall(sys.execve, void(filename), void(argv), void(envp)) end function C.getgroups(size, list) return syscall(sys.getgroups, int(size), void(list)) end function C.setgroups(size, list) return syscall(sys.setgroups, int(size), void(list)) end function C.klogctl(tp, bufp, len) return syscall(sys.syslog, int(tp), void(bufp), int(len)) end function C.sigprocmask(how, set, oldset) return syscall(sys.rt_sigprocmask, int(how), void(set), void(oldset), sigmasksize(set or oldset)) end function C.sigpending(set) return syscall(sys.rt_sigpending, void(set), sigmasksize(set)) end function C.mremap(old_address, old_size, new_size, flags, new_address) return syscall_void(sys.mremap, void(old_address), ulong(old_size), ulong(new_size), int(flags), void(new_address)) end function C.nanosleep(req, rem) return syscall(sys.nanosleep, void(req), void(rem)) end function C.wait4(pid, status, options, rusage) return syscall(sys.wait4, int(pid), void(status), int(options), void(rusage)) end function C.waitid(idtype, id, infop, options, rusage) return syscall(sys.waitid, int(idtype), uint(id), void(infop), int(options), void(rusage)) end function C.settimeofday(tv, tz) return syscall(sys.settimeofday, void(tv), void(tz)) end function C.timer_create(clockid, sevp, timerid) return syscall(sys.timer_create, int(clockid), void(sevp), void(timerid)) end function C.timer_settime(timerid, flags, new_value, old_value) return syscall(sys.timer_settime, int(timerid), int(flags), void(new_value), void(old_value)) end function C.timer_gettime(timerid, curr_value) return syscall(sys.timer_gettime, int(timerid), void(curr_value)) end function C.timer_delete(timerid) return syscall(sys.timer_delete, int(timerid)) end function C.timer_getoverrun(timerid) return syscall(sys.timer_getoverrun, int(timerid)) end -- only on some architectures if sys.waitpid then function C.waitpid(pid, status, options) return syscall(sys.waitpid, int(pid), void(status), int(options)) end end -- fcntl needs a cast as last argument may be int or pointer local fcntl = sys.fcntl64 or sys.fcntl function C.fcntl(fd, cmd, arg) return syscall(fcntl, int(fd), int(cmd), ffi.cast(long, arg)) end function C.pselect(nfds, readfds, writefds, exceptfds, timeout, sigmask) local size = 0 if sigmask then size = sigset_size end local data = longs(void(sigmask), size) return syscall(sys.pselect6, int(nfds), void(readfds), void(writefds), void(exceptfds), void(timeout), void(data)) end -- need _newselect syscall on some platforms local sysselect = sys._newselect or sys.select if sysselect then function C.select(nfds, readfds, writefds, exceptfds, timeout) return syscall(sysselect, int(nfds), void(readfds), void(writefds), void(exceptfds), void(timeout)) end end -- missing on some platforms eg ARM if sys.alarm then function C.alarm(seconds) return syscall(sys.alarm, uint(seconds)) end end -- new system calls, may be missing TODO fix so is not if sys.getrandom then function C.getrandom(buf, count, flags) return syscall(sys.getrandom, void(buf), uint(count), uint(flags)) end end if sys.memfd_create then function C.memfd_create(name, flags) return syscall(sys.memfd_create, void(name), uint(flags)) end end -- kernel sigaction structures actually rather different in Linux from libc ones function C.sigaction(signum, act, oldact) return syscall(sys.rt_sigaction, int(signum), void(act), void(oldact), ulong(sigset_size)) -- size is size of sigset field end -- in VDSO for many archs, so use ffi for speed; TODO read VDSO to find functions there, needs elf reader if pcall(function(k) return ffi.C[k] end, "clock_gettime") then C.clock_gettime = ffi.C.clock_gettime else function C.clock_gettime(clk_id, ts) return syscall(sys.clock_gettime, int(clk_id), void(ts)) end end C.gettimeofday = ffi.C.gettimeofday --function C.gettimeofday(tv, tz) return syscall(sys.gettimeofday, void(tv), void(tz)) end -- glibc does not provide getcpu; it is however VDSO function C.getcpu(cpu, node, tcache) return syscall(sys.getcpu, void(node), void(node), void(tcache)) end -- time is VDSO but not really performance critical; does not exist for some architectures if sys.time then function C.time(t) return syscall(sys.time, void(t)) end end -- socketcalls if not sys.socketcall then function C.socket(domain, tp, protocol) return syscall(sys.socket, int(domain), int(tp), int(protocol)) end function C.bind(sockfd, addr, addrlen) return syscall(sys.bind, int(sockfd), void(addr), uint(addrlen)) end function C.connect(sockfd, addr, addrlen) return syscall(sys.connect, int(sockfd), void(addr), uint(addrlen)) end function C.listen(sockfd, backlog) return syscall(sys.listen, int(sockfd), int(backlog)) end function C.accept(sockfd, addr, addrlen) return syscall(sys.accept, int(sockfd), void(addr), void(addrlen)) end function C.getsockname(sockfd, addr, addrlen) return syscall(sys.getsockname, int(sockfd), void(addr), void(addrlen)) end function C.getpeername(sockfd, addr, addrlen) return syscall(sys.getpeername, int(sockfd), void(addr), void(addrlen)) end function C.socketpair(domain, tp, protocol, sv) return syscall(sys.socketpair, int(domain), int(tp), int(protocol), void(sv)) end function C.send(sockfd, buf, len, flags) return syscall_long(sys.send, int(sockfd), void(buf), ulong(len), int(flags)) end function C.recv(sockfd, buf, len, flags) return syscall_long(sys.recv, int(sockfd), void(buf), ulong(len), int(flags)) end function C.sendto(sockfd, buf, len, flags, dest_addr, addrlen) return syscall_long(sys.sendto, int(sockfd), void(buf), ulong(len), int(flags), void(dest_addr), uint(addrlen)) end function C.recvfrom(sockfd, buf, len, flags, src_addr, addrlen) return syscall_long(sys.recvfrom, int(sockfd), void(buf), ulong(len), int(flags), void(src_addr), void(addrlen)) end function C.shutdown(sockfd, how) return syscall(sys.shutdown, int(sockfd), int(how)) end function C.setsockopt(sockfd, level, optname, optval, optlen) return syscall(sys.setsockopt, int(sockfd), int(level), int(optname), void(optval), uint(optlen)) end function C.getsockopt(sockfd, level, optname, optval, optlen) return syscall(sys.getsockopt, int(sockfd), int(level), int(optname), void(optval), void(optlen)) end function C.sendmsg(sockfd, msg, flags) return syscall_long(sys.sendmsg, int(sockfd), void(msg), int(flags)) end function C.recvmsg(sockfd, msg, flags) return syscall_long(sys.recvmsg, int(sockfd), void(msg), int(flags)) end function C.accept4(sockfd, addr, addrlen, flags) return syscall(sys.accept4, int(sockfd), void(addr), void(addrlen), int(flags)) end function C.recvmmsg(sockfd, msgvec, vlen, flags, timeout) return syscall(sys.recvmmsg, int(sockfd), void(msgvec), uint(vlen), int(flags), void(timeout)) end function C.sendmmsg(sockfd, msgvec, vlen, flags) return syscall(sys.sendmmsg, int(sockfd), void(msgvec), uint(vlen), int(flags)) end else function C.socket(domain, tp, protocol) local args = longs(domain, tp, protocol) return syscall(sys.socketcall, int(socketcalls.SOCKET), void(args)) end function C.bind(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), addrlen) return syscall(sys.socketcall, int(socketcalls.BIND), void(args)) end function C.connect(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), addrlen) return syscall(sys.socketcall, int(socketcalls.CONNECT), void(args)) end function C.listen(sockfd, backlog) local args = longs(sockfd, backlog) return syscall(sys.socketcall, int(socketcalls.LISTEN), void(args)) end function C.accept(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), void(addrlen)) return syscall(sys.socketcall, int(socketcalls.ACCEPT), void(args)) end function C.getsockname(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), void(addrlen)) return syscall(sys.socketcall, int(socketcalls.GETSOCKNAME), void(args)) end function C.getpeername(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), void(addrlen)) return syscall(sys.socketcall, int(socketcalls.GETPEERNAME), void(args)) end function C.socketpair(domain, tp, protocol, sv) local args = longs(domain, tp, protocol, void(sv)) return syscall(sys.socketcall, int(socketcalls.SOCKETPAIR), void(args)) end function C.send(sockfd, buf, len, flags) local args = longs(sockfd, void(buf), len, flags) return syscall_long(sys.socketcall, int(socketcalls.SEND), void(args)) end function C.recv(sockfd, buf, len, flags) local args = longs(sockfd, void(buf), len, flags) return syscall_long(sys.socketcall, int(socketcalls.RECV), void(args)) end function C.sendto(sockfd, buf, len, flags, dest_addr, addrlen) local args = longs(sockfd, void(buf), len, flags, void(dest_addr), addrlen) return syscall_long(sys.socketcall, int(socketcalls.SENDTO), void(args)) end function C.recvfrom(sockfd, buf, len, flags, src_addr, addrlen) local args = longs(sockfd, void(buf), len, flags, void(src_addr), void(addrlen)) return syscall_long(sys.socketcall, int(socketcalls.RECVFROM), void(args)) end function C.shutdown(sockfd, how) local args = longs(sockfd, how) return syscall(sys.socketcall, int(socketcalls.SHUTDOWN), void(args)) end function C.setsockopt(sockfd, level, optname, optval, optlen) local args = longs(sockfd, level, optname, void(optval), optlen) return syscall(sys.socketcall, int(socketcalls.SETSOCKOPT), void(args)) end function C.getsockopt(sockfd, level, optname, optval, optlen) local args = longs(sockfd, level, optname, void(optval), void(optlen)) return syscall(sys.socketcall, int(socketcalls.GETSOCKOPT), void(args)) end function C.sendmsg(sockfd, msg, flags) local args = longs(sockfd, void(msg), flags) return syscall_long(sys.socketcall, int(socketcalls.SENDMSG), void(args)) end function C.recvmsg(sockfd, msg, flags) local args = longs(sockfd, void(msg), flags) return syscall_long(sys.socketcall, int(socketcalls.RECVMSG), void(args)) end function C.accept4(sockfd, addr, addrlen, flags) local args = longs(sockfd, void(addr), void(addrlen), flags) return syscall(sys.socketcall, int(socketcalls.ACCEPT4), void(args)) end function C.recvmmsg(sockfd, msgvec, vlen, flags, timeout) local args = longs(sockfd, void(msgvec), vlen, flags, void(timeout)) return syscall(sys.socketcall, int(socketcalls.RECVMMSG), void(args)) end function C.sendmmsg(sockfd, msgvec, vlen, flags) local args = longs(sockfd, void(msgvec), vlen, flags) return syscall(sys.socketcall, int(socketcalls.SENDMMSG), void(args)) end end return C
apache-2.0
xToken/CompMod
lua/CompMod/Weapons/Marine/FlameCloud/shared.lua
1
8800
-- Natural Selection 2 Competitive Mod -- Source located at - https://github.com/xToken/CompMod -- lua\CompMod\Weapons\Marine\FlameCloud\shared.lua -- - Dragon Script.Load("lua/TeamMixin.lua") Script.Load("lua/OwnerMixin.lua") Script.Load("lua/DamageMixin.lua") Script.Load("lua/EffectsMixin.lua") Script.Load("lua/EntityChangeMixin.lua") class 'FlameCloud' (Entity) FlameCloud.kMapName = "flamecloud" FlameCloud.kFireEffect = PrecacheAsset("cinematics/marine/flamethrower/burning_surface.cinematic") local kDamageInterval = 0.25 local gHurtByFlames = { } FlameCloud.kMaxRange = 12 FlameCloud.kTravelSpeed = 8 --m/s FlameCloud.kConeWidth = 0.25 FlameCloud.kGravity = -1 FlameCloud.kMaxTrackedVectors = 100 FlameCloud.kMaxLifetime = 20 local networkVars = { destination1 = "vector" } for i = 1, FlameCloud.kMaxTrackedVectors do --networkVars[destination..ToString(i)] = "vector" end AddMixinNetworkVars(TeamMixin, networkVars) function FlameCloud:OnCreate() Entity.OnCreate(self) InitMixin(self, TeamMixin) InitMixin(self, DamageMixin) InitMixin(self, EffectsMixin) InitMixin(self, EntityChangeMixin) InitMixin(self, LOSMixin) if Server then InitMixin(self, OwnerMixin) self.nextDamageTime = 0 end self:SetUpdates(true) self.createTime = Shared.GetTime() self.endOfDamageTime = self.createTime + FlameCloud.kMaxLifetime self.destroyTime = self.endOfDamageTime + 2 end function FlameCloud:SetInitialDestination(dest) self.destination1 = dest self.source1 = self:GetOrigin() end function FlameCloud:AddIntermediateDestination(origin, dest) for i = 1, FlameCloud.kMaxTrackedVectors do if not self["destination"..ToString(i)] then self["destination"..ToString(i)] = dest self["source"..ToString(i)] = origin break end end end function FlameCloud:FinishedFiring() self.finishedFiring = true end function FlameCloud:OnDestroy() Entity.OnDestroy(self) if Client then if self.flameEffect then Client.DestroyCinematic(self.flameEffect) self.flameEffect = nil end end end local function GetEntityRecentlyHurt(entityId, time) for index, pair in ipairs(gHurtByFlames) do if pair[1] == entityId and pair[2] > time then return true end end return false end local function SetEntityRecentlyHurt(entityId) for index, pair in ipairs(gHurtByFlames) do if pair[1] == entityId then table.remove(gHurtByFlames, index) end end table.insert(gHurtByFlames, {entityId, Shared.GetTime()}) end function FlameCloud:GetDamageType() return kDamageType.Normal end function FlameCloud:GetDeathIconIndex() return kDeathMessageIcon.Flamethrower end function FlameCloud:GetDamageRadius() return FlameCloud.kFlameRadius end function FlameCloud:GetShowHitIndicator() return true end function FlameCloud:GetMeleeOffset() return 0.0 end function FlameCloud:FlameDamage(locations, time, enemies) local damageRadius = self:GetDamageRadius() for i =1, #enemies do if not enemies[i]:isa("Commander") and not GetEntityRecentlyHurt(enemies[i]:GetId(), (time - kDamageInterval)) then self:DoDamage(kFlamethrowerDamagePerSecond * kDamageInterval, enemies[i], locations[i], nil, "flame" ) SetEntityRecentlyHurt(enemies[i]:GetId()) end end end function FlameCloud:OnUpdate(deltaTime) local time = Shared.GetTime() if Client then if self.destination and not self.flameSpawnEffect then self.flameSpawnEffect = Client.CreateCinematic(RenderScene.Zone_Default) self.flameSpawnEffect:SetCinematic(FlameCloud.kFireEffect) self.flameSpawnEffect:SetRepeatStyle(Cinematic.Repeat_Endless) local coords = Coords.GetIdentity() coords.origin = self:GetOrigin() coords.zAxis = GetNormalizedVector(self:GetOrigin()-self.destination) coords.xAxis = GetNormalizedVector(coords.yAxis:CrossProduct(coords.zAxis)) coords.yAxis = coords.zAxis:CrossProduct(coords.xAxis) self.flameSpawnEffect:SetCoords(coords) end end if Server then local damageTime = false local extents = Vector(self.kConeWidth, self.kConeWidth, self.kConeWidth) local filterEnts = {self, self:GetOwner()} local ents = { } local damageLocations = { } local originSet = false if time > self.nextDamageTime and time < self.endOfDamageTime then damageTime = true self.nextDamageTime = time + kDamageInterval end if not self.doneTraveling then local allFinished = true for i = 1, FlameCloud.kMaxTrackedVectors do if not self["doneTraveling"..ToString(i)] then if self["destination"..ToString(i)] then local dest = self["destination"..ToString(i)] local origin = self["source"..ToString(i)] local travelDistance = dest - origin local travelVector = GetNormalizedVector(travelDistance) local remainingRange = deltaTime * FlameCloud.kTravelSpeed local startPoint = origin if travelDistance:GetLengthSquared() > 0.1 then local trace = TraceMeleeBox(self, startPoint, travelVector, extents, remainingRange, PhysicsMask.Flame, EntityFilterList(filterEnts)) local endPoint = trace.endPoint if trace.fraction ~= 1 then local traceEnt = trace.entity if traceEnt and HasMixin(traceEnt, "Live") and traceEnt:GetCanTakeDamage() then table.insert(ents, traceEnt) table.insert(damageLocations, endPoint) end end origin = endPoint + Vector(0, FlameCloud.kGravity, 0) * deltaTime self["destination"..ToString(i)] = self["destination"..ToString(i)] + Vector(0, FlameCloud.kGravity, 0) * deltaTime self["source"..ToString(i)] = origin if not originSet then self:SetOrigin(self["source"..ToString(i)]) originSet = true end allFinished = false else self["doneTraveling"..ToString(i)] = true end else break end else allFinished = allFinished and true end end if allFinished and self.finishedFiring then self.doneTraveling = true end end if damageTime then self:FlameDamage(damageLocations, time, ents) end if time > self.destroyTime then DestroyEntity(self) end elseif Client then local coords = Coords.GetIdentity() coords.origin = self:GetOrigin() if self.flameEffect then self.flameEffect:SetCoords( coords ) else self.flameEffect = Client.CreateCinematic(RenderScene.Zone_Default) self.flameEffect:SetCinematic( FlameCloud.kFireEffect ) self.flameEffect:SetRepeatStyle(Cinematic.Repeat_Endless) self.flameEffect:SetCoords( coords ) end end end if Client then function FlameCloud:OnUpdateRender() if self.flameSpawnEffect and self.destination then local coords = Coords.GetIdentity() coords.origin = self:GetOrigin() coords.zAxis = GetNormalizedVector(self:GetOrigin()-self.destination) coords.xAxis = GetNormalizedVector(coords.yAxis:CrossProduct(coords.zAxis)) coords.yAxis = coords.zAxis:CrossProduct(coords.xAxis) self.flameSpawnEffect:SetCoords(coords) end end end function FlameCloud:GetRemainingLifeTime() return math.min(0, self.endOfDamageTime - Shared.GetTime()) end Shared.LinkClassToMap("FlameCloud", FlameCloud.kMapName, networkVars)
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Cloister_of_Flames/Zone.lua
32
1663
----------------------------------- -- -- Zone: Cloister_of_Flames (207) -- ----------------------------------- package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Cloister_of_Flames/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-698.729,-1.045,-646.659,184); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
lordporya1/lord
plugins/banhammer.lua
23
11188
-- data saved to moderation.json do -- make sure to set with value that not higher than stats.lua local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id if user_id == tostring(our_id) then send_msg(chat, "I won't kick myself!", ok_cb, true) else chat_del_user(chat, user, ok_cb, true) end end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function unban_user(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function action_by_reply(extra, success, result) local msg = result local chat_id = msg.to.id local user_id = msg.from.id local chat = 'chat#id'..msg.to.id local user = 'user#id'..msg.from.id if result.to.type == 'chat' and not is_sudo(msg) then if extra.match == 'kick' then chat_del_user(chat, user, ok_cb, false) elseif extra.match == 'ban' then ban_user(user_id, chat_id) send_msg(chat, 'User '..user_id..' banned', ok_cb, true) elseif extra.match == 'unban' then unban_user(user_id, chat_id) send_msg(chat, 'User '..user_id..' unbanned', ok_cb, true) end else return 'Use This in Your Groups' end end local function resolve_username(extra, success, result) if success == 1 then local msg = extra.msg local chat_id = msg.to.id local user_id = result.id local chat = 'chat#id'..msg.to.id local user = 'user#id'..result.id if msg.to.type == 'chat' then -- check if sudo users local is_sudoers = false for v,username in pairs(_config.sudo_users) do if username == user_id then is_sudoers = true end end -- if not sudo users if not is_sudoers then if extra.match == 'kick' then chat_del_user(chat, user, ok_cb, false) elseif extra.match == 'ban' then ban_user(user_id, chat_id) send_msg(chat, 'User @'..result.username..' banned', ok_cb, true) elseif extra.match == 'unban' then unban_user(user_id, chat_id) send_msg(chat, 'User @'..result.username..' unbanned', ok_cb, true) end end else return 'Use This in Your Groups.' end end end local function pre_process(msg) local user_id = msg.from.id local chat_id = msg.to.id local chat = 'chat#id'..chat_id local user = 'user#id'..user_id -- ANTI FLOOD local post_count = 'floodc:'..user_id..':'..chat_id redis:incr(post_count) if msg.from.type == 'user' then local post_count = 'user:'..user_id..':floodc' local msgs = tonumber(redis:get(post_count) or 0) local text = 'User '..user_id..' is flooding' if msgs > NUM_MSG_MAX and not is_sudo(msg) then local data = load_data(_config.moderation.data) local anti_flood_stat = data[tostring(chat_id)]['settings']['anti_flood'] if anti_flood_stat == 'kick' then send_large_msg(get_receiver(msg), text) kick_user(user_id, chat_id) msg = nil elseif anti_flood_stat == 'ban' then send_large_msg(get_receiver(msg), text) ban_user(user_id, chat_id) send_msg(chat, 'User '..user_id..' banned', ok_cb, true) msg = nil end end redis:setex(post_count, TIME_CHECK, msgs+1) end -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local banned = is_banned(user_id, chat_id) if banned then print('User is banned!') kick_user(user_id, chat_id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local banned = is_banned(user_id, chat_id) if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(user_id) if not allowed then print('User '..user..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(chat_id) if not allowed then print ('Chat '..chat_id..' not whitelisted') else print ('Chat '..chat_id..' whitelisted :)') end end else print('User '..user_id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function run(msg, matches) -- Silent ignore if not is_sudo(msg) then return nil end local user_id = matches[2] local chat_id = msg.to.id local chat = 'chat#id'..msg.to.id local user = 'user#id'..msg.to.id if msg.to.type == 'chat' then if matches[1] == 'ban' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]}) elseif string.match(user_id, '^%d+$') then ban_user(user_id, chat_id) return 'User '..user_id..' banned' elseif string.match(user_id, '^@.+$') then local user = string.gsub(user_id, '@', '') msgr = res_user(user, resolve_username, {msg=msg, match=matches[1]}) end elseif matches[1] == 'unban' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]}) elseif string.match(user_id, '^%d+$') then unban_user(user_id, chat_id) return 'User '..user_id..' unbanned' elseif string.match(user_id, '^@.+$') then local user = string.gsub(user_id, '@', '') msgr = res_user(user, resolve_username, {msg=msg, match=matches[1]}) end elseif matches[1] == 'kick' then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg, match=matches[1]}) elseif string.match(user_id, '^%d+$') then kick_user(user_id, msg.to.id) elseif string.match(user_id, '^@.+$') then local user = string.gsub(user_id, '@', '') msgr = res_user(user, resolve_username, {msg=msg, match=matches[1]}) end end else return 'This is not a chat group' end if matches[1] == 'antiflood' then local data = load_data(_config.moderation.data) local anti_flood_stat = data[tostring(chat_id)]['settings']['anti_flood'] if matches[2] == 'kick' then if anti_flood_stat ~= 'kick' then data[tostring(chat_id)]['settings']['anti_flood'] = 'kick' save_data(_config.moderation.data, data) end return 'Anti flood protection already enabled.\nFlooder will be kicked.' end if matches[2] == 'ban' then if anti_flood_stat ~= 'ban' then data[tostring(chat_id)]['settings']['anti_flood'] = 'ban' save_data(_config.moderation.data, data) end return 'Anti flood protection already enabled.\nFlooder will be banned.' end if matches[2] == 'disable' then if anti_flood_stat == 'no' then return 'Anti flood protection is not enabled.' else data[tostring(chat_id)]['settings']['anti_flood'] = 'no' save_data(_config.moderation.data, data) return 'Anti flood protection has been disabled.' end end end if matches[1] == 'whitelist' then if matches[2] == 'enable' then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This is not a chat group' end local hash = 'whitelist:chat#id'..chat_id redis:set(hash, true) return 'Chat '..chat_id..' whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This is not a chat group' end local hash = 'whitelist:chat#id'..chat_id redis:del(hash) return 'Chat '..chat_id..' removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { "!antiflood kick : Enable flood protection. Flooder will be kicked.", "!antiflood ban : Enable flood protection. Flooder will be banned.", "!antiflood disable : Disable flood protection", "!ban : If type in reply, will ban user from chat group.", "!ban <user_id>/<@username>: Kick user from chat and kicks it if joins chat again", "!unban : If type in reply, will unban user from chat group.", "!unban <user_id>/<@username>: Unban user", "!kick : If type in reply, will kick user from chat group.", "!kick <user_id>/<@username>: Kick user from chat group", "!whitelist chat: Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete chat: Remove chat from whitelist", "!whitelist delete user <user_id>: Remove user from whitelist", "!whitelist <enable>/<disable>: Enable or disable whitelist mode", "!whitelist user <user_id>: Allow user to use the bot when whitelist mode is enabled" }, patterns = { "^!(antiflood) (.*)$", "^!(ban) (.*)$", "^!(ban)$", "^!(unban) (.*)$", "^!(unban)$", "^!(kick) (.+)$", "^!(kick)$", "^!!tgservice (.+)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (chat)$", "^!(whitelist) (delete) (user) (%d+)$", "^!(whitelist) (disable)$", "^!(whitelist) (enable)$", "^!(whitelist) (user) (%d+)$" }, run = run, pre_process = pre_process, privileged = true } end
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/globals/spells/valor_minuet_ii.lua
4
1590
----------------------------------------- -- Spell: Valor Minuet II -- Grants Attack bonus to all allies. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 10; if (sLvl+iLvl > 85) then power = power + math.floor((sLvl+iLvl-85) / 6); end if(power >= 32) then power = 32; end local iBoost = caster:getMod(MOD_MINUET_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end power = power + caster:getMerit(MERIT_MINUET_EFFECT); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MINUET,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(75); end return EFFECT_MINUET; end;
gpl-3.0
tobiebooth/nodemcu-firmware
lua_modules/ds3231/ds3231-web.lua
84
1338
require('ds3231') port = 80 -- ESP-01 GPIO Mapping gpio0, gpio2 = 3, 4 days = { [1] = "Sunday", [2] = "Monday", [3] = "Tuesday", [4] = "Wednesday", [5] = "Thursday", [6] = "Friday", [7] = "Saturday" } months = { [1] = "January", [2] = "Febuary", [3] = "March", [4] = "April", [5] = "May", [6] = "June", [7] = "July", [8] = "August", [9] = "September", [10] = "October", [11] = "November", [12] = "December" } ds3231.init(gpio0, gpio2) srv=net.createServer(net.TCP) srv:listen(port, function(conn) second, minute, hour, day, date, month, year = ds3231.getTime() prettyTime = string.format("%s, %s %s %s %s:%s:%s", days[day], date, months[month], year, hour, minute, second) conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" .. "<!DOCTYPE HTML>" .. "<html><body>" .. "<b>ESP8266</b></br>" .. "Time and Date: " .. prettyTime .. "<br>" .. "Node ChipID : " .. node.chipid() .. "<br>" .. "Node MAC : " .. wifi.sta.getmac() .. "<br>" .. "Node Heap : " .. node.heap() .. "<br>" .. "Timer Ticks : " .. tmr.now() .. "<br>" .. "</html></body>") conn:on("sent",function(conn) conn:close() end) end )
mit
elt11bot/seed-sup
plugins/MemberManager.lua
44
9652
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No @'..member..' in group' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then send_large_msg(receiver, 'User @'..member..' ('..member_id..') BANNED!') return ban_user(member_id, chat_id) elseif get_cmd == 'globalban' then send_large_msg(receiver, 'User @'..member..' ('..member_id..') GLOBALLY BANNED!!') return superban_user(member_id, chat_id) elseif get_cmd == 'wlist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'wlist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == '+' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' BANNED!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == '-' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' UNbanned' end else return 'Only work in group' end end if matches[1] == 'globalban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == '+' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' GLOBALLY BANNED!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == '-' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' GLOBALLY UNbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'Only work in group' end end if matches[1] == 'wlist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Group Members Manager System", usage = { user = "/kickme : leave group", moderator = { "/kick (@user) : kick user", "/kick (id) : kick user", "/ban + (@user) : kick user for ever", "/ban + (id) : kick user for ever", "/ban - (id) : unban user" }, admin = { "/globalban + (@user) : ban user from all groups", "/globalban + (id) : ban user from all groups", "/globalban - (id) : globally unban user" }, }, patterns = { "^[!/](wlist) (enable)$", "^[!/](wlist) (disable)$", "^[!/](wlist) (user) (.*)$", "^[!/](wlist) (chat)$", "^[!/](wlist) (delete) (user) (.*)$", "^[!/](wlist) (delete) (chat)$", "^[!/](ban) (+) (.*)$", "^[!/](ban) (-) (.*)$", "^[!/](globalban) (+) (.*)$", "^[!/](globalban) (-) (.*)$", "^[!/](kick) (.*)$", "^[!/](kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Cape_Teriggan/npcs/Voranbo-Natanbo_WW.lua
6
3025
----------------------------------- -- Area: Cape Teriggan -- NPC: Voranbo-Natanbo, W.W. -- Type: Outpost Conquest Guards -- @pos -185 7 -63 113 ----------------------------------- package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Cape_Teriggan/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = VOLLBOW; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
TRIEXTEAM/TaylortTG
plugins/info.lua
2
9024
do local ali_ghoghnoos = 100577715 --put your id here(BOT OWNER ID) local function setrank(msg, name, value) -- setrank function local hash = nil if msg.to.type == 'chat' then hash = 'rank:'..msg.to.id..':variables' end if hash then redis:hset(hash, name, value) return send_msg('chat#id'..msg.to.id, 'مقام کاربر ('..name..') به '..value..' تغییر داده شد ', ok_cb, true) end end local function res_user_callback(extra, success, result) -- /info <username> function if success == 1 then if result.username then Username = '@'..result.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.id..'\n\n' local hash = 'rank:'..extra.chat2..':variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(ali_ghoghnoos) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.id, extra.chat2) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.id, extra.chat2) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'' send_msg(extra.receiver, text, ok_cb, true) else send_msg(extra.receiver, extra.user..' نام کاربری مورد نظر یافت نشد.', ok_cb, false) end end local function action_by_id(extra, success, result) -- /info <ID> function if success == 1 then if result.username then Username = '@'..result.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.id..'\n\n' local hash = 'rank:'..extra.chat2..':variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(ali_ghoghnoos) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.id, extra.chat2) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.id, extra.chat2) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'' send_msg(extra.receiver, text, ok_cb, true) else send_msg(extra.receiver, 'ایدی شخص مورد نظر در سیستم ثبت نشده است.\nاز دستور زیر استفاده کنید\n/info @username', ok_cb, false) end end local function action_by_reply(extra, success, result)-- (reply) /info function if result.from.username then Username = '@'..result.from.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.from.id..'\n\n' local hash = 'rank:'..result.to.id..':variables' local value = redis:hget(hash, result.from.id) if not value then if result.from.id == tonumber(ali_ghoghnoos) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.from.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.from.id, result.to.id) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.from.id, result.to.id) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local user_info = {} local uhash = 'user:'..result.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.from.id..':'..result.to.id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'' send_msg(extra.receiver, text, ok_cb, true) end local function action_by_reply2(extra, success, result) local value = extra.value setrank(result, result.from.id, value) end local function run(msg, matches) if matches[1]:lower() == 'setrank' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) if not is_owner(msg) then return "تنها برای صاحبان گروه مجاز است" end local receiver = get_receiver(msg) local Reply = msg.reply_id if msg.reply_id then local value = string.sub(matches[2], 1, 1000) msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value}) else local name = string.sub(matches[2], 1, 50) local value = string.sub(matches[3], 1, 1000) local text = setrank(msg, name, value) return text end end if matches[1]:lower() == 'info' and not matches[2] then local receiver = get_receiver(msg) local Reply = msg.reply_id if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply}) else if msg.from.username then Username = '@'..msg.from.username else Username = 'ندارد' end local text = 'نام : '..(msg.from.first_name or 'ندارد')..'\n' local text = text..'فامیل : '..(msg.from.last_name or 'ندارد')..'\n' local text = text..'یوزر : '..Username..'\n' local text = text..'ایدی کاربری : '..msg.from.id..'\n\n' local hash = 'rank:'..msg.to.id..':variables' if hash then local value = redis:hget(hash, msg.from.id) if not value then if msg.from.id == tonumber(ali_ghoghnoos) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_sudo(msg) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner(msg) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod(msg) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n' end end local uhash = 'user:'..msg.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' if msg.to.type == 'chat' then text = text..'نام گروه : '..msg.to.title..'\n' text = text..'ایدی گروه : '..msg.to.id end text = text..'' return send_msg(receiver, text, ok_cb, true) end end if matches[1]:lower() == 'info' and matches[2] then local user = matches[2] local chat2 = msg.to.id local receiver = get_receiver(msg) if string.match(user, '^%d+$') then user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2}) elseif string.match(user, '^@.+$') then username = string.gsub(user, '@', '') msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2}) end end end return { description = 'Know your information or the info of a chat members.', usage = { '!info: Return your info and the chat info if you are in one.', '(Reply)!info: Return info of replied user if used by reply.', '!info <id>: Return the info\'s of the <id>.', '!info @<user_name>: Return the member @<user_name> information from the current chat.', '!setrank <userid> <rank>: change members rank.', '(Reply)!setrank <rank>: change members rank.', }, patterns = { "^[/!]([Ii][Nn][Ff][Oo])$", "^[/!]([Ii][Nn][Ff][Oo]) (.*)$", "^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$", "^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$", }, run = run } end -- tnx to Arian ( @dragon_born ) -- @telemanager_ch
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Yuhtunga_Jungle/npcs/Mupia_RK.lua
8
2940
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Mupia, R.K. -- Border Conquest Guards -- @pos -241.334 -1 478.602 123 ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yuhtunga_Jungle/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ELSHIMOLOWLANDS; local csid = 0x7ffa; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/plate_of_tuna_sushi.lua
35
1526
----------------------------------------- -- ID: 5150 -- Item: plate_of_tuna_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Dexterity 3 -- Charisma 5 -- Accuracy % 15 -- Ranged ACC % 15 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5150); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_CHR, 5); target:addMod(MOD_ACCP, 15); target:addMod(MOD_RACCP, 15); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_CHR, 5); target:delMod(MOD_ACCP, 15); target:delMod(MOD_RACCP, 15); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/weaponskills/herculean_slash.lua
6
1565
----------------------------------- -- Herculean Slash -- Great Sword weapon skill -- Skill Level: 290 -- Paralyzes target. Duration of effect varies with TP. -- Aligned with the Snow Gorget, Thunder Gorget & Breeze Gorget. -- Aligned with the Snow Belt, Thunder Belt & Breeze Belt. -- Element: Ice -- Modifiers: VIT:60% -- As this is a magic-based weaponskill it is also modified by Magic Attack Bonus. -- 100%TP 200%TP 300%TP -- 3.50 3.50 3.50 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 3.5; params.ftp200 = 3.5; params.ftp300 = 3.5; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.6; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 60) if(target:hasStatusEffect(EFFECT_PARALYSIS) == false) then target:addStatusEffect(EFFECT_PARALYSIS, 30, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Mhaura/npcs/Pikini-Mikini.lua
36
1448
----------------------------------- -- Area: Mhaura -- NPC: Pikini-Mikini -- Standard Merchant NPC -- @pos -48 -4 30 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,PIKINIMIKINI_SHOP_DIALOG); stock = {0x1036,2335, --Eye Drops 0x1034,284, --Antidote 0x1037,720, --Echo Drops 0x1010,819, --Potion 0x119d,10, --Distilled Water 0x395,1821, --Parchment 0x43f3,9, --Lugworm 0x3fd,450, --Hatchet 0x1118,108, --Meat Jerky 0x14b3,133, --Salsa 0x0b33,9000} --Mhaura Waystone showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
groupforspeed/TeleSniper
plugins/chat_bot.lua
2
2038
local function run(msg) if msg.text == "Mohammad" then return "کی اسم سازندمو صدا زد؟" end if msg.text == "Umbrella" then return "کیر tele sniper هم نیس" end if msg.text == "umbrella" then return "کیر tele sniper هم نیس" end if msg.text == "Telesniper" then return "hum?" end if msg.text == "اسپم" then return "کس ننت میذارم بخای اسپم کنی" end if msg.text == "زتا" then return "کس ننش بگو مرسی" end if msg.text == "ایکس ایگرگ" then return "ایکس ایگرگو همرا ننت گاییدم ابمم ریختم روش" end if msg.text == "spam" then return "تو اگه تخم داشتی اسپم کنی الان اینجا بودی" end if msg.text == "ایکس" then return "ایکس ایگرگ گاییدم ابمم کس ننته" end if msg.text == "ایگرگ" then return "ایکس ایگرگ گاییدم ابمم کس ننته" end if msg.text == "x" then return "ایکس ایگرگ گاییدم ابمم کس ننته" end if msg.text == "start" then return "کس بگی میری بیرون" end if msg.text == "y" then return "ایکس ایگرگ گاییدم ابمم کس ننته" end if msg.text == "Bot" then return "چی کس میگی؟" end if msg.text == "?" then return "Hum??" end if msg.text == "بای" then return "برو به سلامت " end if msg.text == "XY" then return "کس ننت میگام سیکتیر اوبی" end if msg.text == "Xy" then return "Bye Bye" end end return { description = "Chat With Robot Server", usage = "chat with robot", patterns = { "^Mohammad$", "^[Bb]ot$", "^[Uu]mbrella$", "^بای$", "^x$", "^y$", "^ایکس$", "^ایگرگ$", "^اسپم$", "^زتا$", "^spam$", "^start$", "^بای$", "^Xy$", "^XY$", "^?$", "^Telesniper$" }, run = run, --privileged = true, pre_process = pre_process } --Copyright; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
vietlq/luasocket
etc/dict.lua
59
4652
----------------------------------------------------------------------------- -- Little program to download DICT word definitions -- LuaSocket sample files -- Author: Diego Nehab -- RCS ID: $Id: dict.lua,v 1.22 2005/11/22 08:33:29 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Load required modules ----------------------------------------------------------------------------- local base = _G local string = require("string") local table = require("table") local socket = require("socket") local url = require("socket.url") local tp = require("socket.tp") module("socket.dict") ----------------------------------------------------------------------------- -- Globals ----------------------------------------------------------------------------- HOST = "dict.org" PORT = 2628 TIMEOUT = 10 ----------------------------------------------------------------------------- -- Low-level dict API ----------------------------------------------------------------------------- local metat = { __index = {} } function open(host, port) local tp = socket.try(tp.connect(host or HOST, port or PORT, TIMEOUT)) return base.setmetatable({tp = tp}, metat) end function metat.__index:greet() return socket.try(self.tp:check(220)) end function metat.__index:check(ok) local code, status = socket.try(self.tp:check(ok)) return code, base.tonumber(socket.skip(2, string.find(status, "^%d%d%d (%d*)"))) end function metat.__index:getdef() local line = socket.try(self.tp:receive()) local def = {} while line ~= "." do table.insert(def, line) line = socket.try(self.tp:receive()) end return table.concat(def, "\n") end function metat.__index:define(database, word) database = database or "!" socket.try(self.tp:command("DEFINE", database .. " " .. word)) local code, count = self:check(150) local defs = {} for i = 1, count do self:check(151) table.insert(defs, self:getdef()) end self:check(250) return defs end function metat.__index:match(database, strat, word) database = database or "!" strat = strat or "." socket.try(self.tp:command("MATCH", database .." ".. strat .." ".. word)) self:check(152) local mat = {} local line = socket.try(self.tp:receive()) while line ~= '.' do database, word = socket.skip(2, string.find(line, "(%S+) (.*)")) if not mat[database] then mat[database] = {} end table.insert(mat[database], word) line = socket.try(self.tp:receive()) end self:check(250) return mat end function metat.__index:quit() self.tp:command("QUIT") return self:check(221) end function metat.__index:close() return self.tp:close() end ----------------------------------------------------------------------------- -- High-level dict API ----------------------------------------------------------------------------- local default = { scheme = "dict", host = "dict.org" } local function there(f) if f == "" then return nil else return f end end local function parse(u) local t = socket.try(url.parse(u, default)) socket.try(t.scheme == "dict", "invalid scheme '" .. t.scheme .. "'") socket.try(t.path, "invalid path in url") local cmd, arg = socket.skip(2, string.find(t.path, "^/(.)(.*)$")) socket.try(cmd == "d" or cmd == "m", "<command> should be 'm' or 'd'") socket.try(arg and arg ~= "", "need at least <word> in URL") t.command, t.argument = cmd, arg arg = string.gsub(arg, "^:([^:]+)", function(f) t.word = f end) socket.try(t.word, "need at least <word> in URL") arg = string.gsub(arg, "^:([^:]*)", function(f) t.database = there(f) end) if cmd == "m" then arg = string.gsub(arg, "^:([^:]*)", function(f) t.strat = there(f) end) end string.gsub(arg, ":([^:]*)$", function(f) t.n = base.tonumber(f) end) return t end local function tget(gett) local con = open(gett.host, gett.port) con:greet() if gett.command == "d" then local def = con:define(gett.database, gett.word) con:quit() con:close() if gett.n then return def[gett.n] else return def end elseif gett.command == "m" then local mat = con:match(gett.database, gett.strat, gett.word) con:quit() con:close() return mat else return nil, "invalid command" end end local function sget(u) local gett = parse(u) return tget(gett) end get = socket.protect(function(gett) if base.type(gett) == "string" then return sget(gett) else return tget(gett) end end)
mit
velukh/MplusLedger
Libs/AceGUI-3.0/widgets/AceGUIContainer-SimpleGroup.lua
15
1959
--[[----------------------------------------------------------------------------- SimpleGroup Container Simple container widget that just groups widgets. -------------------------------------------------------------------------------]] local Type, Version = "SimpleGroup", 20 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local pairs = pairs -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetWidth(300) self:SetHeight(100) end, -- ["OnRelease"] = nil, ["LayoutFinished"] = function(self, width, height) if self.noAutoHeight then return end self:SetHeight(height or 0) end, ["OnWidthSet"] = function(self, width) local content = self.content content:SetWidth(width) content.width = width end, ["OnHeightSet"] = function(self, height) local content = self.content content:SetHeight(height) content.height = height end } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:SetFrameStrata("FULLSCREEN_DIALOG") --Container Support local content = CreateFrame("Frame", nil, frame) content:SetPoint("TOPLEFT") content:SetPoint("BOTTOMRIGHT") local widget = { frame = frame, content = content, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsContainer(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Yhoator_Jungle/npcs/Ilieumort_RK.lua
8
2940
----------------------------------- -- Area: Yhoator Jungle -- NPC: Ilieumort, R.K. -- Outpost Conquest Guards -- @pos 200.254 -1 -80.324 124 ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yhoator_Jungle/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ELSHIMOUPLANDS; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/mobskills/Glacier_Splitter.lua
6
1085
--------------------------------------------- -- Glacier Splitter -- -- Description: Cleaves into targets in a fan-shaped area. Additional effect: Paralyze -- Type: Physical -- Utsusemi/Blink absorb: 1-3 shadows -- Range: Unknown cone -- Notes: Only used the Aern wielding a sword (RDM, DRK, and PLD). --------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------- function OnMobSkillCheck(target,mob,skill) return 0; end; function OnMobWeaponSkill(target, mob, skill) local numhits = math.random(1,3); local accmod = 1; local dmgmod = 1; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local typeEffect = EFFECT_PARALYSIS; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 15, 0, 120); target:delHP(dmg); return dmg; end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Port_San_dOria/npcs/Nogelle.lua
36
2293
----------------------------------- -- Area: Port San d'Oria -- NPC: Nogelle -- Starts Lufet's Lake Salt ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end if (player:getQuestStatus(SANDORIA,LUFET_S_LAKE_SALT) == QUEST_ACCEPTED) then count = trade:getItemCount(); LufetSalt = trade:hasItemQty(1019,3); if (LufetSalt == true and count == 3) then player:tradeComplete(); player:addFame(SANDORIA,SAN_FAME*30); player:addGil(GIL_RATE*600); player:addTitle(BEAN_CUISINE_SALTER); player:completeQuest(SANDORIA,LUFET_S_LAKE_SALT); player:startEvent(0x000b); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) LufetsLakeSalt = player:getQuestStatus(SANDORIA,LUFET_S_LAKE_SALT); if (LufetsLakeSalt == 0) then player:startEvent(0x000c); elseif (LufetsLakeSalt == 1) then player:startEvent(0x000a); elseif (LufetsLakeSalt == 2) then player:startEvent(0x020a); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x000c and option == 1) then player:addQuest(SANDORIA,LUFET_S_LAKE_SALT); elseif (csid == 0x000b) then player:messageSpecial(GIL_OBTAINED,GIL_RATE*600); end end;
gpl-3.0
Mogara/QSanguosha
lua/ai/standard_cards-ai.lua
5
119172
--[[******************************************************************** Copyright (c) 2013-2014 - QSanguosha-Rara This file is part of QSanguosha-Hegemony. This game is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See the LICENSE file for more details. QSanguosha-Rara *********************************************************************]] function SmartAI:canAttack(enemy, attacker, nature) attacker = attacker or self.player nature = nature or sgs.DamageStruct_Normal local damage = 1 if nature == sgs.DamageStruct_Fire and not enemy:hasArmorEffect("SilverLion") then if enemy:hasArmorEffect("Vine") then damage = damage + 1 end if enemy:getMark("@gale") > 0 then damage = damage + 1 end end if #self.enemies == 1 then return true end if self:getDamagedEffects(enemy, attacker) or (self:needToLoseHp(enemy, attacker, false, true) and #self.enemies > 1) or not sgs.isGoodTarget(enemy, self.enemies, self) then return false end if self:objectiveLevel(enemy) <= 2 or self:cantbeHurt(enemy, self.player, damage) or not self:damageIsEffective(enemy, nature, attacker) then return false end if nature ~= sgs.DamageStruct_Normal and enemy:isChained() and not self:isGoodChainTarget(enemy, self.player, nature) then return false end return true end function sgs.isGoodHp(player, observer) observer = observer or sgs.recorder.player local goodHp = player:getHp() > 1 or getCardsNum("Peach", player, observer) >= 1 or getCardsNum("Analeptic", player, observer) >= 1 or hasBuquEffect(player) or hasNiepanEffect(player) if goodHp then return goodHp else local n = 0 for _, friend in ipairs(sgs.recorder:getFriends(player)) do if global_room:getCurrent():hasShownSkill("wansha") and player:objectName() ~= friend:objectName() then continue end n = n + getCardsNum("Peach", friend, observer) end return n > 0 end return false end function sgs.isGoodTarget(player, targets, self, isSlash) if not self then global_room:writeToConsole(debug.traceback()) end -- self = self or sgs.ais[player:objectName()] local arr = { "jieming", "yiji", "fangzhu" } local m_skill = false local attacker = global_room:getCurrent() if targets and type(targets)=="table" then if #targets == 1 then return true end local foundtarget = false for i = 1, #targets, 1 do if sgs.isGoodTarget(targets[i], nil, self) and not self:cantbeHurt(targets[i]) then foundtarget = true break end end if not foundtarget then return true end end for _, masochism in ipairs(arr) do if player:hasShownSkill(masochism) then if masochism == "jieming" and self and self:getJiemingChaofeng(player) > -4 then m_skill = false elseif masochism == "yiji" and self and not self:findFriendsByType(sgs.Friend_Draw, player) then m_skill = false else m_skill = true break end end end if isSlash and self and (self:hasCrossbowEffect() or self:getCardsNum("Crossbow") > 0) and self:getCardsNum("Slash") > player:getHp() then return true end if m_skill and sgs.isGoodHp(player, self and self.player) then return false else return true end end function sgs.getDefenseSlash(player, self) if not player or not self then global_room:writeToConsole(debug.traceback()) return 0 end local attacker = self.player local unknownJink = getCardsNum("Jink", player, attacker) local defense = unknownJink local knownJink = getKnownCard(player, attacker, "Jink", true, "he") if sgs.card_lack[player:objectName()]["Jink"] == 1 and knownJink == 0 then defense = 0 end defense = defense + knownJink * 1.2 if attacker:canSlashWithoutCrossbow() and attacker:getPhase() == sgs.Player_Play then local hcard = player:getHandcardNum() if attacker:hasShownSkill("liegong") and (hcard >= attacker:getHp() or hcard <= attacker:getAttackRange()) then defense = 0 end end local niaoxiang_BA = false local jiangqin = sgs.findPlayerByShownSkillName("niaoxiang") if jiangqin then if jiangqin:inSiegeRelation(jiangqin, player) then niaoxiang_BA = true end end local need_double_jink = attacker:hasShownSkill("wushuang") or niaoxiang_BA if need_double_jink and knownJink < 2 and unknownJink < 1.5 then defense = 0 end local jink = sgs.cloneCard("jink") if player:isCardLimited(jink, sgs.Card_MethodUse) then defense = 0 end if player:hasFlag("QianxiTarget") then local red = player:getMark("@qianxi_red") > 0 local black = player:getMark("@qianxi_black") > 0 if red then if player:hasShownSkill("qingguo") then defense = defense - 1 else defense = 0 end elseif black then if player:hasShownSkill("qingguo") then defense = defense - 1 end end end defense = defense + math.min(player:getHp() * 0.45, 10) if sgs.isAnjiang(player) then defense = defense - 1 end local hasEightDiagram = false if (player:hasArmorEffect("EightDiagram") or (player:hasShownSkill("bazhen") and not player:getArmor())) and not IgnoreArmor(attacker, player) then hasEightDiagram = true end if hasEightDiagram then defense = defense + 1.3 if player:hasShownSkills("qingguo+tiandu") then defense = defense + 10 elseif player:hasShownSkill("tiandu") then defense = defense + 0.6 end if player:hasShownSkill("leiji") then defense = defense + 0.4 end if player:hasShownSkill("hongyan") then defense = defense + 0.2 end end if player:hasShownSkill("tuntian") and player:hasShownSkill("jixi") and unknownJink >= 1 then defense = defense + 1.5 end if attacker then local m = sgs.masochism_skill:split("|") for _, masochism in ipairs(m) do if player:hasShownSkill(masochism) and sgs.isGoodHp(player, self.player) then defense = defense + 1 end end if player:hasShownSkill("jieming") then defense = defense + 4 end if player:hasShownSkill("yiji") then defense = defense + 4 end end if not sgs.isGoodTarget(player, nil, self) then defense = defense + 10 end if player:hasShownSkill("rende") and player:getHp() > 2 then defense = defense + 1 end if player:hasShownSkill("kuanggu") and player:getHp() > 1 then defense = defense + 0.2 end if player:hasShownSkill("zaiqi") and player:getHp() > 1 then defense = defense + 0.35 end if player:getHp() <= 2 then defense = defense - 0.4 end local playernum = global_room:alivePlayerCount() if (player:getSeat()-attacker:getSeat()) % playernum >= playernum-2 and playernum>3 and player:getHandcardNum()<=2 and player:getHp()<=2 then defense = defense - 0.4 end if player:hasShownSkill("tianxiang") then defense = defense + player:getHandcardNum() * 0.5 end if player:getHandcardNum() == 0 and player:getPile("wooden_ox"):isEmpty() and not player:hasShownSkills("kongcheng") then if player:getHp() <= 1 then defense = defense - 2.5 end if player:getHp() == 2 then defense = defense - 1.5 end if not hasEightDiagram then defense = defense - 2 end end local has_fire_slash local cards = sgs.QList2Table(attacker:getHandcards()) for i = 1, #cards, 1 do if (attacker:hasWeapon("Fan") and cards[i]:objectName() == "slash" and not cards[i]:isKindOf("ThunderSlash")) or cards[i]:isKindOf("FireSlash") then has_fire_slash = true break end end if player:hasArmorEffect("Vine") and not IgnoreArmor(attacker, player) and has_fire_slash then defense = defense - 0.6 end if player:hasTreasure("JadeSeal") then defense = defense - 0.5 end if not player:faceUp() then defense = defense - 0.35 end if player:containsTrick("indulgence") then defense = defense - 0.15 end if player:containsTrick("supply_shortage") then defense = defense - 0.15 end if not hasEightDiagram then if player:hasShownSkill("jijiu") then defense = defense - 3 elseif sgs.hasNullSkill("jijiu", player) then defense = defense - 4 end if player:hasShownSkill("dimeng") then defense = defense - 2.5 elseif sgs.hasNullSkill("dimeng", player) then defense = defense - 3.5 end if player:hasShownSkill("guzheng") and knownJink == 0 then defense = defense - 2.5 elseif sgs.hasNullSkill("guzheng", player) and knownJink == 0 then defense = defense - 3.5 end if player:hasShownSkill("qiaobian") then defense = defense - 2.4 elseif sgs.hasNullSkill("qiaobian", player) then defense = defense - 3.4 end if player:hasShownSkill("jieyin") then defense = defense - 2.3 elseif sgs.hasNullSkill("jieyin", player) then defense = defense - 3.3 end if player:hasShownSkill("lijian") then defense = defense - 2.2 elseif sgs.hasNullSkill("lijian", player) then defense = defense - 3.2 end local m = sgs.masochism_skill:split("|") for _, masochism in ipairs(m) do if sgs.hasNullSkill(masochism, player) then defense = defense - 1 end end end return defense end function SmartAI:slashProhibit(card, enemy, from) card = card or sgs.cloneCard("slash", sgs.Card_NoSuit, 0) from = from or self.player if enemy:isRemoved() then return true end local nature = card:isKindOf("FireSlash") and sgs.DamageStruct_Fire or card:isKindOf("ThunderSlash") and sgs.DamageStruct_Thunder for _, askill in sgs.qlist(enemy:getVisibleSkillList(true)) do local filter = sgs.ai_slash_prohibit[askill:objectName()] if filter and type(filter) == "function" and filter(self, from, enemy, card) then return true end end if self:isFriend(enemy, from) then if (card:isKindOf("FireSlash") or from:hasWeapon("Fan")) and enemy:hasArmorEffect("Vine") and not (enemy:isChained() and self:isGoodChainTarget(enemy, from, nil, nil, card)) then return true end if enemy:isChained() and card:isKindOf("NatureSlash") and self:slashIsEffective(card, enemy, from) and not self:isGoodChainTarget(enemy, from, nature, nil, card) then return true end if getCardsNum("Jink",enemy, from) == 0 and enemy:getHp() < 2 and self:slashIsEffective(card, enemy, from) then return true end else if card:isKindOf("NatureSlash") and enemy:isChained() and not self:isGoodChainTarget(enemy, from, nature, nil, card) and self:slashIsEffective(card, enemy, from) then return true end end return not self:slashIsEffective(card, enemy, from) -- @todo: param of slashIsEffective end function SmartAI:canLiuli(daqiao, another) if not daqiao:hasShownSkill("liuli") then return false end if type(another) == "table" then if #another == 0 then return false end for _, target in ipairs(another) do if target:getHp() < 3 and self:canLiuli(daqiao, target) then return true end end return false end if not self:needToLoseHp(another, self.player, true) or not self:getDamagedEffects(another, self.player, true) then return false end if another:hasShownSkill("xiangle") then return false end local n = daqiao:getHandcardNum() if n > 0 and (daqiao:distanceTo(another) <= daqiao:getAttackRange()) then return true elseif daqiao:getWeapon() and daqiao:getOffensiveHorse() and (daqiao:distanceTo(another) <= daqiao:getAttackRange()) then return true elseif daqiao:getWeapon() or daqiao:getOffensiveHorse() then return daqiao:distanceTo(another) <= 1 else return false end end function SmartAI:slashIsEffective(slash, to, from, ignore_armor) if not slash or not to then self.room:writeToConsole(debug.traceback()) return end from = from or self.player if to:hasShownSkill("kongcheng") and to:isKongcheng() then return false end if to:isRemoved() then return false end local nature = sgs.Slash_Natures[slash:getClassName()] local damage = {} damage.from = from damage.to = to damage.nature = nature damage.damage = 1 if not from:hasShownAllGenerals() and to:hasShownSkill("mingshi") then local dummy_use = { to = sgs.SPlayerList() } dummy_use.to:append(to) local analeptic = self:searchForAnaleptic(dummy_use, to, slash) if analeptic and self:shouldUseAnaleptic(to, dummy_use) and analeptic:getEffectiveId() ~= slash:getEffectiveId() then damage.damage = damage.damage + 1 end end if not self:damageIsEffective_(damage) then return false end if to:hasSkill("jgyizhong") and not to:getArmor() and slash:isBlack() then if (from:hasWeapon("DragonPhoenix") or from:hasWeapon("DoubleSword") and (from:isMale() and to:isFemale() or from:isFemale() or to:isMale())) and (to:getCardCount(true) == 1 or #self:getEnemies(from) == 1) then else return false end end if not ignore_armor and to:hasArmorEffect("IronArmor") and slash:isKindOf("FireSlash") then return false end if not (ignore_armor or IgnoreArmor(from, to)) then if to:hasArmorEffect("RenwangShield") and slash:isBlack() then if (from:hasWeapon("DragonPhoenix") or from:hasWeapon("DoubleSword") and (from:isMale() and to:isFemale() or from:isFemale() or to:isMale())) and (to:getCardCount(true) == 1 or #self:getEnemies(from) == 1) then else return false end end if to:hasArmorEffect("Vine") and not slash:isKindOf("NatureSlash") then if (from:hasWeapon("DragonPhoenix") or from:hasWeapon("DoubleSword") and (from:isMale() and to:isFemale() or from:isFemale() or to:isMale())) and (to:getCardCount(true) == 1 or #self:getEnemies(from) == 1) then else local skill_name = slash:getSkillName() or "" local can_convert = false local skill = sgs.Sanguosha:getSkill(skill_name) if not skill or skill:inherits("FilterSkill") then can_convert = true end if not can_convert or not from:hasWeapon("Fan") then return false end end end end if slash:isKindOf("ThunderSlash") then local f_slash = self:getCard("FireSlash") if f_slash and self:hasHeavySlashDamage(from, f_slash, to, true) > self:hasHeavySlashDamage(from, slash, to, true) and (not to:isChained() or self:isGoodChainTarget(to, from, sgs.DamageStruct_Fire, nil, f_slash)) then return self:slashProhibit(f_slash, to, from) end elseif slash:isKindOf("FireSlash") then local t_slash = self:getCard("ThunderSlash") if t_slash and self:hasHeavySlashDamage(from, t_slash, to, true) > self:hasHeavySlashDamage(from, slash, to, true) and (not to:isChained() or self:isGoodChainTarget(to, from, sgs.DamageStruct_Thunder, nil, t_slash)) then return self:slashProhibit(t_slash, to, from) end end return true end function SmartAI:slashIsAvailable(player, slash) -- @todo: param of slashIsAvailable player = player or self.player if slash and not slash:isKindOf("Slash") then self.room:writeToConsole(debug.traceback()) end slash = slash or sgs.cloneCard("slash") return slash:isAvailable(player) end function SmartAI:findWeaponToUse(enemy) local weaponvalue = {} local hasweapon for _, c in sgs.qlist(self.player:getHandcards()) do if c:isKindOf("Weapon") then local dummy_use = { isDummy == true, to = sgs.SPlayerList() } self:useEquipCard(c, dummy_use) if dummy_use.card then weaponvalue[c] = self:evaluateWeapon(c, self.player, enemy) hasweapon = true end end end if not hasweapon then return end if self.player:getWeapon() then weaponvalue[self.player:getWeapon()] = self:evaluateWeapon(self.player:getWeapon(), self.player, enemy) end local max_value, max_card = -1000 for c, v in pairs(weaponvalue) do if v > max_value then max_card = c max_value = v end end if self.player:getWeapon() and self.player:getWeapon():getEffectiveId() == max_card:getEffectiveId() then return false end return max_card end function SmartAI:isPriorFriendOfSlash(friend, card, source) source = source or self.player local huatuo = sgs.findPlayerByShownSkillName("jijiu") if not self:hasHeavySlashDamage(source, card, friend) and (self:findLeijiTarget(friend, 50, source) or (friend:hasShownSkill("jieming") and source:hasShownSkill("rende") and huatuo and self:isFriend(huatuo, source))) then return true end if card:isKindOf("NatureSlash") and friend:isChained() and self:isGoodChainTarget(friend, source, nil, nil, card) then return true end return end function SmartAI:useCardSlash(card, use) if not use.isDummy and not self:slashIsAvailable(self.player, card) then return end local cards = self.player:getCards("he") cards = sgs.QList2Table(cards) local no_distance = sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_DistanceLimit, self.player, card) > 50 or self.player:hasFlag("slashNoDistanceLimit") self.slash_targets = 1 + sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_ExtraTarget, self.player, card) if self.player:hasSkill("duanbing") and self:willShowForAttack() then self.slash_targets = self.slash_targets + 1 end if self.player:hasFlag("HalberdUse") then self.slash_targets = self.slash_targets + 99 end local rangefix = 0 if card:isVirtualCard() then if self.player:getWeapon() and card:getSubcards():contains(self.player:getWeapon():getEffectiveId()) then if self.player:getWeapon():getClassName() ~= "Weapon" then rangefix = sgs.weapon_range[self.player:getWeapon():getClassName()] - self.player:getAttackRange(false) end end if self.player:getOffensiveHorse() and card:getSubcards():contains(self.player:getOffensiveHorse():getEffectiveId()) then rangefix = rangefix + 1 end end local function canAppendTarget(target) if not self:isWeak(target) and self:hasSkill("keji") and not self.player:hasFlag("KejiSlashInPlayPhase") and self:getOverflow() > 2 and self:getCardsNum("Crossbow", "he") == 0 then return end if self.player:hasSkill("qingnang") and not self.player:hasUsed("QingnangCard") and self:isWeak() and self.player:getHandcardNum() <= 2 and (target:getHp() > 1 or getCardsNum("Peach", target, self.player) + getCardsNum("Peach", target, self.player) > 0) then return end local targets = sgs.PlayerList() if use.to and not use.to:isEmpty() then if use.to:contains(target) then return false end for _, to in sgs.qlist(use.to) do targets:append(to) end end return card:targetFilter(targets, target, self.player) end for _, friend in ipairs(self.friends_noself) do if self:isPriorFriendOfSlash(friend, card) and not self:slashProhibit(card, friend) then if self.player:canSlash(friend, card, not no_distance, rangefix) or (use.isDummy and self.player:distanceTo(friend, rangefix) <= self.predictedRange) then use.card = card if use.to and canAppendTarget(friend) then use.to:append(friend) end if not use.to or self.slash_targets <= use.to:length() then return end end end end local targets = {} local forbidden = {} self:sort(self.enemies, "defenseSlash") for _, enemy in ipairs(self.enemies) do if not self:slashProhibit(card, enemy) and sgs.isGoodTarget(enemy, self.enemies, self, true) then if not self:getDamagedEffects(enemy, self.player, true) then table.insert(targets, enemy) else table.insert(forbidden, enemy) end end end if #targets == 0 and #forbidden > 0 then targets = forbidden end for _, target in ipairs(targets) do local canliuli = false for _, friend in ipairs(self.friends_noself) do if self:canLiuli(target, friend) and self:slashIsEffective(card, friend) and #targets > 1 and friend:getHp() < 3 then canliuli = true end end if (self.player:canSlash(target, card, not no_distance, rangefix) or (use.isDummy and self.predictedRange and self.player:distanceTo(target, rangefix) <= self.predictedRange)) and self:objectiveLevel(target) > 3 and not canliuli and not (not self:isWeak(target) and #self.enemies > 1 and #self.friends > 1 and self.player:hasSkill("keji") and self:getOverflow() > 0 and not self:hasCrossbowEffect()) then if target:getHp() > 1 and target:hasShownSkill("jianxiong") and self.player:hasWeapon("Spear") and card:getSkillName() == "Spear" then local ids, isGood = card:getSubcards(), true for _, id in sgs.qlist(ids) do local c = sgs.Sanguosha:getCard(id) if isCard("Peach", c, target) or isCard("Analeptic", c, target) then isGood = false break end end if not isGood then continue end end -- fill the card use struct local usecard = card if not use.to or use.to:isEmpty() then if self.player:hasWeapon("Spear") and card:getSkillName() == "Spear" then elseif self.player:hasWeapon("Crossbow") and self:getCardsNum("Slash") > 0 then elseif not use.isDummy then local weapon = self:findWeaponToUse(target) if weapon then use.card = weapon return end end if target:isChained() and self:isGoodChainTarget(target, nil, nil, nil, card) and not use.card then if self:hasCrossbowEffect() and card:isKindOf("NatureSlash") then for _, slash in ipairs(self:getCards("Slash")) do if not slash:isKindOf("NatureSlash") and self:slashIsEffective(slash, target) and not self:slashProhibit(slash, target) then usecard = slash break end end elseif not card:isKindOf("NatureSlash") then local slash = self:getCard("NatureSlash") if slash and self:slashIsEffective(slash, target) and not self:slashProhibit(slash, target) then usecard = slash end end end local godsalvation = self:getCard("GodSalvation") if not use.isDummy and godsalvation and godsalvation:getId() ~= card:getId() and self:willUseGodSalvation(godsalvation) and (not target:isWounded() or not self:hasTrickEffective(godsalvation, target, self.player)) then use.card = godsalvation return end end if not use.isDummy then local analeptic = self:searchForAnaleptic(use, target, use.card or usecard) if analeptic and self:shouldUseAnaleptic(target, use) and analeptic:getEffectiveId() ~= card:getEffectiveId() then use.card = analeptic if use.to then use.to = sgs.SPlayerList() end return end end use.card = use.card or usecard if use.to and canAppendTarget(target) then use.to:append(target) end if not use.to or self.slash_targets <= use.to:length() then return end end end for _, friend in ipairs(self.friends_noself) do if not self:slashProhibit(card, friend) and not self:hasHeavySlashDamage(self.player, card, friend) and (self:getDamagedEffects(friend, self.player) or self:needToLoseHp(friend, self.player, true, true)) and (self.player:canSlash(friend, card, not no_distance, rangefix) or (use.isDummy and self.predictedRange and self.player:distanceTo(friend, rangefix) <= self.predictedRange)) then use.card = card if use.to and canAppendTarget(friend) then use.to:append(friend) end if not use.to or self.slash_targets <= use.to:length() then return end end end end sgs.ai_skill_use.slash = function(self, prompt) if prompt == "@Halberd" then local ret = sgs.ai_skill_cardask["@Halberd"](self) return ret or "." end local parsedPrompt = prompt:split(":") local callback = sgs.ai_skill_cardask[parsedPrompt[1]] -- for askForUseSlashTo if self.player:hasFlag("slashTargetFixToOne") and type(callback) == "function" then local slash local target for _, player in sgs.qlist(self.room:getOtherPlayers(self.player)) do if player:hasFlag("SlashAssignee") then target = player break end end local target2 = nil if #parsedPrompt >= 3 then target2 = findPlayerByObjectName(parsedPrompt[3]) end if not target then return "." end local ret = callback(self, nil, nil, target, target2, prompt) if ret == nil or ret == "." then return "." end slash = sgs.Card_Parse(ret) assert(slash) if slash:isKindOf("HalbedrCard") then return ret elseif not self.player:hasFlag("Global_HalberdFailed") and self.player:getMark("Equips_Nullified_to_Yourself") == 0 and self.player:hasWeapon("Halberd") then local HalberdCard = sgs.Card_Parse("@HalberdCard=.") assert(HalberdCard) return "@HalberdCard=." end local no_distance = sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_DistanceLimit, self.player, slash) > 50 or self.player:hasFlag("slashNoDistanceLimit") local targets = {} local use = { to = sgs.SPlayerList() } if self.player:canSlash(target, slash, not no_distance) then use.to:append(target) else return "." end self:useCardSlash(slash, use) for _, p in sgs.qlist(use.to) do table.insert(targets, p:objectName()) end if table.contains(targets, target:objectName()) then return ret .. "->" .. table.concat(targets, "+") end return "." end local useslash, target local slashes = self:getCards("Slash") self:sortByUseValue(slashes) self:sort(self.enemies, "defenseSlash") for _, slash in ipairs(slashes) do local no_distance = sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_DistanceLimit, self.player, slash) > 50 or self.player:hasFlag("slashNoDistanceLimit") for _, friend in ipairs(self.friends_noself) do if not self:hasHeavySlashDamage(self.player, slash, friend) and self.player:canSlash(friend, slash, not no_distance) and not self:slashProhibit(slash, friend) and self:slashIsEffective(slash, friend) and (self:findLeijiTarget(friend, 50, self.player) or (friend:hasShownSkill("jieming") and self.player:hasSkill("rende"))) and not (self.player:hasFlag("slashTargetFix") and not friend:hasFlag("SlashAssignee")) then useslash = slash target = friend break end end end if not useslash then for _, slash in ipairs(slashes) do local no_distance = sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_DistanceLimit, self.player, slash) > 50 or self.player:hasFlag("slashNoDistanceLimit") for _, enemy in ipairs(self.enemies) do if self.player:canSlash(enemy, slash, not no_distance) and not self:slashProhibit(slash, enemy) and self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self) and not (self.player:hasFlag("slashTargetFix") and not enemy:hasFlag("SlashAssignee")) then useslash = slash target = enemy break end end end end if useslash and target then local targets = {} local use = { to = sgs.SPlayerList() } use.to:append(target) self:useCardSlash(useslash, use) for _, p in sgs.qlist(use.to) do table.insert(targets, p:objectName()) end if table.contains(targets, target:objectName()) then return useslash:toString() .. "->" .. table.concat(targets, "+") end end return "." end sgs.ai_skill_playerchosen.slash_extra_targets = function(self, targets) local slash = sgs.cloneCard("slash") targets = sgs.QList2Table(targets) self:sort(targets, "defenseSlash") for _, target in ipairs(targets) do if self:isEnemy(target) and not self:slashProhibit(slash, target) and sgs.isGoodTarget(target, targets, self) and self:slashIsEffective(slash, target) then return target end end return nil end sgs.ai_skill_playerchosen.zero_card_as_slash = function(self, targets) local slash = sgs.cloneCard("slash") local targetlist = sgs.QList2Table(targets) local arrBestHp, canAvoidSlash, forbidden = {}, {}, {} self:sort(targetlist, "defenseSlash") for _, target in ipairs(targetlist) do if self:isEnemy(target) and not self:slashProhibit(slash ,target) and sgs.isGoodTarget(target, targetlist, self) then if self:slashIsEffective(slash, target) then if self:getDamagedEffects(target, self.player, true) or self:needLeiji(target, self.player) then table.insert(forbidden, target) elseif self:needToLoseHp(target, self.player, true, true) then table.insert(arrBestHp, target) else return target end else table.insert(canAvoidSlash, target) end end end for i=#targetlist, 1, -1 do local target = targetlist[i] if not self:slashProhibit(slash, target) then if self:slashIsEffective(slash, target) then if self:isFriend(target) and (self:needToLoseHp(target, self.player, true, true) or self:getDamagedEffects(target, self.player, true) or self:needLeiji(target, self.player)) then return target end else table.insert(canAvoidSlash, target) end end end if #canAvoidSlash > 0 then return canAvoidSlash[1] end if #arrBestHp > 0 then return arrBestHp[1] end self:sort(targetlist, "defenseSlash") targetlist = sgs.reverse(targetlist) for _, target in ipairs(targetlist) do if target:objectName() ~= self.player:objectName() and not self:isFriend(target) and not table.contains(forbidden, target) then return target end end return targetlist[1] end sgs.ai_card_intention.Slash = function(self, card, from, tos) for _, to in ipairs(tos) do local value = 80 sgs.updateIntention(from, to, value) end end sgs.ai_skill_cardask["slash-jink"] = function(self, data, pattern, target) local isdummy = type(data) == "number" local function getJink() local cards = self:getCards("Jink") self:sortByKeepValue(cards) for _, card in ipairs(cards) do if self.room:isJinkEffected(self.player, card) then return card:toString() end end return not isdummy and "." end local slash if type(data) == "userdata" then local effect = data:toSlashEffect() slash = effect.slash else slash = sgs.cloneCard("slash") end local cards = sgs.QList2Table(self.player:getHandcards()) if sgs.ai_skill_cardask.nullfilter(self, data, pattern, target) then return "." end if not target then return getJink() end if not self:hasHeavySlashDamage(target, slash, self.player) and self:getDamagedEffects(self.player, target, slash) then return "." end if slash:isKindOf("NatureSlash") and self.player:isChained() and self:isGoodChainTarget(self.player, target, nil, nil, slash) then return "." end if self:isFriend(target) then if self:findLeijiTarget(self.player, 50, target) then return getJink() end if target:hasShownSkill("jieyin") and not self.player:isWounded() and self.player:isMale() and not self.player:hasSkill("leiji") then return "." end if target:hasShownSkill("rende") and self.player:hasSkill("jieming") then return "." end else if self:hasHeavySlashDamage(target, slash) then return getJink() end if self.player:getHandcardNum() == 1 and self:needKongcheng() then return getJink() end if not self:hasLoseHandcardEffective() and not self.player:isKongcheng() then return getJink() end if target:hasShownSkill("mengjin") then if self:doNotDiscard(self.player, "he", true) then return getJink() end if self.player:getCards("he"):length() == 1 and not self.player:getArmor() then return getJink() end if self.player:hasSkills("jijiu|qingnang") and self.player:getCards("he"):length() > 1 then return "." end if (self:getCardsNum("Peach") > 0 or (self:getCardsNum("Analeptic") > 0 and self:isWeak())) and not self.player:hasSkill("tuntian") and not self:willSkipPlayPhase() then return "." end end if target:hasWeapon("Axe") then if target:hasShownSkills(sgs.lose_equip_skill) and target:getEquips():length() > 1 and target:getCards("he"):length() > 2 then return not isdummy and "." end if target:getHandcardNum() - target:getHp() > 2 and not self:isWeak() and not self:getOverflow() then return not isdummy and "." end end end return getJink() end sgs.dynamic_value.damage_card.Slash = true sgs.ai_use_value.Slash = 4.5 sgs.ai_keep_value.Slash = 3.6 sgs.ai_use_priority.Slash = 2.6 function SmartAI:canHit(to, from, conservative) from = from or self.room:getCurrent() to = to or self.player local jink = sgs.cloneCard("jink") if to:isCardLimited(jink, sgs.Card_MethodUse) then return true end if self:canLiegong(to, from) then return true end if not self:isFriend(to, from) then if from:hasWeapon("Axe") and from:getCards("he"):length() > 2 then return true end if from:hasShownSkill("mengjin") and not self:hasHeavySlashDamage(from, nil, to) and not self:needLeiji(to, from) then if self:doNotDiscard(to, "he", true) then elseif to:getCards("he"):length() == 1 and not to:getArmor() then elseif self:willSkipPlayPhase() then elseif (getCardsNum("Peach", to, from) > 0 or getCardsNum("Analeptic", to, from) > 0) then return true elseif not self:isWeak(to) and to:getArmor() and not self:needToThrowArmor() then return true elseif not self:isWeak(to) and to:getDefensiveHorse() then return true end end end local hasHeart, hasRed, hasBlack if to:objectName() == self.player:objectName() then for _, card in ipairs(self:getCards("Jink")) do if card:getSuit() == sgs.Card_Heart then hasHeart = true end if card:isRed() then hasRed = true end if card:isBlack() then hasBlack = true end end end if to:getMark("@qianxi_red") > 0 and not hasBlack then return true end if to:getMark("@qianxi_black") > 0 and not hasRed then return true end if not conservative and self:hasHeavySlashDamage(from, nil, to) then conservative = true end if not conservative and self:hasEightDiagramEffect(to) and not IgnoreArmor(from, to) then return false end local need_double_jink = from and from:hasShownSkill("wushuang") if to:objectName() == self.player:objectName() then if getCardsNum("Jink", to, from) == 0 then return true end if need_double_jink and getCardsNum("Jink", to, from) < 2 then return true end end if getCardsNum("Jink", to, from) == 0 then return true end if need_double_jink and getCardsNum("Jink", to, from) < 2 then return true end return false end function SmartAI:useCardPeach(card, use) if not self.player:isWounded() then return end local mustusepeach = false local peaches = 0 local cards = sgs.QList2Table(self.player:getHandcards()) for _, card in ipairs(cards) do if isCard("Peach", card, self.player) then peaches = peaches + 1 end end if self.player:hasSkill("rende") and self:findFriendsByType(sgs.Friend_Draw) then return end if not use.isDummy then if self.player:hasArmorEffect("SilverLion") then for _, card in sgs.qlist(self.player:getHandcards()) do if card:isKindOf("Armor") and self:evaluateArmor(card) > 0 then use.card = card return end end end local SilverLion, OtherArmor for _, card in sgs.qlist(self.player:getHandcards()) do if card:isKindOf("SilverLion") then SilverLion = card elseif card:isKindOf("Armor") and not card:isKindOf("SilverLion") and self:evaluateArmor(card) > 0 then OtherArmor = true end end if SilverLion and OtherArmor then use.card = SilverLion return end end for _, enemy in ipairs(self.enemies) do if self.player:getHandcardNum() < 3 and (enemy:hasShownSkills(sgs.drawpeach_skill) or getCardsNum("Dismantlement", enemy, self.player) >= 1 or enemy:hasShownSkill("jixi") and enemy:getPile("field"):length() >0 and enemy:distanceTo(self.player) == 1 or enemy:hasShownSkill("qixi") and getKnownCard(enemy, self.player, "black", nil, "he") >= 1 or getCardsNum("Snatch", enemy, self.player) >= 1 and enemy:distanceTo(self.player) == 1 or (enemy:hasShownSkill("tiaoxin") and (self.player:inMyAttackRange(enemy) and self:getCardsNum("Slash") < 1 or not self.player:canSlash(enemy)))) then mustusepeach = true break end end local maxCards = self:getOverflow(self.player, true) local overflow = self:getOverflow() > 0 if self.player:hasSkill("buqu") and self.player:getHp() < 1 and maxCards == 0 then use.card = card return end if mustusepeach or peaches > maxCards or self.player:getHp() == 1 then use.card = card return end if not overflow and #self.friends_noself > 0 then return end local useJieyinCard if self.player:hasSkill("jieyin") and not self.player:hasUsed("JieyinCard") and overflow and self.player:getPhase() == sgs.Player_Play then self:sort(self.friends, "hp") for _, friend in ipairs(self.friends) do if friend:isWounded() and friend:isMale() then useJieyinCard = true end end end if overflow then self:sortByKeepValue(cards) local handcardNum = self.player:getHandcardNum() - (useJieyinCard and 2 or 0) local discardNum = handcardNum - maxCards if discardNum > 0 then for i, c in ipairs(cards) do if c:getEffectiveId() == card:getEffectiveId() then use.card = card return end if i >= discardNum then break end end end end local lord = self.player:getLord() if lord and lord:getHp() <= 2 and self:isWeak(lord) then if self.player:isLord() then use.card = card end return end if self:needToLoseHp(self.player, nil, nil, nil, true) then return end self:sort(self.friends, "hp") if self.friends[1]:objectName() == self.player:objectName() or self.player:getHp() < 2 then use.card = card return end if #self.friends > 1 and ((not hasBuquEffect(self.friends[2]) and self.friends[2]:getHp() < 3 and self:getOverflow() < 2) or (not hasBuquEffect(self.friends[1]) and self.friends[1]:getHp() < 2 and peaches <= 1 and self:getOverflow() < 3)) then return end use.card = card end sgs.ai_card_intention.Peach = function(self, card, from, tos) for _, to in ipairs(tos) do sgs.updateIntention(from, to, -120) end end sgs.ai_use_value.Peach = 7 sgs.ai_keep_value.Peach = 7 sgs.ai_use_priority.Peach = 0.9 sgs.ai_use_value.Jink = 8.9 sgs.ai_keep_value.Jink = 5.2 sgs.dynamic_value.benefit.Peach = true sgs.ai_keep_value.Weapon = 2.08 sgs.ai_keep_value.Armor = 2.06 sgs.ai_keep_value.Treasure = 2.05 sgs.ai_keep_value.Horse = 2.04 sgs.weapon_range.Weapon = 1 sgs.weapon_range.Crossbow = 1 sgs.weapon_range.DoubleSword = 2 sgs.weapon_range.QinggangSword = 2 sgs.weapon_range.IceSword = 2 sgs.weapon_range.GudingBlade = 2 sgs.weapon_range.Axe = 3 sgs.weapon_range.Blade = 3 sgs.weapon_range.Spear = 3 sgs.weapon_range.Halberd = 4 sgs.weapon_range.KylinBow = 5 sgs.weapon_range.SixSwords = 2 sgs.weapon_range.DragonPhoenix = 2 sgs.weapon_range.Triblade = 3 sgs.ai_skill_invoke.DoubleSword = function(self, data) return not self:needKongcheng(self.player, true) end function sgs.ai_slash_weaponfilter.DoubleSword(self, to, player) return player:distanceTo(to) <= math.max(sgs.weapon_range.DoubleSword, player:getAttackRange()) and player:getGender() ~= to:getGender() end function sgs.ai_weapon_value.DoubleSword(self, enemy, player) if enemy and enemy:isMale() ~= player:isMale() then return 4 end end function SmartAI:getExpectedJinkNum(use) local jink_list = use.from:getTag("Jink_" .. use.card:toString()):toStringList() local index, jink_num = 1, 1 for _, p in sgs.qlist(use.to) do if p:objectName() == self.player:objectName() then local n = tonumber(jink_list[index]) if n == 0 then return 0 elseif n > jink_num then jink_num = n end end index = index + 1 end return jink_num end sgs.ai_skill_cardask["double-sword-card"] = function(self, data, pattern, target) if self.player:isKongcheng() then return "." end local use = data:toCardUse() local jink_num = self:getExpectedJinkNum(use) if jink_num > 1 and self:getCardsNum("Jink") == jink_num then return "." end if self:needKongcheng(self.player, true) and self.player:getHandcardNum() <= 2 then if self.player:getHandcardNum() == 1 then local card = self.player:getHandcards():first() return (jink_num > 0 and isCard("Jink", card, self.player)) and "." or ("$" .. card:getEffectiveId()) end if self.player:getHandcardNum() == 2 then local first = self.player:getHandcards():first() local last = self.player:getHandcards():last() local jink = isCard("Jink", first, self.player) and first or (isCard("Jink", last, self.player) and last) if jink then return first:getEffectiveId() == jink:getEffectiveId() and ("$"..last:getEffectiveId()) or ("$"..first:getEffectiveId()) end end end if target and self:isFriend(target) then return "." end if target and self:needKongcheng(target, true) then return "." end local cards = self.player:getHandcards() for _, card in sgs.qlist(cards) do if (card:isKindOf("Slash") and self:getCardsNum("Slash") > 1) or (card:isKindOf("Jink") and self:getCardsNum("Jink") > 2) or card:isKindOf("Disaster") or (card:isKindOf("EquipCard") and not self.player:hasSkills(sgs.lose_equip_skill)) or (not self.player:hasSkill("jizhi") and (card:isKindOf("Collateral") or card:isKindOf("GodSalvation") or card:isKindOf("FireAttack") or card:isKindOf("IronChain") or card:isKindOf("AmazingGrace"))) then return "$" .. card:getEffectiveId() end end return "." end function sgs.ai_weapon_value.QinggangSword(self, enemy) if enemy and enemy:getArmor() and enemy:hasArmorEffect(enemy:getArmor():objectName()) then return 3 end end function sgs.ai_slash_weaponfilter.QinggangSword(self, enemy, player) if player:distanceTo(enemy) > math.max(sgs.weapon_range.QinggangSword, player:getAttackRange()) then return end if enemy:getArmor() and enemy:hasArmorEffect(enemy:getArmor():objectName()) and (sgs.card_lack[enemy:objectName()] == 1 or getCardsNum("Jink", enemy, self.player) < 1) then return true end end sgs.ai_skill_invoke.IceSword = function(self, data) local damage = data:toDamage() local target = damage.to if self:isFriend(target) then if self:getDamagedEffects(target, self.players, true) or self:needToLoseHp(target, self.player, true) then return false elseif target:isChained() and self:isGoodChainTarget(target, self.player, nil, nil, damage.card) then return false elseif self:isWeak(target) or damage.damage > 1 then return true elseif target:getLostHp() < 1 then return false end return true else if self:isWeak(target) then return false end if damage.damage > 1 or self:hasHeavySlashDamage(self.player, damage.card, target) then return false end if target:hasShownSkill("lirang") and #self:getFriendsNoself(target) > 0 then return false end if target:getArmor() and self:evaluateArmor(target:getArmor(), target) > 3 and not (target:hasArmorEffect("SilverLion") and target:isWounded()) then return true end local num = target:getHandcardNum() if self.player:hasSkill("tieqi") or self:canLiegong(target, self.player) then return false end if target:hasShownSkill("tuntian") and target:getPhase() == sgs.Player_NotActive then return false end if target:hasShownSkills(sgs.need_kongcheng) then return false end if target:getCards("he"):length()<4 and target:getCards("he"):length()>1 then return true end return false end end function sgs.ai_slash_weaponfilter.GudingBlade(self, to) return to:isKongcheng() and not to:hasArmorEffect("SilverLion") end function sgs.ai_weapon_value.GudingBlade(self, enemy) if not enemy then return end local value = 2 if enemy:getHandcardNum() < 1 and not enemy:hasArmorEffect("SilverLion") then value = 4 end return value end function SmartAI:needToThrowAll(player) player = player or self.player if player:getPhase() == sgs.Player_NotActive or player:getPhase() == sgs.Player_Finish then return false end local erzhang = sgs.findPlayerByShownSkillName("guzheng") if erzhang and not zhanglu and self:isFriend(erzhang, player) then return false end self.yongsi_discard = nil local index = 0 local kingdom_num = 0 local kingdoms = {} for _, ap in sgs.qlist(self.room:getAlivePlayers()) do if not kingdoms[ap:getKingdom()] then kingdoms[ap:getKingdom()] = true kingdom_num = kingdom_num + 1 end end local cards = self.player:getCards("he") local Discards = {} for _, card in sgs.qlist(cards) do local shouldDiscard = true if card:isKindOf("Axe") then shouldDiscard = false end if isCard("Peach", card, player) or isCard("Slash", card, player) then local dummy_use = { isDummy = true } self:useBasicCard(card, dummy_use) if dummy_use.card then shouldDiscard = false end end if card:getTypeId() == sgs.Card_TypeTrick then local dummy_use = { isDummy = true } self:useTrickCard(card, dummy_use) if dummy_use.card then shouldDiscard = false end end if shouldDiscard then if #Discards < 2 then table.insert(Discards, card:getId()) end index = index + 1 end end if #Discards == 2 and index < kingdom_num then self.yongsi_discard = Discards return true end return false end sgs.ai_skill_cardask["@Axe"] = function(self, data, pattern, target) if target and self:isFriend(target) then return "." end local effect = data:toSlashEffect() local allcards = self.player:getCards("he") allcards = sgs.QList2Table(allcards) if self:hasHeavySlashDamage(self.player, effect.slash, target) or (#allcards - 3 >= self.player:getHp()) or (self.player:hasSkill("kuanggu") and self.player:isWounded() and self.player:distanceTo(effect.to) == 1) or (effect.to:getHp() == 1 and not effect.to:hasShownSkill("buqu")) or (self:needKongcheng() and self.player:getHandcardNum() > 0) or (self.player:hasSkills(sgs.lose_equip_skill) and self.player:getEquips():length() > 1 and self.player:getHandcardNum() < 2) or self:needToThrowAll() then local discard = self.yongsi_discard if discard then return "$"..table.concat(discard, "+") end local hcards = {} for _, c in sgs.qlist(self.player:getHandcards()) do if not (isCard("Slash", c, self.player) and self:hasCrossbowEffect()) and (not isCard("Peach", c, self.player) or target:getHp() == 1 and self:isWeak(target)) then table.insert(hcards, c) end end self:sortByKeepValue(hcards) local cards = {} local hand, armor, def, off = 0, 0, 0, 0 if self:needToThrowArmor() then table.insert(cards, self.player:getArmor():getEffectiveId()) armor = 1 end if (self.player:hasSkills(sgs.need_kongcheng) or not self:hasLoseHandcardEffective()) and self.player:getHandcardNum() > 0 then hand = 1 for _, card in ipairs(hcards) do table.insert(cards, card:getEffectiveId()) if #cards == 2 then break end end end if #cards < 2 and self.player:hasSkills(sgs.lose_equip_skill) then if #cards < 2 and self.player:getOffensiveHorse() then off = 1 table.insert(cards, self.player:getOffensiveHorse():getEffectiveId()) end if #cards < 2 and self.player:getArmor() then armor = 1 table.insert(cards, self.player:getArmor():getEffectiveId()) end if #cards < 2 and self.player:getDefensiveHorse() then def = 1 table.insert(cards, self.player:getDefensiveHorse():getEffectiveId()) end end if #cards < 2 and hand < 1 and self.player:getHandcardNum() > 2 then hand = 1 for _, card in ipairs(hcards) do table.insert(cards, card:getEffectiveId()) if #cards == 2 then break end end end if #cards < 2 and off < 1 and self.player:getOffensiveHorse() then off = 1 table.insert(cards, self.player:getOffensiveHorse():getEffectiveId()) end if #cards < 2 and hand < 1 and self.player:getHandcardNum() > 0 then hand = 1 for _, card in ipairs(hcards) do table.insert(cards, card:getEffectiveId()) if #cards == 2 then break end end end if #cards < 2 and armor < 1 and self.player:getArmor() then armor = 1 table.insert(cards, self.player:getArmor():getEffectiveId()) end if #cards < 2 and def < 1 and self.player:getDefensiveHorse() then def = 1 table.insert(cards, self.player:getDefensiveHorse():getEffectiveId()) end if #cards == 2 then local num = 0 for _, id in ipairs(cards) do if self.player:hasEquip(sgs.Sanguosha:getCard(id)) then num = num + 1 end end local eff = self:damageIsEffective(effect.to, effect.nature, self.player) if not eff then return "." end return "$" .. table.concat(cards, "+") end end end function sgs.ai_slash_weaponfilter.Axe(self, to, player) return player:distanceTo(to) <= math.max(sgs.weapon_range.Axe, player:getAttackRange()) and self:getOverflow(player) > 0 end function sgs.ai_weapon_value.Axe(self, enemy, player) if player:hasShownSkill("luoyi") then return 6 end if enemy and self:getOverflow() > 0 then return 2 end if enemy and enemy:getHp() < 3 then return 3 - enemy:getHp() end end function sgs.ai_cardsview.Spear(self, class_name, player, cards) if class_name == "Slash" then if not cards then cards = {} for _, c in sgs.qlist(player:getHandcards()) do if sgs.cardIsVisible(c, player, self.player) and c:isKindOf("Slash") then continue end table.insert(cards, c) end for _, id in sgs.qlist(player:getPile("wooden_ox")) do c = sgs.Sanguosha:getCard(id) if sgs.cardIsVisible(c, player, self.player) and c:isKindOf("Slash") then continue end table.insert(cards, c) end end if #cards < 2 then return {} end sgs.ais[player:objectName()]:sortByKeepValue(cards) local newcards = {} for _, card in ipairs(cards) do if not self.room:getCardOwner(card:getEffectiveId()) or self.room:getCardOwner(card:getEffectiveId()):objectName() ~= player:objectName() or self.room:getCardPlace(card:getEffectiveId()) ~= sgs.Player_PlaceHand then continue end if not isCard("Peach", card, player) and not (isCard("ExNihilo", card, player) and player:getPhase() == sgs.Player_Play) then table.insert(newcards, card) end end if #newcards < 2 then return {} end local card_str = {} for i = 1, #newcards, 2 do if i + 1 > #newcards then break end local id1 = newcards[i]:getEffectiveId() local id2 = newcards[i + 1]:getEffectiveId() local str = ("slash:%s[%s:%s]=%d+%d&"):format("Spear", "to_be_decided", 0, id1, id2) table.insert(card_str , str) end return card_str end end function turnUse_spear(self, inclusive, skill_name) if self.player:hasSkill("wusheng") then local cards = self.player:getCards("he") cards = sgs.QList2Table(cards) for _, id in sgs.qlist(self.player:getPile("wooden_ox")) do table.insert(cards, sgs.Sanguosha:getCard(id)) end for _, acard in ipairs(cards) do if isCard("Slash", acard, self.player) then return end end end local cards = self.player:getCards("h") cards = sgs.QList2Table(cards) self:sortByUseValue(cards) local newcards = {} for _, card in ipairs(cards) do if not isCard("Slash", card, self.player) and not isCard("Peach", card, self.player) and not (isCard("ExNihilo", card, self.player) and self.player:getPhase() == sgs.Player_Play) then table.insert(newcards, card) end end if #cards <= self.player:getHp() - 1 and self.player:getHp() <= 4 and not self:hasHeavySlashDamage(self.player) and not self.player:hasSkills("kongcheng|paoxiao") then return end if #newcards < 2 then return end local card_id1 = newcards[1]:getEffectiveId() local card_id2 = newcards[2]:getEffectiveId() if newcards[1]:isBlack() and newcards[2]:isBlack() then local black_slash = sgs.cloneCard("slash", sgs.Card_NoSuitBlack) local nosuit_slash = sgs.cloneCard("slash") self:sort(self.enemies, "defenseSlash") for _, enemy in ipairs(self.enemies) do if self.player:canSlash(enemy) and not self:slashProhibit(nosuit_slash, enemy) and self:slashIsEffective(nosuit_slash, enemy) and self:canAttack(enemy) and self:slashProhibit(black_slash, enemy) and self:isWeak(enemy) then local redcards, blackcards = {}, {} for _, acard in ipairs(newcards) do if acard:isBlack() then table.insert(blackcards, acard) else table.insert(redcards, acard) end end if #redcards == 0 then break end local redcard, othercard self:sortByUseValue(blackcards, true) self:sortByUseValue(redcards, true) redcard = redcards[1] othercard = #blackcards > 0 and blackcards[1] or redcards[2] if redcard and othercard then card_id1 = redcard:getEffectiveId() card_id2 = othercard:getEffectiveId() break end end end end local card_str = ("slash:%s[%s:%s]=%d+%d&%s"):format(skill_name, "to_be_decided", 0, card_id1, card_id2, skill_name) local slash = sgs.Card_Parse(card_str) assert(slash) return slash end local Spear_skill = {} Spear_skill.name = "Spear" table.insert(sgs.ai_skills, Spear_skill) Spear_skill.getTurnUseCard = function(self, inclusive) return turnUse_spear(self, inclusive, "Spear") end function sgs.ai_weapon_value.Spear(self, enemy, player) if enemy and getCardsNum("Slash", player, self.player) == 0 then if self:getOverflow(player) > 0 then return 2 elseif player:getHandcardNum() > 2 then return 1 end end return 0 end function sgs.ai_slash_weaponfilter.Fan(self, to, player) return player:distanceTo(to) <= math.max(sgs.weapon_range.Fan, player:getAttackRange()) and to:hasArmorEffect("Vine") end sgs.ai_skill_invoke.KylinBow = function(self, data) local damage = data:toDamage() if damage.from:hasShownSkill("kuangfu") and damage.to:getCards("e"):length() == 1 then return false end if damage.to:hasShownSkills(sgs.lose_equip_skill) then return self:isFriend(damage.to) end return self:isEnemy(damage.to) end function sgs.ai_slash_weaponfilter.KylinBow(self, to, player) return player:distanceTo(to) <= math.max(sgs.weapon_range.KylinBow, player:getAttackRange()) and (to:getDefensiveHorse() or to:getOffensiveHorse()) end function sgs.ai_weapon_value.KylinBow(self, enemy) if enemy and (enemy:getOffensiveHorse() or enemy:getDefensiveHorse()) then return 1 end end sgs.ai_skill_invoke.EightDiagram = function(self, data) local jink = sgs.cloneCard("jink") if not self.room:isJinkEffected(self.player, jink) then return false end if self:getDamagedEffects(self.player, nil, true) or self:needToLoseHp(self.player, nil, true, true) then return false end if self:getCardsNum("Jink") == 0 then return true end local zhangjiao = sgs.findPlayerByShownSkillName("guidao") if zhangjiao and self:isEnemy(zhangjiao) then if getKnownCard(zhangjiao, self.player, "black", false, "he") > 1 then return false end if self:getCardsNum("Jink") > 1 and getKnownCard(zhangjiao, self.player, "black", false, "he") > 0 then return false end if zhangjiao:getHandcardNum() - getKnownNum(zhangjiao, self.player) >= 3 then return false end end return true end function sgs.ai_armor_value.EightDiagram(player, self) local haszj = self:hasSkills("guidao", self:getEnemies(player)) if haszj then return 2 end if player:hasShownSkills("tiandu|leiji") then return 6 end return 4 end function sgs.ai_armor_value.RenwangShield(player, self) if player:hasShownSkill("bazhen") then return 0 end if player:hasShownSkill("leiji") and getKnownCard(player, self.player, "Jink", true) > 1 and player:hasShownSkill("guidao") and getKnownCard(player, self.player, "black", false, "he") > 0 then return 0 end return 4.5 end function sgs.ai_armor_value.SilverLion(player, self) if self:hasWizard(self:getEnemies(player), true) then for _, player in sgs.qlist(self.room:getAlivePlayers()) do if player:containsTrick("lightning") then return 5 end end end if self.player:isWounded() and not self.player:getArmor() then return 9 end if self.player:isWounded() and self:getCardsNum("Armor", "h") >= 2 and not self.player:hasArmorEffect("SilverLion") then return 8 end return 1 end sgs.ai_use_priority.Axe = 2.688 sgs.ai_use_priority.Halberd = 2.685 sgs.ai_use_priority.KylinBow = 2.68 sgs.ai_use_priority.Blade = 2.675 sgs.ai_use_priority.GudingBlade = 2.67 sgs.ai_use_priority.DoubleSword =2.665 sgs.ai_use_priority.Spear = 2.66 sgs.ai_use_priority.IceSword = 2.65 -- sgs.ai_use_priority.Fan = 2.655 sgs.ai_use_priority.QinggangSword = 2.645 sgs.ai_use_priority.Crossbow = 2.63 sgs.ai_use_priority.SilverLion = 1.0 -- sgs.ai_use_priority.Vine = 0.95 -- sgs.ai_use_priority.Breastplate = 0.95 sgs.ai_use_priority.RenwangShield = 0.85 --sgs.ai_use_priority.IronArmor = 0.82 sgs.ai_use_priority.EightDiagram = 0.8 sgs.ai_use_priority.DefensiveHorse = 2.75 sgs.ai_use_priority.OffensiveHorse = 2.69 function SmartAI:useCardArcheryAttack(card, use) if self:getAoeValue(card) > 0 then use.card = card end end function SmartAI:useCardSavageAssault(card, use) if self:getAoeValue(card) > 0 then use.card = card end end sgs.dynamic_value.damage_card.ArcheryAttack = true sgs.dynamic_value.damage_card.SavageAssault = true sgs.ai_use_value.ArcheryAttack = 3.8 sgs.ai_use_priority.ArcheryAttack = 3.5 sgs.ai_keep_value.ArcheryAttack = 3.35 sgs.ai_use_value.SavageAssault = 3.9 sgs.ai_use_priority.SavageAssault = 3.5 sgs.ai_keep_value.SavageAssault = 3.34 sgs.ai_skill_cardask.aoe = function(self, data, pattern, target, name) if sgs.ai_skill_cardask.nullfilter(self, data, pattern, target) then return "." end local aoe if type(data) == "userdata" then aoe = data:toCardEffect().card else aoe = sgs.cloneCard(name) end assert(aoe ~= nil) local menghuo = sgs.findPlayerByShownSkillName("huoshou") local attacker = target if menghuo and aoe:isKindOf("SavageAssault") then attacker = menghuo end if not self:damageIsEffective(nil, nil, attacker) then return "." end if self:getDamagedEffects(self.player, attacker) or self:needToLoseHp(self.player, attacker) then return "." end if self.player:hasSkill("jianxiong") and (self.player:getHp() > 1 or self:getAllPeachNum() > 0) and not self:willSkipPlayPhase() then if not self:needKongcheng(self.player, true) and self:getAoeValue(aoe) > 0 then return "." end end end sgs.ai_skill_cardask["savage-assault-slash"] = function(self, data, pattern, target) return sgs.ai_skill_cardask.aoe(self, data, pattern, target, "savage_assault") end sgs.ai_skill_cardask["archery-attack-jink"] = function(self, data, pattern, target) return sgs.ai_skill_cardask.aoe(self, data, pattern, target, "archery_attack") end sgs.ai_keep_value.Nullification = 3.8 sgs.ai_use_value.Nullification = 7.8 function SmartAI:useCardAmazingGrace(card, use) local value = 1 local suf, coeff = 0.8, 0.8 if self:needKongcheng() and self.player:getHandcardNum() == 1 or self.player:hasSkill("jizhi") then suf = 0.6 coeff = 0.6 end for _, player in sgs.qlist(self.room:getOtherPlayers(self.player)) do local index = 0 if self:hasTrickEffective(card, player, self.player) then if self:isFriend(player) then index = 1 elseif self:isEnemy(player) then index = -1 end end value = value + index * suf if value < 0 then return end suf = suf * coeff end use.card = card end sgs.ai_use_value.AmazingGrace = 3 sgs.ai_keep_value.AmazingGrace = -1 sgs.ai_use_priority.AmazingGrace = 1.2 sgs.dynamic_value.benefit.AmazingGrace = true function SmartAI:willUseGodSalvation(card) if not card then self.room:writeToConsole(debug.traceback()) return false end local good, bad = 0, 0 local wounded_friend = 0 local wounded_enemy = 0 if self.player:hasSkill("jizhi") then good = good + 6 end if (self.player:hasSkill("kongcheng") and self.player:getHandcardNum() == 1) or not self:hasLoseHandcardEffective() then good = good + 5 end for _, friend in ipairs(self.friends) do good = good + 10 * getCardsNum("Nullification", friend, self.player) if self:hasTrickEffective(card, friend, self.player) then if friend:isWounded() then wounded_friend = wounded_friend + 1 good = good + 10 if friend:isLord() then good = good + 10 / math.max(friend:getHp(), 1) end if friend:hasShownSkills(sgs.masochism_skill) then good = good + 5 end if friend:getHp() <= 1 and self:isWeak(friend) then good = good + 5 if friend:isLord() then good = good + 10 end else if friend:isLord() then good = good + 5 end end if self:needToLoseHp(friend, nil, nil, true, true) then good = good - 3 end end end end for _, enemy in ipairs(self.enemies) do bad = bad + 10 * getCardsNum("Nullification", enemy, self.player) if self:hasTrickEffective(card, enemy, self.player) then if enemy:isWounded() then wounded_enemy = wounded_enemy + 1 bad = bad + 10 if enemy:isLord() then bad = bad + 10 / math.max(enemy:getHp(), 1) end if enemy:hasShownSkills(sgs.masochism_skill) then bad = bad + 5 end if enemy:getHp() <= 1 and self:isWeak(enemy) then bad = bad + 5 if enemy:isLord() then bad = bad + 10 end else if enemy:isLord() then bad = bad + 5 end end if self:needToLoseHp(enemy, nil, nil, true, true) then bad = bad - 3 end end end end return good - bad > 5 and wounded_friend > 0 end function SmartAI:useCardGodSalvation(card, use) if self:willUseGodSalvation(card) then use.card = card end end sgs.ai_use_priority.GodSalvation = 1.1 sgs.ai_keep_value.GodSalvation = 3.30 sgs.dynamic_value.benefit.GodSalvation = true sgs.ai_card_intention.GodSalvation = function(self, card, from, tos) local can, first for _, to in ipairs(tos) do if to:isWounded() and not first then first = to can = true elseif first and to:isWounded() and not self:isFriend(first, to) then can = false break end end if can then sgs.updateIntention(from, first, -10) end end function SmartAI:useCardDuel(duel, use) local enemies = self:exclude(self.enemies, duel) local friends = self:exclude(self.friends_noself, duel) duel:setFlags("AI_Using") local n1 = self:getCardsNum("Slash") duel:setFlags("-AI_Using") if self.player:hasSkill("wushuang") then n1 = n1 * 2 end local huatuo = sgs.findPlayerByShownSkillName("jijiu") local targets = {} local canUseDuelTo=function(target) return self:hasTrickEffective(duel, target) and self:damageIsEffective(target,sgs.DamageStruct_Normal) end for _, friend in ipairs(friends) do if friend:hasSkill("jieming") and canUseDuelTo(friend) and self.player:hasSkill("rende") and (huatuo and self:isFriend(huatuo)) then table.insert(targets, friend) end end for _, enemy in ipairs(enemies) do if self.player:hasFlag("duelTo_" .. enemy:objectName()) and canUseDuelTo(enemy) then table.insert(targets, enemy) end end local cmp = function(a, b) local v1 = getCardsNum("Slash", a, self.player) + a:getHp() local v2 = getCardsNum("Slash", b, self.player) + b:getHp() if self:getDamagedEffects(a, self.player) then v1 = v1 + 20 end if self:getDamagedEffects(b, self.player) then v2 = v2 + 20 end if not self:isWeak(a) and a:hasSkill("jianxiong") then v1 = v1 + 10 end if not self:isWeak(b) and b:hasSkill("jianxiong") then v2 = v2 + 10 end if self:needToLoseHp(a) then v1 = v1 + 5 end if self:needToLoseHp(b) then v2 = v2 + 5 end if a:hasShownSkills(sgs.masochism_skill) then v1 = v1 + 5 end if b:hasShownSkills(sgs.masochism_skill) then v2 = v2 + 5 end if not self:isWeak(a) and a:hasSkill("jiang") then v1 = v1 + 5 end if not self:isWeak(b) and b:hasSkill("jiang") then v2 = v2 + 5 end if v1 == v2 then return sgs.getDefenseSlash(a, self) < sgs.getDefenseSlash(b, self) end return v1 < v2 end table.sort(enemies, cmp) for _, enemy in ipairs(enemies) do local useduel local n2 = getCardsNum("Slash", enemy, self.player) if enemy:hasSkill("wushuang") then n2 = n2 * 2 end if sgs.card_lack[enemy:objectName()]["Slash"] == 1 then n2 = 0 end useduel = n1 >= n2 or self:needToLoseHp(self.player, nil, nil, true) or self:getDamagedEffects(self.player, enemy) or (n2 < 1 and sgs.isGoodHp(self.player, self.player)) or ((self:hasSkill("jianxiong") or self.player:getMark("shuangxiong") > 0) and sgs.isGoodHp(self.player, self.player) and n1 + self.player:getHp() >= n2 and self:isWeak(enemy)) if self:objectiveLevel(enemy) > 3 and canUseDuelTo(enemy) and not self:cantbeHurt(enemy) and useduel and sgs.isGoodTarget(enemy, enemies, self) then if not table.contains(targets, enemy) then table.insert(targets, enemy) end end end if #targets > 0 then local godsalvation = self:getCard("GodSalvation") if godsalvation and godsalvation:getId() ~= duel:getId() and self:willUseGodSalvation(godsalvation) then local use_gs = true for _, p in ipairs(targets) do if not p:isWounded() or not self:hasTrickEffective(godsalvation, p, self.player) then break end use_gs = false end if use_gs then use.card = godsalvation return end end local targets_num = 1 + sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_ExtraTarget, self.player, duel) if use.isDummy and use.xiechan then targets_num = 100 end local enemySlash = 0 local setFlag = false use.card = duel for i = 1, #targets, 1 do local n2 = getCardsNum("Slash", targets[i], self.player) if sgs.card_lack[targets[i]:objectName()]["Slash"] == 1 then n2 = 0 end if self:isEnemy(targets[i]) then enemySlash = enemySlash + n2 end if use.to then if i == 1 then use.to:append(targets[i]) end if not setFlag and self.player:getPhase() == sgs.Player_Play and self:isEnemy(targets[i]) then self.player:setFlags("duelTo" .. targets[i]:objectName()) setFlag = true end if use.to:length() == targets_num then return end end end end end sgs.ai_card_intention.Duel = function(self, card, from, tos) if string.find(card:getSkillName(), "lijian") then return end sgs.updateIntentions(from, tos, 80) end sgs.ai_use_value.Duel = 3.7 sgs.ai_use_priority.Duel = 2.9 sgs.ai_keep_value.Duel = 3.42 sgs.dynamic_value.damage_card.Duel = true sgs.ai_skill_cardask["duel-slash"] = function(self, data, pattern, target) if self.player:getPhase()==sgs.Player_Play then return self:getCardId("Slash") end if sgs.ai_skill_cardask.nullfilter(self, data, pattern, target) then return "." end if self:cantbeHurt(target) then return "." end if self:isFriend(target) and target:hasSkill("rende") and self.player:hasSkill("jieming") then return "." end if self:isEnemy(target) and not self:isWeak() and self:getDamagedEffects(self.player, target) then return "." end if self:isFriend(target) then if self:getDamagedEffects(self.player, target) or self:needToLoseHp(self.player, target) then return "." end if self:getDamagedEffects(target, self.player) or self:needToLoseHp(target, self.player) then return self:getCardId("Slash") else return "." end end if (not self:isFriend(target) and self:getCardsNum("Slash") >= getCardsNum("Slash", target, self.player)) or (target:getHp() > 2 and self.player:getHp() <= 1 and self:getCardsNum("Peach") == 0 and not self.player:hasSkill("buqu")) then return self:getCardId("Slash") else return "." end end function SmartAI:useCardExNihilo(card, use) use.card = card end sgs.ai_card_intention.ExNihilo = -80 sgs.ai_keep_value.ExNihilo = 3.9 sgs.ai_use_value.ExNihilo = 10 sgs.ai_use_priority.ExNihilo = 9.3 sgs.dynamic_value.benefit.ExNihilo = true function SmartAI:getDangerousCard(who) local weapon = who:getWeapon() local armor = who:getArmor() local treasure = who:getTreasure() if treasure then if treasure:isKindOf("JadeSeal") then return treasure:getEffectiveId() end end if weapon and (weapon:isKindOf("Crossbow") or weapon:isKindOf("GudingBlade")) then for _, friend in ipairs(self.friends) do if weapon:isKindOf("Crossbow") and who:distanceTo(friend) <= 1 and getCardsNum("Slash", who, self.player) > 0 then return weapon:getEffectiveId() end if weapon:isKindOf("GudingBlade") and who:inMyAttackRange(friend) and friend:isKongcheng() and not friend:hasSkill("kongcheng") and getCardsNum("Slash", who) > 0 then return weapon:getEffectiveId() end end end if (weapon and weapon:isKindOf("Spear") and who:hasSkill("paoxiao") and who:getHandcardNum() >=1 ) then return weapon:getEffectiveId() end if weapon and weapon:isKindOf("Axe") and who:hasSkill("luoyi") then return weapon:getEffectiveId() end if armor and armor:isKindOf("EightDiagram") and who:hasSkill("leiji") then return armor:getEffectiveId() end if (weapon and who:hasSkill("liegong")) then return weapon:getEffectiveId() end if weapon then for _, friend in ipairs(self.friends) do if who:distanceTo(friend) < who:getAttackRange(false) and self:isWeak(friend) and not self:doNotDiscard(who, "e", true) then return weapon:getEffectiveId() end end end end function SmartAI:getValuableCard(who) local weapon = who:getWeapon() local armor = who:getArmor() local offhorse = who:getOffensiveHorse() local defhorse = who:getDefensiveHorse() local treasure = who:getTreasure() self:sort(self.friends, "hp") local friend if #self.friends > 0 then friend = self.friends[1] end if friend and self:isWeak(friend) and who:distanceTo(friend) <= who:getAttackRange(false) and not self:doNotDiscard(who, "e", true) then if weapon and (who:distanceTo(friend) > 1) then return weapon:getEffectiveId() end if offhorse and who:distanceTo(friend) > 1 then return offhorse:getEffectiveId() end end if treasure then if (treasure:isKindOf("WoodenOx") and who:getPile("wooden_ox"):length() > 1) or treasure:isKindOf("JadeSeal") then return treasure:getEffectiveId() end end if defhorse and not self:doNotDiscard(who, "e") and not (self.player:hasWeapon("KylinBow") and self.player:canSlash(who) and self:slashIsEffective(sgs.cloneCard("slash"), who, self.player) and (getCardsNum("Jink", who, self.player) < 1 or sgs.card_lack[who:objectName()].Jink == 1 )) then return defhorse:getEffectiveId() end if armor and self:evaluateArmor(armor, who) > 3 and not self:needToThrowArmor(who) and not self:doNotDiscard(who, "e") then return armor:getEffectiveId() end if offhorse then if who:hasShownSkills("kuanggu|duanbing|qianxi") then return offhorse:getEffectiveId() end end local equips = sgs.QList2Table(who:getEquips()) for _,equip in ipairs(equips) do if who:hasShownSkills("guose") and equip:getSuit() == sgs.Card_Diamond then return equip:getEffectiveId() end if who:hasShownSkills("qixi|duanliang|guidao") and equip:isBlack() then return equip:getEffectiveId() end if who:hasShownSkills("wusheng|jijiu") and equip:isRed() then return equip:getEffectiveId() end if who:hasShownSkills(sgs.need_equip_skill) and not who:hasShownSkills(sgs.lose_equip_skill) then return equip:getEffectiveId() end end if armor and not self:needToThrowArmor(who) and not self:doNotDiscard(who, "e") then return armor:getEffectiveId() end if offhorse and who:getHandcardNum() > 1 then if not self:doNotDiscard(who, "e", true) then for _,friend in ipairs(self.friends) do if who:distanceTo(friend) == who:getAttackRange() and who:getAttackRange() > 1 then return offhorse:getEffectiveId() end end end end if weapon and who:getHandcardNum() > 1 then if not self:doNotDiscard(who, "e", true) then for _,friend in ipairs(self.friends) do if (who:distanceTo(friend) <= who:getAttackRange()) and (who:distanceTo(friend) > 1) then return weapon:getEffectiveId() end end end end end function SmartAI:useCardSnatchOrDismantlement(card, use) local isJixi = card:getSkillName() == "jixi" local isDiscard = (not card:isKindOf("Snatch")) local name = card:objectName() local players = self.room:getOtherPlayers(self.player) local tricks local usecard = false local targets = {} local targets_num = (1 + sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_ExtraTarget, self.player, card)) local addTarget = function(player, cardid) if not table.contains(targets, player:objectName()) then if not usecard then use.card = card usecard = true end table.insert(targets, player:objectName()) if usecard and use.to and use.to:length() < targets_num then use.to:append(player) if not use.isDummy then sgs.Sanguosha:getCard(cardid):setFlags("AIGlobal_SDCardChosen_" .. name) end end if #targets == targets_num then return true end end end players = self:exclude(players, card) for _, player in ipairs(players) do if not player:getJudgingArea():isEmpty() and self:hasTrickEffective(card, player) and ((player:containsTrick("lightning") and self:getFinalRetrial(player) == 2) or #self.enemies == 0) then tricks = player:getCards("j") for _, trick in sgs.qlist(tricks) do if trick:isKindOf("Lightning") and (not isDiscard or self.player:canDiscard(player, trick:getId())) then if addTarget(player, trick:getEffectiveId()) then return end end end end end local enemies = {} if #self.enemies == 0 and self:getOverflow() > 0 then enemies = self:exclude(enemies, card) self:sort(enemies, "defense") enemies = sgs.reverse(enemies) local temp = {} for _, enemy in ipairs(enemies) do if self:hasTrickEffective(card, enemy) then table.insert(temp, enemy) end end enemies = temp else enemies = self:exclude(self.enemies, card) self:sort(enemies, "defense") local temp = {} for _, enemy in ipairs(enemies) do if self:hasTrickEffective(card, enemy) then table.insert(temp, enemy) end end enemies = temp end if self:slashIsAvailable() then local dummyuse = { isDummy = true, to = sgs.SPlayerList() } self:useCardSlash(sgs.cloneCard("slash"), dummyuse) if not dummyuse.to:isEmpty() then local tos = self:exclude(dummyuse.to, card) for _, to in ipairs(tos) do if to:getHandcardNum() == 1 and to:getHp() <= 2 and self:hasLoseHandcardEffective(to) and not to:hasSkill("kongcheng") and (not self:hasEightDiagramEffect(to) or IgnoreArmor(self.player, to)) then if addTarget(to, to:getRandomHandCardId()) then return end end end end end for _, enemy in ipairs(enemies) do if not enemy:isNude() then local dangerous = self:getDangerousCard(enemy) if dangerous and (not isDiscard or self.player:canDiscard(enemy, dangerous)) then if addTarget(enemy, dangerous) then return end end end end self:sort(self.friends_noself, "defense") local friends = self:exclude(self.friends_noself, card) for _, friend in ipairs(friends) do if (friend:containsTrick("indulgence") or friend:containsTrick("supply_shortage")) then local cardchosen tricks = friend:getJudgingArea() for _, trick in sgs.qlist(tricks) do if trick:isKindOf("Indulgence") and (not isDiscard or self.player:canDiscard(friend, trick:getId())) then if friend:getHp() <= friend:getHandcardNum() or friend:isLord() or name == "snatch" then cardchosen = trick:getEffectiveId() break end end if trick:isKindOf("SupplyShortage") and (not isDiscard or self.player:canDiscard(friend, trick:getId())) then cardchosen = trick:getEffectiveId() break end if trick:isKindOf("Indulgence") and (not isDiscard or self.player:canDiscard(friend, trick:getId())) then cardchosen = trick:getEffectiveId() break end end if cardchosen then if addTarget(friend, cardchosen) then return end end end end local hasLion, target for _, friend in ipairs(friends) do if self:needToThrowArmor(friend) and (not isDiscard or self.player:canDiscard(friend, friend:getArmor():getEffectiveId())) then hasLion = true target = friend end end for _, enemy in ipairs(enemies) do if not enemy:isNude() then local valuable = self:getValuableCard(enemy) if valuable and (not isDiscard or self.player:canDiscard(enemy, valuable)) then if addTarget(enemy, valuable) then return end end end end for _, enemy in ipairs(enemies) do local cards = sgs.QList2Table(enemy:getHandcards()) if #cards <= 2 and not enemy:isKongcheng() and not self:doNotDiscard(enemy, "h", true) then for _, cc in ipairs(cards) do if sgs.cardIsVisible(cc, enemy, self.player) and (cc:isKindOf("Peach") or cc:isKindOf("Analeptic")) then if addTarget(enemy, self:getCardRandomly(enemy, "h")) then return end end end end end for _, enemy in ipairs(enemies) do if not enemy:isNude() then if enemy:hasShownSkills("jijiu|qingnang|jieyin") then local cardchosen local equips = { enemy:getDefensiveHorse(), enemy:getArmor(), enemy:getOffensiveHorse(), enemy:getWeapon(),enemy:getTreasure()} for _, equip in ipairs(equips) do if equip and (not enemy:hasSkill("jijiu") or equip:isRed()) and (not isDiscard or self.player:canDiscard(enemy, equip:getEffectiveId())) then cardchosen = equip:getEffectiveId() break end end if not cardchosen and enemy:getDefensiveHorse() and (not isDiscard or self.player:canDiscard(enemy, enemy:getDefensiveHorse():getEffectiveId())) then cardchosen = enemy:getDefensiveHorse():getEffectiveId() end if not cardchosen and enemy:getArmor() and not self:needToThrowArmor(enemy) and (not isDiscard or self.player:canDiscard(enemy, enemy:getArmor():getEffectiveId())) then cardchosen = enemy:getArmor():getEffectiveId() end if not cardchosen and not enemy:isKongcheng() and enemy:getHandcardNum() <= 3 and (not isDiscard or self.player:canDiscard(enemy, "h")) then cardchosen = self:getCardRandomly(enemy, "h") end if cardchosen then if addTarget(enemy, cardchosen) then return end end end end end for _, enemy in ipairs(enemies) do if enemy:hasArmorEffect("EightDiagram") and not self:needToThrowArmor(enemy) and (not isDiscard or self.player:canDiscard(enemy, enemy:getArmor():getEffectiveId())) then addTarget(enemy, enemy:getArmor():getEffectiveId()) end if enemy:getTreasure() and (enemy:getPile("wooden_ox"):length() > 1 or enemy:hasTreasure("JadeSeal")) and (not isDiscard or self.player:canDiscard(enemy, enemy:getTreasure():getEffectiveId())) then addTarget(enemy, enemy:getTreasure():getEffectiveId()) end end for i = 1, 2 + (isJixi and 3 or 0), 1 do for _, enemy in ipairs(enemies) do if not enemy:isNude() and not (self:needKongcheng(enemy) and i <= 2) and not self:doNotDiscard(enemy) then if (enemy:getHandcardNum() == i and sgs.getDefenseSlash(enemy, self) < 6 + (isJixi and 6 or 0) and enemy:getHp() <= 3 + (isJixi and 2 or 0)) then local cardchosen if self.player:distanceTo(enemy) == self.player:getAttackRange() + 1 and enemy:getDefensiveHorse() and not self:doNotDiscard(enemy, "e") and (not isDiscard or self.player:canDiscard(enemy, enemy:getDefensiveHorse():getEffectiveId()))then cardchosen = enemy:getDefensiveHorse():getEffectiveId() elseif enemy:getArmor() and not self:needToThrowArmor(enemy) and not self:doNotDiscard(enemy, "e") and (not isDiscard or self.player:canDiscard(enemy, enemy:getArmor():getEffectiveId()))then cardchosen = enemy:getArmor():getEffectiveId() elseif not isDiscard or self.player:canDiscard(enemy, "h") then cardchosen = self:getCardRandomly(enemy, "h") end if cardchosen then if addTarget(enemy, cardchosen) then return end end end end end end for _, enemy in ipairs(enemies) do if not enemy:isNude() then local valuable = self:getValuableCard(enemy) if valuable and (not isDiscard or self.player:canDiscard(enemy, valuable)) then if addTarget(enemy, valuable) then return end end end end if hasLion and (not isDiscard or self.player:canDiscard(target, target:getArmor():getEffectiveId())) then if addTarget(target, target:getArmor():getEffectiveId()) then return end end for _, enemy in ipairs(enemies) do if not enemy:isKongcheng() and not self:doNotDiscard(enemy, "h") and enemy:hasShownSkills(sgs.cardneed_skill) and (not isDiscard or self.player:canDiscard(enemy, "h")) then if addTarget(enemy, self:getCardRandomly(enemy, "h")) then return end end end for _, enemy in ipairs(enemies) do if enemy:hasEquip() and not self:doNotDiscard(enemy, "e") then local cardchosen if enemy:getDefensiveHorse() and (not isDiscard or self.player:canDiscard(enemy, enemy:getDefensiveHorse():getEffectiveId())) then cardchosen = enemy:getDefensiveHorse():getEffectiveId() elseif enemy:getArmor() and not self:needToThrowArmor(enemy) and (not isDiscard or self.player:canDiscard(enemy, enemy:getArmor():getEffectiveId())) then cardchosen = enemy:getArmor():getEffectiveId() elseif enemy:getOffensiveHorse() and (not isDiscard or self.player:canDiscard(enemy, enemy:getOffensiveHorse():getEffectiveId())) then cardchosen = enemy:getOffensiveHorse():getEffectiveId() elseif enemy:getWeapon() and (not isDiscard or self.player:canDiscard(enemy, enemy:getWeapon():getEffectiveId())) then cardchosen = enemy:getWeapon():getEffectiveId() end if cardchosen then if addTarget(enemy, cardchosen) then return end end end end if name == "snatch" or self:getOverflow() > 0 then for _, enemy in ipairs(enemies) do local equips = enemy:getEquips() if not enemy:isNude() and not self:doNotDiscard(enemy, "he") then local cardchosen if not equips:isEmpty() and not self:doNotDiscard(enemy, "e") then cardchosen = self:getCardRandomly(enemy, "e") else cardchosen = self:getCardRandomly(enemy, "h") end if cardchosen then if addTarget(enemy, cardchosen) then return end end end end end end SmartAI.useCardSnatch = SmartAI.useCardSnatchOrDismantlement sgs.ai_use_value.Snatch = 9 sgs.ai_use_priority.Snatch = 4.3 sgs.ai_keep_value.Snatch = 3.46 sgs.dynamic_value.control_card.Snatch = true SmartAI.useCardDismantlement = SmartAI.useCardSnatchOrDismantlement sgs.ai_use_value.Dismantlement = 5.6 sgs.ai_use_priority.Dismantlement = 4.4 sgs.ai_keep_value.Dismantlement = 3.44 sgs.dynamic_value.control_card.Dismantlement = true sgs.ai_choicemade_filter.cardChosen.snatch = function(self, player, promptlist) local from = findPlayerByObjectName(promptlist[4]) local to = findPlayerByObjectName(promptlist[5]) if from and to then local id = tonumber(promptlist[3]) local place = self.room:getCardPlace(id) local card = sgs.Sanguosha:getCard(id) local intention = 70 if place == sgs.Player_PlaceDelayedTrick then if not card:isKindOf("Disaster") then intention = -intention else intention = 0 end elseif place == sgs.Player_PlaceEquip then if card:isKindOf("Armor") and self:evaluateArmor(card, to) <= -2 then intention = 0 end if card:isKindOf("SilverLion") then if to:getLostHp() > 1 then if to:hasShownSkills(sgs.use_lion_skill) then intention = self:willSkipPlayPhase(to) and -intention or 0 else intention = self:isWeak(to) and -intention or 0 end else intention = 0 end elseif to:hasShownSkills(sgs.lose_equip_skill) then if self:isWeak(to) and (card:isKindOf("DefensiveHorse") or card:isKindOf("Armor")) then intention = math.abs(intention) else intention = 0 end end elseif place == sgs.Player_PlaceHand then if self:needKongcheng(to, true) and to:getHandcardNum() == 1 then intention = 0 end end sgs.updateIntention(from, to, intention) end end sgs.ai_choicemade_filter.cardChosen.dismantlement = sgs.ai_choicemade_filter.cardChosen.snatch function SmartAI:useCardCollateral(card, use) local fromList = sgs.QList2Table(self.room:getOtherPlayers(self.player)) local toList = sgs.QList2Table(self.room:getAlivePlayers()) local cmp = function(a, b) local alevel = self:objectiveLevel(a) local blevel = self:objectiveLevel(b) if alevel ~= blevel then return alevel > blevel end local anum = getCardsNum("Slash", a, self.player) local bnum = getCardsNum("Slash", b, self.player) if anum ~= bnum then return anum < bnum end return a:getHandcardNum() < b:getHandcardNum() end table.sort(fromList, cmp) self:sort(toList, "defense") local needCrossbow = false for _, enemy in ipairs(self.enemies) do if self.player:canSlash(enemy) and self:objectiveLevel(enemy) > 3 and sgs.isGoodTarget(enemy, self.enemies, self) and not self:slashProhibit(nil, enemy) then needCrossbow = true break end end needCrossbow = needCrossbow and self:getCardsNum("Slash") > 2 and not self.player:hasSkill("paoxiao") if needCrossbow then for i = #fromList, 1, -1 do local friend = fromList[i] if friend:getWeapon() and friend:getWeapon():isKindOf("Crossbow") and self:hasTrickEffective(card, friend) then for _, enemy in ipairs(toList) do if friend:canSlash(enemy, nil) and friend:objectName() ~= enemy:objectName() then if not use.isDummy then self.room:setPlayerFlag(self.player, "AI_needCrossbow") end use.card = card if use.to then use.to:append(friend) end if use.to then use.to:append(enemy) end return end end end end end local n = nil local final_enemy = nil for _, enemy in ipairs(fromList) do if self:hasTrickEffective(card, enemy) and not enemy:hasShownSkills(sgs.lose_equip_skill) and not (enemy:hasSkill("weimu") and card:isBlack()) and not enemy:hasSkill("tuntian") and self:objectiveLevel(enemy) >= 0 and enemy:getWeapon() then for _, enemy2 in ipairs(toList) do if enemy:canSlash(enemy2) and self:objectiveLevel(enemy2) > 3 and enemy:objectName() ~= enemy2:objectName() then n = 1 final_enemy = enemy2 break end end if not n then for _, enemy2 in ipairs(toList) do if enemy:canSlash(enemy2) and self:objectiveLevel(enemy2) <=3 and self:objectiveLevel(enemy2) >=0 and enemy:objectName() ~= enemy2:objectName() then n = 1 final_enemy = enemy2 break end end end if not n then for _, friend in ipairs(toList) do if enemy:canSlash(friend) and self:objectiveLevel(friend) < 0 and enemy:objectName() ~= friend:objectName() and (self:needToLoseHp(friend, enemy, true, true) or self:getDamagedEffects(friend, enemy, true)) then n = 1 final_enemy = friend break end end end if not n then for _, friend in ipairs(toList) do if enemy:canSlash(friend) and self:objectiveLevel(friend) < 0 and enemy:objectName() ~= friend:objectName() and (getKnownCard(friend, self.player, "Jink", true, "he") >= 2 or getCardsNum("Slash", enemy, self.player) < 1) then n = 1 final_enemy = friend break end end end if n then use.card = card if use.to then use.to:append(enemy) end if use.to then use.to:append(final_enemy) end return end end n = nil end for _, friend in ipairs(fromList) do if friend:getWeapon() and (getKnownCard(friend, self.player, "Slash", true, "he") > 0 or getCardsNum("Slash", friend, self.player) > 1 and friend:getHandcardNum() >= 4) and self:hasTrickEffective(card, friend) and self:objectiveLevel(friend) < 0 then for _, enemy in ipairs(toList) do if friend:canSlash(enemy, nil) and self:objectiveLevel(enemy) > 3 and friend:objectName() ~= enemy:objectName() and sgs.isGoodTarget(enemy, self.enemies, self) and not self:slashProhibit(nil, enemy) then use.card = card if use.to then use.to:append(friend) end if use.to then use.to:append(enemy) end return end end end end self:sort(toList) for _, friend in ipairs(fromList) do if friend:getWeapon() and friend:hasShownSkills(sgs.lose_equip_skill) and self:hasTrickEffective(card, friend) and self:objectiveLevel(friend) < 0 and not (friend:getWeapon():isKindOf("Crossbow") and getCardsNum("Slash", friend, self.player) > 1) then for _, enemy in ipairs(toList) do if friend:canSlash(enemy, nil) and friend:objectName() ~= enemy:objectName() then use.card = card if use.to then use.to:append(friend) end if use.to then use.to:append(enemy) end return end end end end end sgs.ai_use_value.Collateral = 5.8 sgs.ai_use_priority.Collateral = 2.75 sgs.ai_keep_value.Collateral = 3.36 sgs.ai_card_intention.Collateral = function(self,card, from, tos) assert(#tos == 1) sgs.ai_collateral = true end sgs.dynamic_value.control_card.Collateral = true sgs.ai_skill_cardask["collateral-slash"] = function(self, data, pattern, target2, target, prompt) -- self.player = killer -- target = user -- target2 = victim if self:isFriend(target) and (target:hasFlag("AI_needCrossbow") or (getCardsNum("Slash", target, self.player) >= 2 and self.player:getWeapon():isKindOf("Crossbow"))) then if target:hasFlag("AI_needCrossbow") then self.room:setPlayerFlag(target, "-AI_needCrossbow") end return "." end local slashes = self:getCards("Slash") self:sortByUseValue(slashes) if self:isFriend(target2) and self:needLeiji(target2, self.player) then for _, slash in ipairs(slashes) do if self:slashIsEffective(slash, target2) then return slash:toString() end end end if target2 and (self:getDamagedEffects(target2, self.player, true) or self:needToLoseHp(target2, self.player, true)) then for _, slash in ipairs(slashes) do if self:slashIsEffective(slash, target2) and self:isFriend(target2) then return slash:toString() end if not self:slashIsEffective(slash, target2, self.player, true) and self:isEnemy(target2) then return slash:toString() end end for _, slash in ipairs(slashes) do if not self:getDamagedEffects(target2, self.player, true) and self:isEnemy(target2) then return slash:toString() end end end if target2 and not self.player:hasSkills(sgs.lose_equip_skill) and self:isEnemy(target2) then for _, slash in ipairs(slashes) do if self:slashIsEffective(slash, target2) then return slash:toString() end end end if target2 and not self.player:hasSkills(sgs.lose_equip_skill) and self:isFriend(target2) then for _, slash in ipairs(slashes) do if not self:slashIsEffective(slash, target2) then return slash:toString() end end for _, slash in ipairs(slashes) do if (target2:getHp() > 3 or not self:canHit(target2, self.player, self:hasHeavySlashDamage(self.player, slash, target2))) and self.player:getHandcardNum() > 1 then return slash:toString() end if self:needToLoseHp(target2, self.player) then return slash:toString() end end end return "." end local function hp_subtract_handcard(a,b) local diff1 = a:getHp() - a:getHandcardNum() local diff2 = b:getHp() - b:getHandcardNum() return diff1 < diff2 end function SmartAI:enemiesContainsTrick(EnemyCount) local trick_all, possible_indul_enemy, possible_ss_enemy = 0, 0, 0 local indul_num = self:getCardsNum("Indulgence") local ss_num = self:getCardsNum("SupplyShortage") local enemy_num, temp_enemy = 0 local zhanghe = sgs.findPlayerByShownSkillName("qiaobian") if zhanghe and (not self:isEnemy(zhanghe) or zhanghe:isKongcheng() or not zhanghe:faceUp()) then zhanghe = nil end if self.player:hasSkill("guose") then for _, acard in sgs.qlist(self.player:getCards("he")) do if acard:getSuit() == sgs.Card_Diamond then indul_num = indul_num + 1 end end end if self.player:hasSkill("duanliang") then for _, acard in sgs.qlist(self.player:getCards("he")) do if acard:isBlack() then ss_num = ss_num + 1 end end end for _, enemy in ipairs(self.enemies) do if enemy:containsTrick("indulgence") then if not enemy:hasSkill("keji") and (not zhanghe or self:playerGetRound(enemy) >= self:playerGetRound(zhanghe)) then trick_all = trick_all + 1 if not temp_enemy or temp_enemy:objectName() ~= enemy:objectName() then enemy_num = enemy_num + 1 temp_enemy = enemy end end else possible_indul_enemy = possible_indul_enemy + 1 end if self.player:distanceTo(enemy) == 1 or self.player:hasSkill("duanliang") and self.player:distanceTo(enemy) <= 2 then if enemy:containsTrick("supply_shortage") then if not enemy:hasSkill("shensu") and (not zhanghe or self:playerGetRound(enemy) >= self:playerGetRound(zhanghe)) then trick_all = trick_all + 1 if not temp_enemy or temp_enemy:objectName() ~= enemy:objectName() then enemy_num = enemy_num + 1 temp_enemy = enemy end end else possible_ss_enemy = possible_ss_enemy + 1 end end end indul_num = math.min(possible_indul_enemy, indul_num) ss_num = math.min(possible_ss_enemy, ss_num) if not EnemyCount then return trick_all + indul_num + ss_num else return enemy_num + indul_num + ss_num end end function SmartAI:playerGetRound(player, source) if not player then return self.room:writeToConsole(debug.traceback()) end source = source or self.room:getCurrent() if player:objectName() == source:objectName() then return 0 end local players_num = self.room:alivePlayerCount() local round = (player:getSeat() - source:getSeat()) % players_num return round end function SmartAI:useCardIndulgence(card, use) local enemies = {} if #self.enemies == 0 then if sgs.turncount <= 1 and sgs.isAnjiang(self.player:getNextAlive()) then enemies = self:exclude({self.player:getNextAlive()}, card) end else enemies = self:exclude(self.enemies, card) end local zhanghe = sgs.findPlayerByShownSkillName("qiaobian") local zhanghe_seat = zhanghe and zhanghe:faceUp() and not zhanghe:isKongcheng() and not self:isFriend(zhanghe) and zhanghe:getSeat() or 0 if #enemies == 0 then return end local getvalue = function(enemy) if enemy:hasSkills("jgjiguan_qinglong|jgjiguan_baihu|jgjiguan_zhuque|jgjiguan_xuanwu") then return -101 end if enemy:hasSkills("jgjiguan_bian|jgjiguan_suanni|jgjiguan_chiwen|jgjiguan_yazi") then return -101 end if enemy:hasShownSkill("qianxun") then return -101 end if enemy:hasShownSkill("weimu") and card:isBlack() then return -101 end if enemy:containsTrick("indulgence") then return -101 end if enemy:hasShownSkill("qiaobian") and not enemy:containsTrick("supply_shortage") and not enemy:containsTrick("indulgence") then return -101 end if zhanghe_seat > 0 and (self:playerGetRound(zhanghe) <= self:playerGetRound(enemy) and self:enemiesContainsTrick() <= 1 or not enemy:faceUp()) then return -101 end local value = enemy:getHandcardNum() - enemy:getHp() if enemy:hasShownSkills("lijian|fanjian|dimeng|jijiu|jieyin|zhiheng|rende") then value = value + 10 end if enemy:hasShownSkills("qixi|guose|duanliang|luoshen|jizhi|wansha") then value = value + 5 end if enemy:hasShownSkills("guzheng|duoshi") then value = value + 3 end if self:isWeak(enemy) then value = value + 3 end if enemy:isLord() then value = value + 3 end if self:objectiveLevel(enemy) < 3 then value = value - 10 end if not enemy:faceUp() then value = value - 10 end if enemy:hasShownSkills("keji|shensu") then value = value - enemy:getHandcardNum() end if enemy:hasShownSkills("lirang|guanxing") then value = value - 5 end if enemy:hasShownSkills("tuxi|tiandu") then value = value - 3 end if not sgs.isGoodTarget(enemy, self.enemies, self) then value = value - 1 end if getKnownCard(enemy, self.player, "Dismantlement", true) > 0 then value = value + 2 end value = value + (self.room:alivePlayerCount() - self:playerGetRound(enemy)) / 2 return value end local cmp = function(a,b) return getvalue(a) > getvalue(b) end table.sort(enemies, cmp) local target = enemies[1] if getvalue(target) > -100 then use.card = card if use.to then use.to:append(target) end return end end sgs.ai_use_value.Indulgence = 7.7 sgs.ai_use_priority.Indulgence = 0.5 sgs.ai_card_intention.Indulgence = 120 sgs.ai_keep_value.Indulgence = 3.5 sgs.dynamic_value.control_usecard.Indulgence = true function SmartAI:willUseLightning(card) if not card then self.room:writeToConsole(debug.traceback()) return false end if self.player:containsTrick("lightning") then return end if self.player:hasSkill("weimu") and card:isBlack() then local shouldUse = true for _, p in sgs.qlist(self.room:getOtherPlayers(self.player)) do if self:evaluateKingdom(p) == "unknown" then shouldUse = false break end if self:evaluateKingdom(p) == self.player:getKingdom() then shouldUse = false break end end if shouldUse then return true end end --if sgs.Sanguosha:isProhibited(self.player, self.player, card) then return end local function hasDangerousFriend() local hashy = false for _, aplayer in ipairs(self.enemies) do if aplayer:hasSkill("hongyan") then hashy = true break end end for _, aplayer in ipairs(self.enemies) do if aplayer:hasSkill("guanxing") and self:isFriend(aplayer:getNextAlive()) then return true end end return false end if self:getFinalRetrial(self.player) == 2 then return elseif self:getFinalRetrial(self.player) == 1 then return true elseif not hasDangerousFriend() then if self.player:hasSkills("guanxing|kongcheng") and self.player:isLastHandCard(card) == 1 then return true end local players = self.room:getAllPlayers() players = sgs.QList2Table(players) local friends = 0 local enemies = 0 for _, player in ipairs(players) do if self:objectiveLevel(player) >= 4 and not player:hasSkill("hongyan") and not (player:hasSkill("weimu") and card:isBlack()) then enemies = enemies + 1 elseif self:isFriend(player) and not player:hasSkill("hongyan") and not (player:hasSkill("weimu") and card:isBlack()) then friends = friends + 1 end end local ratio if friends == 0 then ratio = 999 else ratio = enemies/friends end if ratio > 1.5 then return true end end end function SmartAI:useCardLightning(card, use) if self:willUseLightning(card) then use.card = card end end sgs.ai_use_priority.Lightning = 0 sgs.dynamic_value.lucky_chance.Lightning = true sgs.ai_keep_value.Lightning = -1 sgs.ai_skill_askforag.amazing_grace = function(self, card_ids) local NextPlayerCanUse, NextPlayerisEnemy local NextPlayer = self.player:getNextAlive() if sgs.turncount > 1 and not self:willSkipPlayPhase(NextPlayer) then if self:isFriend(NextPlayer) then NextPlayerCanUse = true else NextPlayerisEnemy = true end end local cards = {} local trickcard = {} for _, card_id in ipairs(card_ids) do local acard = sgs.Sanguosha:getCard(card_id) table.insert(cards, acard) if acard:isKindOf("TrickCard") then table.insert(trickcard , acard) end end local nextfriend_num = 0 local aplayer = self.player:getNextAlive() for i =1, self.player:aliveCount() do if self:isFriend(aplayer) then aplayer = aplayer:getNextAlive() nextfriend_num = nextfriend_num + 1 else break end end local SelfisCurrent if self.room:getCurrent():objectName() == self.player:objectName() then SelfisCurrent = true end --------------- local friendneedpeach, peach local peachnum, jinknum = 0, 0 if NextPlayerCanUse then if (not self.player:isWounded() and NextPlayer:isWounded()) or (self.player:getLostHp() < self:getCardsNum("Peach")) or (not SelfisCurrent and self:willSkipPlayPhase() and self.player:getHandcardNum() + 2 > self.player:getMaxCards()) then friendneedpeach = true end end for _, card in ipairs(cards) do if isCard("Peach", card, self.player) then peach = card:getEffectiveId() peachnum = peachnum + 1 end if card:isKindOf("Jink") then jinknum = jinknum + 1 end end if (not friendneedpeach and peach) or peachnum > 1 then return peach end local exnihilo, jink, analeptic, nullification, snatch, dismantlement, befriendattacking for _, card in ipairs(cards) do if isCard("ExNihilo", card, self.player) then if not NextPlayerCanUse or (not self:willSkipPlayPhase() and (self.player:hasSkills("jizhi|zhiheng|rende") or not NextPlayer:hasShownSkills("jizhi|zhiheng|rende"))) then exnihilo = card:getEffectiveId() end elseif isCard("Jink", card, self.player) then jink = card:getEffectiveId() elseif isCard("Analeptic", card, self.player) then analeptic = card:getEffectiveId() elseif isCard("Nullification", card, self.player) then nullification = card:getEffectiveId() elseif isCard("Snatch", card, self.player) then snatch = card elseif isCard("Dismantlement", card, self.player) then dismantlement = card elseif isCard("BefriendAttacking", card, self.player) then befriendattacking = card end end for _, target in sgs.qlist(self.room:getAlivePlayers()) do if self:willSkipPlayPhase(target) or self:willSkipDrawPhase(target) then if nullification then return nullification elseif self:isFriend(target) and snatch and self:hasTrickEffective(snatch, target, self.player) and not self:willSkipPlayPhase() and self.player:distanceTo(target) == 1 then return snatch:getEffectiveId() elseif self:isFriend(target) and dismantlement and self:hasTrickEffective(dismantlement, target, self.player) and not self:willSkipPlayPhase() and self.player:objectName() ~= target:objectName() then return dismantlement:getEffectiveId() end end end if SelfisCurrent then if exnihilo then return exnihilo end if befriendattacking then for _, p in sgs.qlist(self.room:getOtherPlayers(self.player)) do if p:hasShownOneGeneral() and not self.player:isFriendWith(p) then return befriendattacking end end end if (jink or analeptic) and (self:getCardsNum("Jink") == 0 or (self:isWeak() and self:getOverflow() <= 0)) then return jink or analeptic end else local CP = self.room:getCurrent() local possible_attack = 0 for _, enemy in ipairs(self.enemies) do if enemy:inMyAttackRange(self.player) and self:playerGetRound(CP, enemy) < self:playerGetRound(CP, self.player) then possible_attack = possible_attack + 1 end end if possible_attack > self:getCardsNum("Jink") and self:getCardsNum("Jink") <= 2 and sgs.getDefenseSlash(self.player, self) <= 2 then if jink or analeptic or exnihilo then return jink or analeptic or exnihilo end else if exnihilo then return exnihilo end if befriendattacking then for _, p in sgs.qlist(self.room:getOtherPlayers(self.player)) do if p:hasShownOneGeneral() and not self.player:isFriendWith(p) then return befriendattacking end end end end end if nullification and (self:getCardsNum("Nullification") < 2 or not NextPlayerCanUse) then return nullification end if jinknum == 1 and jink and self:isEnemy(NextPlayer) and (NextPlayer:isKongcheng() or sgs.card_lack[NextPlayer:objectName()]["Jink"] == 1) then return jink end self:sortByUseValue(cards) for _, card in ipairs(cards) do for _, skill in sgs.qlist(self.player:getVisibleSkillList()) do local callback = sgs.ai_cardneed[skill:objectName()] if type(callback) == "function" and callback(self.player, card, self) then return card:getEffectiveId() end end end local eightdiagram, silverlion, vine, renwang, ironarmor, DefHorse, OffHorse, jadeseal local weapon, crossbow, halberd, double, qinggang, axe, gudingdao for _, card in ipairs(cards) do if card:isKindOf("EightDiagram") then eightdiagram = card:getEffectiveId() elseif card:isKindOf("SilverLion") then silverlion = card:getEffectiveId() elseif card:isKindOf("Vine") then vine = card:getEffectiveId() elseif card:isKindOf("RenwangShield") then renwang = card:getEffectiveId() elseif card:isKindOf("IronArmor") then ironarmor = card:getEffectiveId() elseif card:isKindOf("DefensiveHorse") and not self:getSameEquip(card) then DefHorse = card:getEffectiveId() elseif card:isKindOf("OffensiveHorse") and not self:getSameEquip(card) then OffHorse = card:getEffectiveId() elseif card:isKindOf("Crossbow") then crossbow = card elseif card:isKindOf("DoubleSword") then double = card:getEffectiveId() elseif card:isKindOf("QinggangSword") then qinggang = card:getEffectiveId() elseif card:isKindOf("Axe") then axe = card:getEffectiveId() elseif card:isKindOf("GudingBlade") then gudingdao = card:getEffectiveId() elseif card:isKindOf("Halberd") then halberd = card:getEffectiveId() elseif card:isKindOf("JadeSeal") then jadeseal = card:getEffectiveId() end if not weapon and card:isKindOf("Weapon") then weapon = card:getEffectiveId() end end if eightdiagram then if not self.player:hasSkill("bazhen") and self.player:hasSkills("tiandu|leiji|hongyan") and not self:getSameEquip(card) then return eightdiagram end if NextPlayerisEnemy and NextPlayer:hasShownSkills("tiandu|leiji|hongyan") and not self:getSameEquip(card, NextPlayer) then return eightdiagram end end if silverlion then local lightning, canRetrial for _, aplayer in sgs.qlist(self.room:getOtherPlayers(self.player)) do if aplayer:hasSkill("leiji") and self:isEnemy(aplayer) then return silverlion end if aplayer:containsTrick("lightning") then lightning = true end if aplayer:hasShownSkills("guicai|guidao") and self:isEnemy(aplayer) then canRetrial = true end end if lightning and canRetrial then return silverlion end if self.player:isChained() then for _, friend in ipairs(self.friends) do if friend:hasArmorEffect("Vine") and friend:isChained() then return silverlion end end end if self.player:isWounded() then return silverlion end end if vine then if sgs.ai_armor_value.Vine(self.player, self) > 0 and self.room:alivePlayerCount() <= 3 then return vine end end if renwang then if sgs.ai_armor_value.RenwangShield(self.player, self) > 0 and self:getCardsNum("Jink") == 0 then return renwang end end if ironarmor then for _, enemy in ipairs(self.enemies) do if enemy:hasShownSkill("huoji") then return ironarmor end if getCardsNum("FireAttack", enemy, self.player) > 0 then return ironarmor end if getCardsNum("FireSlash", enemy, self.player) > 0 then return ironarmor end if enemy:getFormation():contains(self.player) and getCardsNum("BurningCamps", enemy, self.player) > 0 then return ironarmor end end end if DefHorse and (not self.player:hasSkill("leiji") or self:getCardsNum("Jink") == 0) then local before_num, after_num = 0, 0 for _, enemy in ipairs(self.enemies) do if enemy:canSlash(self.player, nil, true) then before_num = before_num + 1 end if enemy:canSlash(self.player, nil, true, 1) then after_num = after_num + 1 end end if before_num > after_num and (self:isWeak() or self:getCardsNum("Jink") == 0) then return DefHorse end end if jadeseal then for _, friend in ipairs(self.friends) do if not (friend:getTreasure() and friend:getPile("wooden_ox"):length() > 1) then return jadeseal end end end if analeptic then local slashes = self:getCards("Slash") for _, enemy in ipairs(self.enemies) do local hit_num = 0 for _, slash in ipairs(slashes) do if self:slashIsEffective(slash, enemy) and self.player:canSlash(enemy, slash) and self:slashIsAvailable() then hit_num = hit_num + 1 if getCardsNum("Jink", enemy, self.player) < 1 or enemy:isKongcheng() or self:canLiegong(enemy, self.player) or self.player:hasSkills("tieqi|wushuang|qianxi") or (self.player:hasWeapon("Axe") or self:getCardsNum("Axe") > 0) and self.player:getCards("he"):length() > 4 then return analeptic end end end if self:hasCrossbowEffect(self.player) and hit_num >= 2 then return analeptic end end end if weapon and (self:getCardsNum("Slash") > 0 and self:slashIsAvailable() or not SelfisCurrent) then local current_range = (self.player:getWeapon() and sgs.weapon_range[self.player:getWeapon():getClassName()]) or 1 local nosuit_slash = sgs.cloneCard("slash", sgs.Card_NoSuit, 0) local slash = SelfisCurrent and self:getCard("Slash") or nosuit_slash self:sort(self.enemies, "defense") if crossbow then if #self:getCards("Slash") > 1 or self.player:hasSkills("kurou|keji") or (self.player:hasSkills("luoshen|guzheng") and not SelfisCurrent and self.room:alivePlayerCount() >= 4) then return crossbow:getEffectiveId() end if self.player:hasSkill("rende") then for _, friend in ipairs(self.friends_noself) do if getCardsNum("Slash", friend, self.player) > 1 then return crossbow:getEffectiveId() end end end if self:isEnemy(NextPlayer) then local CanSave, huanggai, zhenji for _, enemy in ipairs(self.enemies) do if enemy:hasShownSkill("jijiu") and getKnownCard(enemy, self.player, "red", nil, "he") > 1 then CanSave = true end if enemy:hasShownSkill("kurou") then huanggai = enemy end if enemy:hasShownSkill("keji") then return crossbow:getEffectiveId() end if enemy:hasShownSkills("luoshen|guzheng") then return crossbow:getEffectiveId() end end if huanggai then if huanggai:getHp() > 2 then return crossbow:getEffectiveId() end if CanSave then return crossbow:getEffectiveId() end end if getCardsNum("Slash", NextPlayer, self.player) >= 3 and NextPlayerisEnemy then return crossbow:getEffectiveId() end end end if halberd then --@todo end if gudingdao then local range_fix = current_range - 2 for _, enemy in ipairs(self.enemies) do if self.player:canSlash(enemy, slash, true, range_fix) and enemy:isKongcheng() and (not SelfisCurrent or (self:getCardsNum("Dismantlement") > 0 or (self:getCardsNum("Snatch") > 0 and self.player:distanceTo(enemy) == 1))) then return gudingdao end end end if axe then local range_fix = current_range - 3 local FFFslash = self:getCard("FireSlash") for _, enemy in ipairs(self.enemies) do if (enemy:hasArmorEffect("Vine") or enemy:getMark("@gale") > 0) and FFFslash and self:slashIsEffective(FFFslash, enemy) and self.player:getCardCount(true) >= 3 and self.player:canSlash(enemy, FFFslash, true, range_fix) then return axe elseif self:getCardsNum("Analeptic") > 0 and self.player:getCardCount(true) >= 4 and self:slashIsEffective(slash, enemy) and self.player:canSlash(enemy, slash, true, range_fix) then return axe end end end if double then local range_fix = current_range - 2 for _, enemy in ipairs(self.enemies) do if self.player:getGender() ~= enemy:getGender() and self.player:canSlash(enemy, nil, true, range_fix) then return double end end end if qinggang then local range_fix = current_range - 2 for _, enemy in ipairs(self.enemies) do if self.player:canSlash(enemy, slash, true, range_fix) and self:slashIsEffective(slash, enemy, self.player, true) then return qinggang end end end end local classNames = { "Snatch", "Dismantlement", "Indulgence", "SupplyShortage", "Collateral", "Duel", "Drowning", "ArcheryAttack", "SavageAssault", "FireAttack", "GodSalvation", "Lightning" } local className2objectName = { Snatch = "snatch", Dismantlement = "dismantlement", Indulgence = "indulgence", SupplyShortage = "supply_shortage", Collateral = "collateral", Duel = "duel", Drowning = "drowning", ArcheryAttack = "archery_attack", SavageAssault = "savage_assault", FireAttack = "fire_attack", GodSalvation = "god_salvation", Lightning = "lightning" } local new_enemies = {} if #self.enemies > 0 then new_enemies = self.enemies else for _, aplayer in sgs.qlist(self.room:getOtherPlayers(self.player)) do if not string.find(self:evaluateKingdom(aplayer), self.player:getKingdom()) then table.insert(new_enemies, aplayer) end end end if not self:willSkipPlayPhase() or not NextPlayerCanUse then for _, className in ipairs(classNames) do for _, card in ipairs(cards) do if isCard(className, card, self.player) then local card_x = className ~= card:getClassName() and sgs.cloneCard(className2objectName[className], card:getSuit(), card:getNumber()) or card self.enemies = new_enemies local dummy_use = { isDummy = true } self:useTrickCard(card_x, dummy_use) self:updatePlayers(false) if dummy_use.card then return card end end end end elseif #trickcard > nextfriend_num + 1 and NextPlayerCanUse then for i = #classNames, 1, -1 do className = classNames[i] for _, card in ipairs(cards) do if isCard(className, card, self.player) then local card_x = className ~= card:getClassName() and sgs.cloneCard(className2objectName[className], card:getSuit(), card:getNumber()) or card self.enemies = new_enemies local dummy_use = { isDummy = true } self:useTrickCard(card_x, dummy_use) self:updatePlayers(false) if dummy_use.card then return card end end end end end if weapon and not self.player:getWeapon() and self:getCardsNum("Slash") > 0 and (self:slashIsAvailable() or not SelfisCurrent) then local inAttackRange for _, enemy in ipairs(self.enemies) do if self.player:inMyAttackRange(enemy) then inAttackRange = true break end end if not inAttackRange then return weapon end end if eightdiagram or silverlion or vine or renwang or ironarmor then return renwang or eightdiagram or ironarmor or silverlion or vine end self:sortByCardNeed(cards, true) for _, card in ipairs(cards) do if not card:isKindOf("TrickCard") and not card:isKindOf("Peach") then return card:getEffectiveId() end end return cards[1]:getEffectiveId() end function SmartAI:useCardAwaitExhausted(AwaitExhausted, use) if not AwaitExhausted:isAvailable(self.player) then return end use.card = AwaitExhausted return end sgs.ai_use_priority.AwaitExhausted = 2.8 sgs.ai_use_value.AwaitExhausted = 4.9 sgs.ai_keep_value.AwaitExhausted = 1 sgs.ai_card_intention.AwaitExhausted = function(self, card, from, tos) for _, to in ipairs(tos) do sgs.updateIntention(from, to, -50) end end sgs.ai_nullification.AwaitExhausted = function(self, card, from, to, positive) if positive then if self:isEnemy(to) and self:evaluateKingdom(to) ~= "unknown" then if self:getOverflow() > 0 or self:getCardsNum("Nullification") > 1 then return true end if to:hasShownSkills(sgs.lose_equip_skill) and to:getEquips():length() > 0 then return true end if to:getArmor() and self:needToThrowArmor(to) then return true end end else if self:isFriend(to) and (self:getOverflow() > 0 or self:getCardsNum("Nullification") > 1) then return true end end return end function SmartAI:useCardBefriendAttacking(BefriendAttacking, use) if not BefriendAttacking:isAvailable(self.player) then return end local targets = sgs.PlayerList() local players = sgs.QList2Table(self.room:getOtherPlayers(self.player)) self:sort(players) for _, to_select in ipairs(players) do if self:isFriend(to_select) and BefriendAttacking:targetFilter(targets, to_select, self.player) and not targets:contains(to_select) and self:hasTrickEffective(BefriendAttacking, to_select, self.player) then targets:append(to_select) if use.to then use.to:append(to_select) end end end if targets:isEmpty() then for _, to_select in ipairs(players) do if BefriendAttacking:targetFilter(targets, to_select, self.player) and not targets:contains(to_select) and self:hasTrickEffective(BefriendAttacking, to_select, self.player) then targets:append(to_select) if use.to then use.to:append(to_select) end end end end if not targets:isEmpty() then use.card = BefriendAttacking return end end sgs.ai_use_priority.BefriendAttacking = 9.28 sgs.ai_use_value.BefriendAttacking = 8.9 sgs.ai_keep_value.BefriendAttacking = 3.88 sgs.ai_nullification.BefriendAttacking = function(self, card, from, to, positive) if positive then if not self:isFriend(to) and self:isEnemy(from) and self:isWeak(from) then return true end else if self:isFriend(from) then return true end end return end function SmartAI:useCardKnownBoth(KnownBoth, use) self.knownboth_choice = {} if not KnownBoth:isAvailable(self.player) then return false end local targets = sgs.PlayerList() local total_num = 1 + sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_ExtraTarget, self.player, KnownBoth) for _, player in sgs.qlist(self.room:getOtherPlayers(self.player)) do if KnownBoth:targetFilter(targets, player, self.player) and sgs.isAnjiang(player) and not targets:contains(player) and player:getMark(("KnownBoth_%s_%s"):format(self.player:objectName(), player:objectName())) == 0 and self:hasTrickEffective(KnownBoth, player, self.player) then use.card = KnownBoth targets:append(player) if use.to then use.to:append(player) end self.knownboth_choice[player:objectName()] = "head_general" end end if total_num > targets:length() then self:sort(self.enemies, "handcard") sgs.reverse(self.enemies) for _, enemy in ipairs(self.enemies) do if KnownBoth:targetFilter(targets, enemy, self.player) and enemy:getHandcardNum() - self:getKnownNum(enemy, self.player) > 3 and not targets:contains(enemy) and self:hasTrickEffective(KnownBoth, enemy, self.player) then use.card = KnownBoth targets:append(enemy) if use.to then use.to:append(enemy) end self.knownboth_choice[enemy:objectName()] = "handcards" end end end if total_num > targets:length() and not targets:isEmpty() then self:sort(self.friends_noself, "handcard") self.friends_noself = sgs.reverse(self.friends_noself) for _, friend in ipairs(self.friends_noself) do if self:getKnownNum(friend, self.player) ~= friend:getHandcardNum() and card:targetFilter(targets, friend, self.player) and not targets:contains(friend) and self:hasTrickEffective(KnownBoth, friend, self.player) then targets:append(friend) if use.to then use.to:append(friend) end self.knownboth_choice[friend:objectName()] = "handcards" end end end if not use.card then targets = sgs.PlayerList() local canRecast = KnownBoth:targetsFeasible(targets, self.player) if canRecast then use.card = KnownBoth if use.to then use.to = sgs.SPlayerList() end end end end sgs.ai_skill_choice.known_both = function(self, choices, data) local target = data:toPlayer() if target and self.knownboth_choice and self.knownboth_choice[target:objectName()] then return self.knownboth_choice[target:objectName()] end return "handcards" end sgs.ai_use_priority.KnownBoth = 9.1 sgs.ai_use_value.KnownBoth = 5.5 sgs.ai_keep_value.KnownBoth = 3.33 sgs.ai_nullification.KnownBoth = function(self, card, from, to, positive) -- todo return false end sgs.ai_choicemade_filter.skillChoice.known_both = function(self, from, promptlist) local choice = promptlist[#promptlist] if choice ~= "handcards" then for _, to in sgs.qlist(self.room:getOtherPlayers(from)) do if to:hasFlag("KnownBothTarget") then to:setMark(("KnownBoth_%s_%s"):format(from:objectName(), to:objectName()), 1) break end end end end sgs.ai_skill_use["@@Triblade"] = function(self, prompt) local damage = self.room:getTag("CurrentDamageStruct"):toDamage() if type(damage) ~= "userdata" then return "." end local targets = sgs.SPlayerList() for _, p in sgs.qlist(self.room:getOtherPlayers(damage.to)) do if damage.to:distanceTo(p) == 1 then targets:append(p) end end if targets:isEmpty() then return "." end local id local cards = sgs.QList2Table(self.player:getHandcards()) self:sortByKeepValue(cards) for _, c in ipairs(cards) do if not self.player:isCardLimited(c, sgs.Card_MethodDiscard) and not self:isValuableCard(c) then id = c:getEffectiveId() break end end if not id then return "." end for _, target in sgs.qlist(targets) do if self:isEnemy(target) and self:damageIsEffective(target, nil, self.player) and not self:getDamagedEffects(target, self.player) and not self:needToLoseHp(target, self.player) then return "@TribladeSkillCard=" .. id .. "&tribladeskill->" .. target:objectName() end end for _, target in sgs.qlist(targets) do if self:isFriend(target) and self:damageIsEffective(target, nil, self.player) and (self:getDamagedEffects(target, self.player) or self:needToLoseHp(target, self.player, nil, true)) then return "@TribladeSkillCard=" .. id .. "&tribladeskill->" .. target:objectName() end end return "." end function sgs.ai_slash_weaponfilter.Triblade(self, to, player) if player:distanceTo(to) > math.max(sgs.weapon_range.Triblade, player:getAttackRange()) then return end return sgs.card_lack[to:objectName()]["Jink"] == 1 or getCardsNum("Jink", to, self.player) == 0 end function sgs.ai_weapon_value.Triblade(self, enemy, player) if not enemy then return 1 end if enemy and player:getHandcardNum() > 2 then return math.min(3.8, player:getHandcardNum() - 1) end end sgs.ai_use_priority.Triblade = 2.673
gpl-3.0
teahouse/FWServer
skynet/examples/login/client.lua
67
3950
package.cpath = "luaclib/?.so" local socket = require "clientsocket" local crypt = require "crypt" if _VERSION ~= "Lua 5.3" then error "Use lua 5.3" end local fd = assert(socket.connect("127.0.0.1", 8001)) local function writeline(fd, text) socket.send(fd, text .. "\n") end local function unpack_line(text) local from = text:find("\n", 1, true) if from then return text:sub(1, from-1), text:sub(from+1) end return nil, text end local last = "" local function unpack_f(f) local function try_recv(fd, last) local result result, last = f(last) if result then return result, last end local r = socket.recv(fd) if not r then return nil, last end if r == "" then error "Server closed" end return f(last .. r) end return function() while true do local result result, last = try_recv(fd, last) if result then return result end socket.usleep(100) end end end local readline = unpack_f(unpack_line) local challenge = crypt.base64decode(readline()) local clientkey = crypt.randomkey() writeline(fd, crypt.base64encode(crypt.dhexchange(clientkey))) local secret = crypt.dhsecret(crypt.base64decode(readline()), clientkey) print("sceret is ", crypt.hexencode(secret)) local hmac = crypt.hmac64(challenge, secret) writeline(fd, crypt.base64encode(hmac)) local token = { server = "sample", user = "hello", pass = "password", } local function encode_token(token) return string.format("%s@%s:%s", crypt.base64encode(token.user), crypt.base64encode(token.server), crypt.base64encode(token.pass)) end local etoken = crypt.desencode(secret, encode_token(token)) local b = crypt.base64encode(etoken) writeline(fd, crypt.base64encode(etoken)) local result = readline() print(result) local code = tonumber(string.sub(result, 1, 3)) assert(code == 200) socket.close(fd) local subid = crypt.base64decode(string.sub(result, 5)) print("login ok, subid=", subid) ----- connect to game server local function send_request(v, session) local size = #v + 4 local package = string.pack(">I2", size)..v..string.pack(">I4", session) socket.send(fd, package) return v, session end local function recv_response(v) local size = #v - 5 local content, ok, session = string.unpack("c"..tostring(size).."B>I4", v) return ok ~=0 , content, session end local function unpack_package(text) local size = #text if size < 2 then return nil, text end local s = text:byte(1) * 256 + text:byte(2) if size < s+2 then return nil, text end return text:sub(3,2+s), text:sub(3+s) end local readpackage = unpack_f(unpack_package) local function send_package(fd, pack) local package = string.pack(">s2", pack) socket.send(fd, package) end local text = "echo" local index = 1 print("connect") fd = assert(socket.connect("127.0.0.1", 8888)) last = "" local handshake = string.format("%s@%s#%s:%d", crypt.base64encode(token.user), crypt.base64encode(token.server),crypt.base64encode(subid) , index) local hmac = crypt.hmac64(crypt.hashkey(handshake), secret) send_package(fd, handshake .. ":" .. crypt.base64encode(hmac)) print(readpackage()) print("===>",send_request(text,0)) -- don't recv response -- print("<===",recv_response(readpackage())) print("disconnect") socket.close(fd) index = index + 1 print("connect again") fd = assert(socket.connect("127.0.0.1", 8888)) last = "" local handshake = string.format("%s@%s#%s:%d", crypt.base64encode(token.user), crypt.base64encode(token.server),crypt.base64encode(subid) , index) local hmac = crypt.hmac64(crypt.hashkey(handshake), secret) send_package(fd, handshake .. ":" .. crypt.base64encode(hmac)) print(readpackage()) print("===>",send_request("fake",0)) -- request again (use last session 0, so the request message is fake) print("===>",send_request("again",1)) -- request again (use new session) print("<===",recv_response(readpackage())) print("<===",recv_response(readpackage())) print("disconnect") socket.close(fd)
mit
SegFault22/res
core/material.lua
1
1260
-- Code handling materials is found here res_material_types = {} res_materials = {} function res.add_material_type(id,name) table.insert(res_material_types,{id,name}) res.log("verbose","Added material class \""..name.."\" with id: "..id) end function res.add_material(type,id,name,strength,weight) if res.list_find(res_material_types,type) == true then do table.insert(res_materials,{type,id,name,strength,weight}) res.log("verbose","Added material of type: "..type.." with id: "..id) end else res.log("error","Attempt to register material of an unrecognized type or with invalid or nonexistent properties") end end function res.add_material_items(materialid,itemslist) for _, row in ipairs(itemslist) do local itemid = row[1] local id = "res:"..itemid.."_"..materialid local properties = { description = res.get_material_name(materialid).." "..res.get_itemtype_name(itemid), inventory_image = "res_"..itemid.."_"..materialid..".png", on_place_on_ground = minetest.craftitem_place_item, } res.add_item("item",id,properties) end end function res.add_material_items_table(table) for _, row in ipairs(table) do local materialid = row[1] local itemslist = row[2] res.add_material_items(materialid,itemslist) end end
gpl-2.0
hb9cwp/snabbswitch
lib/ljsyscall/test/linux-constants.lua
18
9330
-- test against clean set of kernel headers, standard set so cross platform. --[[ luajit test/linux-constants.lua x64 > ./obj/c.c && cc -U__i386__ -DBITS_PER_LONG=64 -I./include/linux-kernel-headers/x86_64/include -o ./obj/c ./obj/c.c && ./obj/c luajit test/linux-constants.lua x86 > ./obj/c.c && cc -D__i386__ -DBITS_PER_LONG=32 -I./include/linux-kernel-headers/i386/include -o ./obj/c ./obj/c.c && ./obj/c luajit test/linux-constants.lua arm > ./obj/c.c && cc -D__ARM_EABI__ -DBITS_PER_LONG=32 -I./include/linux-kernel-headers/arm/include -o ./obj/c ./obj/c.c && ./obj/c luajit test/linux-constants.lua ppc > ./obj/c.c && cc -I./include/linux-kernel-headers/powerpc/include -o ./obj/c ./obj/c.c && ./obj/c luajit test/linux-constants.lua mips > ./obj/c.c && cc -D__MIPSEL__ -D_MIPS_SIM=_MIPS_SIM_ABI32 -DCONFIG_32BIT -DBITS_PER_LONG=32 -D__LITTLE_ENDIAN_BITFIELD -D__LITTLE_ENDIAN -DCONFIG_CPU_LITTLE_ENDIAN -I./include/linux-kernel-headers/mips/include -o ./obj/c ./obj/c.c && ./obj/c ]] -- TODO 32 bit warnings about signed ranges local abi = require "syscall.abi" if arg[1] then -- fake arch abi.arch = arg[1] if abi.arch == "x64" then abi.abi32, abi.abi64 = false, true else abi.abi32, abi.abi64 = true, false end if abi.arch == "mips" then abi.mipsabi = "o32" end end local function fixup_constants(abi, c) -- we only use one set if abi.abi64 then c.F.GETLK64 = nil c.F.SETLK64 = nil c.F.SETLKW64 = nil else c.F.GETLK = nil c.F.SETLK = nil c.F.SETLKW = nil end -- internal use c.syscall = nil c.errornames = nil c.OMQATTR = nil c.EALIAS = nil -- misleading, Musl has higher than Linux c.HOST_NAME_MAX = nil -- fake constants c.MS.RO = nil c.MS.RW = nil c.MS.SECLABEL = nil c.IFF.ALL = nil c.IFF.NONE = nil c.W.ALL = nil c.MAP.ANON = nil -- MAP.ANONYMOUS only -- oddities to fix c.IFLA_VF_INFO.INFO = nil c.IFLA_VF_PORT.PORT = nil -- umount is odd c.MNT = {} c.MNT.FORCE = c.UMOUNT.FORCE c.MNT.DETACH = c.UMOUNT.DETACH c.MNT.EXPIRE = c.UMOUNT.EXPIRE c.UMOUNT.FORCE = nil c.UMOUNT.DETACH = nil c.UMOUNT.EXPIRE = nil if abi.abi64 then c.O.LARGEFILE = nil end -- renamed constants c.OPIPE = nil -- we renamed these for namespacing reasons TODO can just set in nm table for k, v in pairs(c.IFREQ) do c.IFF[k] = v end c.IFREQ = nil c.__WNOTHREAD = c.W.NOTHREAD c.__WALL = c.W.ALL c.__WCLONE = c.W.CLONE c.W.NOTHREAD, c.W.ALL, c.W.CLONE = nil, nil, nil -- not part of kernel ABI I think - TODO check and maybe remove from ljsyscall c.SOMAXCONN = nil c.E.NOTSUP = nil c.SIG.CLD = nil -- extra friendly names c.WAIT.ANY = nil c.WAIT.MYPGRP = nil -- surely part of ABI? not defined in kernel ones we have though c.AF = nil c.MSG = nil c.SOCK = nil c.SOL = nil c.SHUT = nil c.OK = nil c.DT = nil -- part of man(3) API so we can use any value we like?? - TODO move to common code? is this true in all OSs c.LOCKF = nil c.STD = nil c.SCM = nil c.TCSA = nil c.TCFLUSH = nil c.TCFLOW = nil c.EXIT = nil -- not defined? c.UTIME = nil c.REG = nil c.PC = nil -- neither _PC or _POSIX_ defined for capabilities -- pointer type c.SIGACT = nil -- epoll uses POLL values internally? c.EPOLL.MSG = nil c.EPOLL.WRBAND = nil c.EPOLL.RDHUP = nil c.EPOLL.WRNORM = nil c.EPOLL.RDNORM = nil c.EPOLL.HUP = nil c.EPOLL.ERR = nil c.EPOLL.RDBAND = nil c.EPOLL.IN = nil c.EPOLL.OUT = nil c.EPOLL.PRI = nil -- recent additions c.TCP.THIN_DUPACK = nil c.TCP.FASTOPEN = nil c.TCP.REPAIR_OPTIONS = nil c.TCP.THIN_LINEAR_TIMEOUTS = nil c.TCP.REPAIR = nil c.TCP.QUEUE_SEQ = nil c.TCP.TIMESTAMP = nil c.TCP.USER_TIMEOUT = nil c.TCP.REPAIR_QUEUE = nil -- only in very recent headers, not in ones we are testing against, but include seccomp - will upgrade headers or fix soon c.IPPROTO.TP = nil c.IPPROTO.MTP = nil c.IPPROTO.ENCAP = nil c.SO.PEEK_OFF = nil c.SO.GET_FILTER = nil c.SO.NOFCS = nil c.IFF.DETACH_QUEUE = nil c.IFF.ATTACH_QUEUE = nil c.IFF.MULTI_QUEUE = nil c.PR.SET_NO_NEW_PRIVS = nil c.PR.GET_NO_NEW_PRIVS = nil c.PR.GET_TID_ADDRESS = nil c.TUN.TAP_MQ = nil c.IP.UNICAST_IF = nil c.NTF.SELF = nil c.NTF.MASTER = nil c.SECCOMP_MODE = nil c.SECCOMP_RET = nil c.MFD = nil -- these are not even in linux git head headers or names wrong c.O.ASYNC = nil c.O.FSYNC = nil c.O.RSYNC = nil c.SPLICE_F = nil -- not in any exported header, there should be a linux/splice.h for userspace c.MNT.FORCE = nil c.MNT.EXPIRE = nil c.MNT.DETACH = nil c.EPOLLCREATE.NONBLOCK = nil c.PR_MCE_KILL_OPT = nil c.SWAP_FLAG = nil c.ETHERTYPE = nil c.TFD = nil c.UMOUNT.NOFOLLOW = nil c.EFD = nil c.SCHED.OTHER = nil c.AT.EACCESS = nil c.SI.ASYNCNL = nil c.RLIMIT.OFILE = nil c.TFD_TIMER.ABSTIME = nil c.TFD_TIMER.CANCEL_ON_SET = nil c.AT.EMPTY_PATH = nil -- renamed it seems, TODO sort out c.SYS.newfstatat, c.SYS.fstatat = c.SYS.fstatat, nil -- also renamed/issues on arm TODO sort out if abi.arch == "arm" then c.SYS.fadvise64_64 = nil c.SYS.sync_file_range = nil end if abi.arch == "mips" then c.SYS._newselect, c.SYS.select = c.SYS.select, nil -- now called _newselect end -- new syscalls not in headers yet c.SYS.kcmp = nil c.SYS.finit_module = nil c.SYS.sched_setattr = nil c.SYS.sched_getattr = nil c.SYS.renameat2 = nil c.SYS.seccomp = nil c.SYS.getrandom = nil c.SYS.memfd_create = nil c.SYS.kexec_file_load = nil -- new constants c.GRND = nil return c end local nm = { E = "E", SIG = "SIG", EPOLL = "EPOLL", STD = "STD", MODE = "S_I", MSYNC = "MS_", W = "W", POLL = "POLL", S_I = "S_I", LFLAG = "", IFLAG = "", OFLAG = "", CFLAG = "", CC = "", IOCTL = "", B = "B", SYS = "__NR_", FCNTL_LOCK = "F_", PC = "_PC_", AT_FDCWD = "AT_", SIGACT = "SIG_", SIGPM = "SIG_", SIGILL = "ILL_", SIGFPR = "FPE_", SIGSEGV = "SEGV_", SIGBUS = "BUS_", SIGTRAP = "TRAP_", SIGCLD = "CLD_", SIGPOLL = "POLL_", SIGFPE = "FPE_", IN_INIT = "IN_", LINUX_CAPABILITY_VERSION = "_LINUX_CAPABILITY_VERSION_", LINUX_CAPABILITY_U32S = "_LINUX_CAPABILITY_U32S_", EPOLLCREATE = "EPOLL_", RLIM = "RLIM64_", } -- not defined by kernel print [[ #include <stdint.h> #include <stdio.h> typedef unsigned short int sa_family_t; struct sockaddr { sa_family_t sa_family; char sa_data[14]; }; ]] print [[ #include <linux/types.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/net.h> #include <linux/socket.h> #include <linux/poll.h> #include <linux/eventpoll.h> #include <linux/signal.h> #include <linux/ip.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/capability.h> #include <linux/reboot.h> #include <linux/falloc.h> #include <linux/mman.h> #include <linux/veth.h> #include <linux/sockios.h> #include <linux/sched.h> #include <linux/posix_types.h> #include <linux/if.h> #include <linux/if_bridge.h> #include <linux/if_tun.h> #include <linux/if_arp.h> #include <linux/if_link.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/ioctl.h> #include <linux/input.h> #include <linux/uinput.h> #include <linux/audit.h> #include <linux/filter.h> #include <linux/netfilter.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_ipv4/ip_tables.h> #include <linux/vhost.h> #include <linux/neighbour.h> #include <linux/prctl.h> #include <linux/fcntl.h> #include <linux/timex.h> #include <linux/aio_abi.h> #include <linux/fs.h> #include <linux/wait.h> #include <linux/resource.h> #include <linux/termios.h> #include <linux/xattr.h> #include <linux/stat.h> #include <linux/fadvise.h> #include <linux/inotify.h> #include <linux/route.h> #include <linux/ipv6_route.h> #include <linux/neighbour.h> #include <linux/errno.h> #include <linux/signalfd.h> #include <linux/virtio_pci.h> #include <linux/pci.h> #include <linux/tcp.h> #include <linux/vfio.h> #include <linux/seccomp.h> /* defined in attr/xattr.h */ #define ENOATTR ENODATA int ret; void sassert(int a, int b, char *n) { if (a != b) { printf("error with %s: %d (0x%x) != %d (0x%x)\n", n, a, a, b, b); ret = 1; } } void sassert_u64(uint64_t a, uint64_t b, char *n) { if (a != b) { printf("error with %s: %llu (0x%llx) != %llu (0x%llx)\n", n, (unsigned long long)a, (unsigned long long)a, (unsigned long long)b, (unsigned long long)b); ret = 1; } } int main(int argc, char **argv) { ]] local ffi = require "ffi" local c = require "syscall.linux.constants" local nr = require("syscall.linux.nr") c.SYS = nr.SYS -- add syscalls c = fixup_constants(abi, c) for k, v in pairs(c) do if type(v) == "number" then print("sassert(" .. k .. ", " .. v .. ', "' .. k .. '");') elseif type(v) == "table" then for k2, v2 in pairs(v) do local name = nm[k] or k .. "_" if type(v2) ~= "function" then if type(v2) == "cdata" and ffi.sizeof(v2) == 8 then -- TODO avoid use of ffi if possible print("sassert_u64(" .. name .. k2 .. ", " .. tostring(v2) .. ', "' .. name .. k2 .. '");') else print("sassert(" .. name .. k2 .. ", " .. tostring(v2) .. ', "' .. name .. k2 .. '");') end end end end end print [[ return ret; } ]]
apache-2.0