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
Snazz2001/fbcunn
fbcunn/OneBitQuantization.lua
9
1269
-- Copyright 2004-present Facebook. All Rights Reserved. require 'cutorch' require 'nn' --[[ CUDA implementation of the quantize/unquantize methods used by `nn.OneBitDataParallel`. ]] local OneBitQuantization = torch.class('nn.OneBitQuantization') function OneBitQuantization:__init() self.quantized = torch.CudaTensor() self.non_quantized = torch.CudaTensor() self.quantization_error = nil self.avg_pos = torch.CudaTensor() self.avg_neg = torch.CudaTensor() end function OneBitQuantization:reset() self.quantization_error = nil end function OneBitQuantization:quantize(non_quantized_input) -- When starting a new quantization chain, we start with zero error if not self.quantization_error then self.quantization_error = non_quantized_input:clone() self.quantization_error:zero() end non_quantized_input.nn.OneBitQuantization_quantize(self, non_quantized_input) return self.quantized, self.quantization_error, self.avg_pos, self.avg_neg end function OneBitQuantization:dequantize(quantized_input, avg_pos, avg_neg, num_orig_cols) quantized_input.nn.OneBitQuantization_dequantize( self, quantized_input, avg_pos, avg_neg, num_orig_cols) return self.non_quantized end
bsd-3-clause
Hostle/luci
applications/luci-app-ftp/luasrc/model/cbi/admin_ftp/ftp.lua
1
2281
--[[ LuCI - Lua Configuration Interface $Id: FTP.lua 21/12/2014 $ hostle@fire-wrt.com ]]-- require ("uci") require("luci.sys") local uci = uci.cursor() local ntm = require "luci.model.network".init() local wan = ntm:get_wannet() local lan_ip = uci:get("network", "lan", "ipaddr") local wan_ip = uci:get("network", "wan", "ipaddr") local wwan_ip = wan:ipaddr() local m, s, o m = Map("ftp", translate("FTP SERVER"), translate("Here you can configure the FTP server Settings")) m.on_after_commit = function() luci.sys.exec("/etc/init.d/ftp restart &>/dev/null") end s = m:section(NamedSection, "ftp", "ftp", translate("Server Settings")) s.anonymous = true s.addremove = false -- -- FTP Server -- o = s:option(ListValue, "ipaddr", translate("FTP Server Addr")) if lan_ip ~= nil then o:value(lan_ip) end if wan_ip ~= nil then o:value(Wan_ip) end if wwan_ip ~= nil then o:value(wwan_ip) end o.default = lan_ip o.rmempty = false o = s:option(Value, "server_port", translate("FTP Server Port")) o.default = 8383 o.placeholder = "%d%d%d%d" o.datatype = "uinteger" o.rmempty = false -- -- Log Settings -- s = m:section(TypedSection, "ftp", translate("Log Settings")) s.anonymous = true s.addremove = false o = s:option(ListValue, "console_set", translate("Console Log")) o.rmempty = false o.default = 0 o:value(0, translate("Off")) o:value(1, translate("On")) o.rmempty = false o = s:option(ListValue, "log_level", translate("Log Level")) o.default = 1 o:value(1, translate("Level 1")) o:value(2, translate("Level 2")) o:value(3, translate("Level 3")) o:value(4, translate("Level 4")) -- -- Pasv Settings -- s = m:section(TypedSection, "ftp", translate("Passive Settings")) s.anonymous = true s.addremove = false o = s:option(ListValue, "enable_pasv", translate("Passive Mode")) o.default = true o:value("false", translate("Off")) o:value("true", translate("On")) o.rmempty = false o = s:option(ListValue, "pasv_port", translate("Pasv Port"),translate("<code><b>Range:</b> 85xx - 88xx</code>")) o:depends("enable_pasv", "true") o.default = 85 o:value(85, translate("85XX")) o:value(86, translate("86XX")) o:value(87, translate("87XX")) o:value(88, translate("88XX")) m.redirect = luci.dispatcher.build_url("admin/ftp/ftp") return m
apache-2.0
AdamGagorik/darkstar
scripts/globals/effects/int_boost.lua
34
1027
----------------------------------- -- -- EFFECT_INT_BOOST -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT,effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) -- the effect loses intelligence of 1 every 3 ticks depending on the source of the boost local boostINT_effect_size = effect:getPower(); if (boostINT_effect_size > 0) then effect:setPower(boostINT_effect_size - 1) target:delMod(MOD_INT,1); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local boostINT_effect_size = effect:getPower(); if (boostINT_effect_size > 0) then target:delMod(MOD_INT,boostINT_effect_size); end end;
gpl-3.0
ReformedGeek/CodeEval
FizzBuzz/FizzBuzz.lua
1
3422
--[[ Challenge description: https://www.codeeval.com/open_challenges/1/ Solution description: Generalized FizzBuzz generator with optimized routine for cases where one divisor is an even divisor of the other or where the divisors are equal. --]] --[[ In the case that one divisor equals one, we can optimize FizzBuzz by only checking one divisor for even divisibility. In the case that both are equal to 1, no checks are necessary apart from a bounds checks to prevent trailing spaces per the exercise instructions. While these are technically different edge cases, they are similar enough to justify putting this secondary check into one_fizzbuzz() rather than having a second check and additional subroutine. --]] local function one_fizzbuzz(x, y, limit) if x == 1 then if y == 1 then for i=1, limit do io.write("FB") if i == limit then return end io.write(" ") end else for i = 1, limit do if i % y == 0 then io.write("FB") else io.write("F") end if i == limit then return end io.write(" ") end end else for i=1, limit do if i % x == 0 then io.write("FB") else io.write("B") end if i == limit then return end io.write(" ") end end end --[[ If x or y is a divisor of the other, we can optimize our FizzBuzz routine by doing less checks for divisibility, since we can guarantee that the smaller of the two divisors will always be an even divisor of i if the larger divisor is an even divisor of i. --]] local function simplified_fizzbuzz(x, y, limit) for i=1,limit do if x > y then if i % x == 0 then io.write("FB") elseif i % y == 0 then io.write("B") else io.write(tostring(i)) end else if i % y == 0 then io.write("FB") elseif i % x == 0 then io.write("F") else io.write(tostring(i)) end end if i == limit then return end io.write(" ") end end --[[ If x and y are equal, we can optimize our FizzBuzz routine by doing only one check for divisibility. --]] local function equal_fizzbuzz(x, limit) for i=1,limit do if i % x == 0 then io.write("FB") else io.write(tostring(i)) end if i == limit then return end io.write(" ") end end -- Generalized form of FizzBuzz local function generalized_fizzbuzz(x, y, limit) for i=1,limit do if i % x == 0 then if i % y == 0 then io.write("FB") else io.write("F") end elseif i % y == 0 then io.write("B") else io.write(tostring(i)) end if i == limit then return end io.write(" ") end end -- Main routine local lines = {} local file = assert(io.open(arg[1], "r")) for line in file:lines() do local nums = {} for num in line:gmatch("%d+") do nums[#nums + 1] = tonumber(num) end lines[#lines + 1] = nums end for n, line in ipairs(lines) do local x, y, limit = line[1], line[2], line[3] if x == 1 or y == 1 then one_fizzbuzz(x, y, limit) elseif x ~= y and (x % y == 0 or y % x == 0) then simplified_fizzbuzz(x, y, limit) elseif x == y then equal_fizzbuzz(x, limit) else generalized_fizzbuzz(x, y, limit) end if n ~= #lines then io.write("\n") end end
gpl-2.0
delram/inx
plugins/TIME.lua
120
2804
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'In "'..area..'" they dont have time' end local localTime, timeZoneId = get_time(lat,lng) return "Local: "..timeZoneId.."\nTime: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Get Time Give by Local Name", usage = "/time (local) : view local time", patterns = {"^[!/]time (.*)$"}, run = run }
gpl-2.0
Snazz2001/fbcunn
examples/imagenet/dataset.lua
3
14930
require 'torch' torch.setdefaulttensortype('torch.FloatTensor') local ffi = require 'ffi' local class = require('pl.class') local dir = require 'pl.dir' local tablex = require 'pl.tablex' local argcheck = require 'argcheck' require 'sys' require 'xlua' require 'image' local dataset = torch.class('dataLoader') local initcheck = argcheck{ pack=true, help=[[ A dataset class for images in a flat folder structure (folder-name is class-name). Optimized for extremely large datasets (upwards of 14 million images). Tested only on Linux (as it uses command-line linux utilities to scale up) ]], {check=function(paths) local out = true; for k,v in ipairs(paths) do if type(v) ~= 'string' then print('paths can only be of string input'); out = false end end return out end, name="paths", type="table", help="Multiple paths of directories with images"}, {name="sampleSize", type="table", help="a consistent sample size to resize the images"}, {name="split", type="number", help="Percentage of split to go to Training" }, {name="samplingMode", type="string", help="Sampling mode: random | balanced ", default = "balanced"}, {name="verbose", type="boolean", help="Verbose mode during initialization", default = false}, {name="loadSize", type="table", help="a size to load the images to, initially", opt = true}, {name="forceClasses", type="table", help="If you want this loader to map certain classes to certain indices, " .. "pass a classes table that has {classname : classindex} pairs." .. " For example: {3 : 'dog', 5 : 'cat'}" .. "This function is very useful when you want two loaders to have the same " .. "class indices (trainLoader/testLoader for example)", opt = true}, {name="sampleHookTrain", type="function", help="applied to sample during training(ex: for lighting jitter). " .. "It takes the image path as input", opt = true}, {name="sampleHookTest", type="function", help="applied to sample during testing", opt = true}, } function dataset:__init(...) -- argcheck local args = initcheck(...) print(args) for k,v in pairs(args) do self[k] = v end if not self.loadSize then self.loadSize = self.sampleSize; end if not self.sampleHookTrain then self.sampleHookTrain = self.defaultSampleHook end if not self.sampleHookTest then self.sampleHookTest = self.defaultSampleHook end -- find class names self.classes = {} local classPaths = {} if self.forceClasses then for k,v in pairs(self.forceClasses) do self.classes[k] = v classPaths[k] = {} end end local function tableFind(t, o) for k,v in pairs(t) do if v == o then return k end end end -- loop over each paths folder, get list of unique class names, -- also store the directory paths per class -- for each class, for k,path in ipairs(self.paths) do local dirs = dir.getdirectories(path); for k,dirpath in ipairs(dirs) do local class = paths.basename(dirpath) local idx = tableFind(self.classes, class) if not idx then table.insert(self.classes, class) idx = #self.classes classPaths[idx] = {} end if not tableFind(classPaths[idx], dirpath) then table.insert(classPaths[idx], dirpath); end end end self.classIndices = {} for k,v in ipairs(self.classes) do self.classIndices[v] = k end -- define command-line tools, try your best to maintain OSX compatibility local wc = 'wc' local cut = 'cut' local find = 'find' if jit.os == 'OSX' then wc = 'gwc' cut = 'gcut' find = 'gfind' end ---------------------------------------------------------------------- -- Options for the GNU find command local extensionList = {'jpg', 'png','JPG','PNG','JPEG', 'ppm', 'PPM', 'bmp', 'BMP'} local findOptions = ' -iname "*.' .. extensionList[1] .. '"' for i=2,#extensionList do findOptions = findOptions .. ' -o -iname "*.' .. extensionList[i] .. '"' end -- find the image path names self.imagePath = torch.CharTensor() -- path to each image in dataset self.imageClass = torch.LongTensor() -- class index of each image (class index in self.classes) self.classList = {} -- index of imageList to each image of a particular class self.classListSample = self.classList -- the main list used when sampling data print('running "find" on each class directory, and concatenate all' .. ' those filenames into a single file containing all image paths for a given class') -- so, generates one file per class local classFindFiles = {} for i=1,#self.classes do classFindFiles[i] = os.tmpname() end local combinedFindList = os.tmpname(); local tmpfile = os.tmpname() local tmphandle = assert(io.open(tmpfile, 'w')) -- iterate over classes for i, class in ipairs(self.classes) do -- iterate over classPaths for j,path in ipairs(classPaths[i]) do local command = find .. ' "' .. path .. '" ' .. findOptions .. ' >>"' .. classFindFiles[i] .. '" \n' tmphandle:write(command) end end io.close(tmphandle) os.execute('bash ' .. tmpfile) os.execute('rm -f ' .. tmpfile) print('now combine all the files to a single large file') local tmpfile = os.tmpname() local tmphandle = assert(io.open(tmpfile, 'w')) -- concat all finds to a single large file in the order of self.classes for i=1,#self.classes do local command = 'cat "' .. classFindFiles[i] .. '" >>' .. combinedFindList .. ' \n' tmphandle:write(command) end io.close(tmphandle) os.execute('bash ' .. tmpfile) os.execute('rm -f ' .. tmpfile) --========================================================================== print('load the large concatenated list of sample paths to self.imagePath') local maxPathLength = tonumber(sys.fexecute(wc .. " -L '" .. combinedFindList .. "' |" .. cut .. " -f1 -d' '")) + 1 local length = tonumber(sys.fexecute(wc .. " -l '" .. combinedFindList .. "' |" .. cut .. " -f1 -d' '")) assert(length > 0, "Could not find any image file in the given input paths") assert(maxPathLength > 0, "paths of files are length 0?") self.imagePath:resize(length, maxPathLength):fill(0) local s_data = self.imagePath:data() local count = 0 for line in io.lines(combinedFindList) do ffi.copy(s_data, line) s_data = s_data + maxPathLength if self.verbose and count % 10000 == 0 then xlua.progress(count, length) end; count = count + 1 end self.numSamples = self.imagePath:size(1) if self.verbose then print(self.numSamples .. ' samples found.') end --========================================================================== print('Updating classList and imageClass appropriately') self.imageClass:resize(self.numSamples) local runningIndex = 0 for i=1,#self.classes do if self.verbose then xlua.progress(i, #(self.classes)) end local length = tonumber(sys.fexecute(wc .. " -l '" .. classFindFiles[i] .. "' |" .. cut .. " -f1 -d' '")) if length == 0 then error('Class has zero samples') else self.classList[i] = torch.linspace(runningIndex + 1, runningIndex + length, length):long() self.imageClass[{{runningIndex + 1, runningIndex + length}}]:fill(i) end runningIndex = runningIndex + length end --========================================================================== -- clean up temporary files print('Cleaning up temporary files') local tmpfilelistall = '' for i=1,#(classFindFiles) do tmpfilelistall = tmpfilelistall .. ' "' .. classFindFiles[i] .. '"' if i % 1000 == 0 then os.execute('rm -f ' .. tmpfilelistall) tmpfilelistall = '' end end os.execute('rm -f ' .. tmpfilelistall) os.execute('rm -f "' .. combinedFindList .. '"') --========================================================================== if self.split == 100 then self.testIndicesSize = 0 else print('Splitting training and test sets to a ratio of ' .. self.split .. '/' .. (100-self.split)) self.classListTrain = {} self.classListTest = {} self.classListSample = self.classListTrain local totalTestSamples = 0 -- split the classList into classListTrain and classListTest for i=1,#self.classes do local list = self.classList[i] local count = self.classList[i]:size(1) local splitidx = math.floor((count * self.split / 100) + 0.5) -- +round local perm = torch.randperm(count) self.classListTrain[i] = torch.LongTensor(splitidx) for j=1,splitidx do self.classListTrain[i][j] = list[perm[j]] end if splitidx == count then -- all samples were allocated to train set self.classListTest[i] = torch.LongTensor() else self.classListTest[i] = torch.LongTensor(count-splitidx) totalTestSamples = totalTestSamples + self.classListTest[i]:size(1) local idx = 1 for j=splitidx+1,count do self.classListTest[i][idx] = list[perm[j]] idx = idx + 1 end end end -- Now combine classListTest into a single tensor self.testIndices = torch.LongTensor(totalTestSamples) self.testIndicesSize = totalTestSamples local tdata = self.testIndices:data() local tidx = 0 for i=1,#self.classes do local list = self.classListTest[i] if list:dim() ~= 0 then local ldata = list:data() for j=0,list:size(1)-1 do tdata[tidx] = ldata[j] tidx = tidx + 1 end end end end end -- size(), size(class) function dataset:size(class, list) list = list or self.classList if not class then return self.numSamples elseif type(class) == 'string' then return list[self.classIndices[class]]:size(1) elseif type(class) == 'number' then return list[class]:size(1) end end -- size(), size(class) function dataset:sizeTrain(class) if self.split == 0 then return 0; end if class then return self:size(class, self.classListTrain) else return self.numSamples - self.testIndicesSize end end -- size(), size(class) function dataset:sizeTest(class) if self.split == 100 then return 0 end if class then return self:size(class, self.classListTest) else return self.testIndicesSize end end -- by default, just load the image and return it function dataset:defaultSampleHook(imgpath) local out = image.load(imgpath, self.loadSize[1]) out = image.scale(out, self.sampleSize[3], self.sampleSize[2]) return out end -- getByClass function dataset:getByClass(class) local index = math.ceil(torch.uniform() * self.classListSample[class]:nElement()) local imgpath = ffi.string(torch.data(self.imagePath[self.classListSample[class][index]])) return self:sampleHookTrain(imgpath) end -- converts a table of samples (and corresponding labels) to a clean tensor local function tableToOutput(self, dataTable, scalarTable) local data, scalarLabels, labels local quantity = #scalarTable local samplesPerDraw if dataTable[1]:dim() == 3 then samplesPerDraw = 1 else samplesPerDraw = dataTable[1]:size(1) end if quantity == 1 and samplesPerDraw == 1 then data = dataTable[1] scalarLabels = scalarTable[1] labels = torch.LongTensor(#(self.classes)):fill(-1) labels[scalarLabels] = 1 else data = torch.Tensor(quantity * samplesPerDraw, self.sampleSize[1], self.sampleSize[2], self.sampleSize[3]) scalarLabels = torch.LongTensor(quantity * samplesPerDraw) labels = torch.LongTensor(quantity * samplesPerDraw, #(self.classes)):fill(-1) for i=1,#dataTable do local idx = (i-1)*samplesPerDraw data[{{idx+1,idx+samplesPerDraw}}]:copy(dataTable[i]) scalarLabels[{{idx+1,idx+samplesPerDraw}}]:fill(scalarTable[i]) labels[{{idx+1,idx+samplesPerDraw},{scalarTable[i]}}]:fill(1) end end return data, scalarLabels, labels end -- sampler, samples from the training set. function dataset:sample(quantity) if self.split == 0 then error('No training mode when split is set to 0') end quantity = quantity or 1 local dataTable = {} local scalarTable = {} for i=1,quantity do local class = torch.random(1, #self.classes) local out = self:getByClass(class) table.insert(dataTable, out) table.insert(scalarTable, class) end local data, scalarLabels, labels = tableToOutput(self, dataTable, scalarTable) return data, scalarLabels, labels end function dataset:get(i1, i2) local indices, quantity if type(i1) == 'number' then if type(i2) == 'number' then -- range of indices indices = torch.range(i1, i2); quantity = i2 - i1 + 1; else -- single index indices = {i1}; quantity = 1 end elseif type(i1) == 'table' then indices = i1; quantity = #i1; -- table elseif (type(i1) == 'userdata' and i1:nDimension() == 1) then indices = i1; quantity = (#i1)[1]; -- tensor else error('Unsupported input types: ' .. type(i1) .. ' ' .. type(i2)) end assert(quantity > 0) -- now that indices has been initialized, get the samples local dataTable = {} local scalarTable = {} for i=1,quantity do -- load the sample local imgpath = ffi.string(torch.data(self.imagePath[indices[i]])) local out = self:sampleHookTest(imgpath) table.insert(dataTable, out) table.insert(scalarTable, self.imageClass[indices[i]]) end local data, scalarLabels, labels = tableToOutput(self, dataTable, scalarTable) return data, scalarLabels, labels end function dataset:test(quantity) if self.split == 100 then error('No test mode when you are not splitting the data') end local i = 1 local n = self.testIndicesSize local qty = quantity or 1 return function () if i+qty-1 <= n then local data, scalarLabelss, labels = self:get(i, i+qty-1) i = i + qty return data, scalarLabelss, labels end end end return dataset
bsd-3-clause
sjznxd/lc-20130204
applications/luci-upnp/luasrc/controller/upnp.lua
6
1943
--[[ 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$ ]]-- module("luci.controller.upnp", package.seeall) function index() if not nixio.fs.access("/etc/config/upnpd") then return end local page page = entry({"admin", "services", "upnp"}, cbi("upnp/upnp"), _("UPNP")) page.dependent = true page = entry({"mini", "network", "upnp"}, cbi("upnp/upnpmini", {autoapply=true}), _("UPNP")) page.dependent = true entry({"admin", "services", "upnp", "status"}, call("act_status")).leaf = true entry({"admin", "services", "upnp", "delete"}, call("act_delete")).leaf = true end function act_status() local ipt = io.popen("iptables --line-numbers -t nat -xnvL MINIUPNPD") if ipt then local fwd = { } while true do local ln = ipt:read("*l") if not ln then break elseif ln:match("^%d+") then local num, proto, extport, intaddr, intport = ln:match("^(%d+).-([a-z]+).-dpt:(%d+) to:(%S-):(%d+)") if num and proto and extport and intaddr and intport then num = tonumber(num) extport = tonumber(extport) intport = tonumber(intport) fwd[#fwd+1] = { num = num, proto = proto:upper(), extport = extport, intaddr = intaddr, intport = intport } end end end ipt:close() luci.http.prepare_content("application/json") luci.http.write_json(fwd) end end function act_delete(idx) idx = tonumber(idx) if idx and idx > 0 then luci.sys.call("iptables -t filter -D MINIUPNPD %d 2>/dev/null" % idx) luci.sys.call("iptables -t nat -D MINIUPNPD %d 2>/dev/null" % idx) return end luci.http.status(400, "Bad request") end
apache-2.0
AdamGagorik/darkstar
scripts/zones/Port_Windurst/npcs/Pyo_Nzon.lua
13
2857
----------------------------------- -- Area: Port Windurst -- NPC: Pyo Nzon ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) 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); ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE); if (ThePromise == QUEST_COMPLETED) then Message = math.random(0,1) if (Message == 1) then player:startEvent(0x021b); else player:startEvent(0x020f); end elseif (ThePromise == QUEST_ACCEPTED) then player:startEvent(0x0205); elseif (CryingOverOnions == QUEST_COMPLETED) then player:startEvent(0x01fe); elseif (CryingOverOnions == QUEST_ACCEPTED) then player:startEvent(0x01f6); elseif (OnionRings == QUEST_COMPLETED) then player:startEvent(0x01bb); elseif (OnionRings == QUEST_ACCEPTED ) then player:startEvent(0x01b5); elseif (InspectorsGadget == QUEST_COMPLETED) then player:startEvent(0x01aa); elseif (InspectorsGadget == QUEST_ACCEPTED) then player:startEvent(0x01a2); elseif (KnowOnesOnions == QUEST_COMPLETED) then player:startEvent(0x0199); elseif (KnowOnesOnions == QUEST_ACCEPTED) then KnowOnesOnionsVar = player:getVar("KnowOnesOnions"); if (KnowOnesOnionsVar == 2) then player:startEvent(0x0198); else player:startEvent(0x018c); end elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then player:startEvent(0x017e); elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then player:startEvent(0x0177); else player:startEvent(0x016e); 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); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Port_Jeuno/npcs/Kochahy-Muwachahy.lua
14
3674
----------------------------------- -- Area: Port Jeuno -- NPC: Kochahy-Muwachahy -- @pos 40 0 6 246 ------------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/conquest"); require("scripts/zones/Port_Jeuno/TextIDs"); local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno). local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Menu1 = getArg1(guardnation,player); local Menu3 = conquestRanking(); local Menu6 = getArg6(player); local Menu7 = player:getCP(); player:startEvent(0x7ffb,Menu1,0,Menu3,0,0,Menu6,Menu7,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); if (player:getNation() == 0) then inventory = SandInv; size = table.getn(SandInv); elseif (player:getNation() == 1) then inventory = BastInv; size = table.getn(BastInv); else inventory = WindInv; size = table.getn(WindInv); end if (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then CPVerify = 1; if (player:getCP() >= inventory[Item + 1]) then CPVerify = 0; end; player:updateEvent(2,CPVerify,inventory[Item + 2]); -- can't equip = 2 ? break; end; end; end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then if (player:getFreeSlotsCount() >= 1) then -- Logic to impose limits on exp bands if (option >= 32933 and option <= 32935) then if (checkConquestRing(player) > 0) then player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]); break; else player:setVar("CONQUEST_RING_TIMER",getConquestTally()); end end itemCP = inventory[Item + 1]; player:delCP(itemCP); player:addItem(inventory[Item + 2],1); player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end; break; end; end; end; end;
gpl-3.0
TeleDALAD/test1
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
mohammad25253/seed238
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
hadirahimi1380/-AhRiMaN-
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
sjznxd/lc-20130204
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_config.lua
80
1153
--[[ LuCI - Lua Configuration Interface (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 $Id$ ]]-- require("luci.controller.luci_diag.devinfo_common") m = Map("luci_devinfo", translate("Network Device Scanning Configuration"), translate("Configure scanning for devices on specified networks. Decreasing \'Timeout\', \'Repeat Count\', and/or \'Sleep Between Requests\' may speed up scans, but also may fail to find some devices.")) s = m:section(SimpleSection, "", translate("Use Configuration")) b = s:option(DummyValue, "_scans", translate("Perform Scans (this can take a few minutes)")) b.value = "" b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo") scannet = m:section(TypedSection, "netdiscover_scannet", translate("Scanning Configuration"), translate("Networks to scan for devices")) scannet.addremove = true scannet.anonymous = false luci.controller.luci_diag.devinfo_common.config_devinfo_scan(m, scannet) return m
apache-2.0
linux-man/lovefs
GspotDemo/main.lua
1
2123
gui = require('Gspot/Gspot') require('lovefs/lovefs') require('lovefs/gspotDialog') love.load = function() fs = lovefs() local button = gui:button('Load Image', {0, 0, 200, 40}) button.click = function(this) save = false fs:loadDialog(gui, 'Load Image', {'All | *.*', 'Jpeg | *.jpg *.jpeg', 'Png | *.png', 'Bmp | *.bmp', 'Gif | *.gif'}) end local button = gui:button('Load Sound', {200, 0, 200, 40}) button.click = function(this) save = false fs:loadDialog(gui, 'Load Sound', {'Sound | *.mp3 *.wav', 'All | *.*'}) end local button = gui:button('Load TrueType', {400, 0, 200, 40}) button.click = function(this) save = false fs:loadDialog(gui, 'Load TrueType', {'TrueType | *.ttf', 'All | *.*'}) end saveButton = gui:button('Save Image (as png)', {600, 0, 200, 40}) saveButton.click = function(this) save = true fs:saveDialog(gui, 'Save Image') end saveButton:hide() end love.update = function(dt) gui:update(dt) if fs.selectedFile then ext = fs.selectedFile:match('[^'..fs.sep..']+$'):match('[^.]+$') if save then if newImage then fs:saveImage(newImage) end save = false elseif ext == 'jpg' or ext == 'png' or ext == 'bmp' then newImage = fs:loadImage() saveButton:show() elseif ext == 'mp3' or ext == 'wav' then sound = fs:loadSource() sound:play() elseif ext == 'ttf' then font = fs:loadFont(32) if font then love.graphics.setFont(font) end end end end love.draw = function() love.graphics.setColor(255, 255, 255) if newImage then love.graphics.draw(newImage, 0, 0, 0, math.min(800 / newImage:getWidth(), 600 / newImage:getHeight()), math.min(800 / newImage:getWidth(), 600 / newImage:getHeight())) end love.graphics.print('LoveFS Demo', 5, 550) gui:draw() end love.mousepressed = function(x, y, button) gui:mousepress(x, y, button) end love.mousereleased = function(x, y, button) gui:mouserelease(x, y, button) end love.wheelmoved = function(x, y) gui:mousewheel(x, y) end love.keypressed = function(key) if gui.focus then gui:keypress(key) end end love.textinput = function(key) if gui.focus then gui:textinput(key) end end
mit
AdamGagorik/darkstar
scripts/zones/Beadeaux/npcs/The_Mute.lua
13
1276
----------------------------------- -- Area: Beadeaux -- NPC: ??? -- @pos -166.230 -1 -73.685 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Beadeaux/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local duration = math.random(600,900); if (player:getQuestStatus(BASTOK,THE_CURSE_COLLECTOR) == QUEST_ACCEPTED and player:getVar("cCollectSilence") == 0) then player:setVar("cCollectSilence",1); end player:addStatusEffect(EFFECT_SILENCE,0,0,duration); 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
AdamGagorik/darkstar
scripts/globals/items/cheese_sandwich_+1.lua
18
1186
----------------------------------------- -- ID: 5687 -- Item: cheese_sandwich_+1 -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 10 -- Agility 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,3600,5687); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_AGI, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_AGI, 2); end;
gpl-3.0
ohmbase/OpenRA
mods/ra/maps/allies-03a/allies03a.lua
18
9282
ProductionUnits = { "e1", "e1", "e2" } ProductionBuildings = { USSRBarracks1, USSRBarracks2 } TransportReinforcements = { "e1", "e1", "e1", "e2", "e2" } FirstUSSRBase = { USSRFlameTower1, USSRBarracks1, USSRPowerPlant1, USSRPowerPlant2, USSRConstructionYard1, USSRTechCenter, USSRBaseGuard1, USSRBaseGuard2, USSRBaseGuard3, USSRBaseGuard4, USSRBaseGuard5, USSRBaseGuard6, USSRBaseGuard7, USSRBaseGuard8 } SecondUSSRBase = { USSRBarracks2, USSRKennel, USSRRadarDome, USSRBaseGuard10, USSRBaseGuard11, USSRBaseGuard12, USSRBaseGuard13, USSRBaseGuard14 } Prisoners = { PrisonedMedi1, PrisonedMedi2, PrisonedEngi } CameraTriggerArea = { CPos.New(43, 64), CPos.New(44, 64), CPos.New(45, 64), CPos.New(46, 64), CPos.New(47, 64) } WaterTransportTriggerArea = { CPos.New(39, 54), CPos.New(40, 54), CPos.New(41, 54), CPos.New(42, 54), CPos.New(43, 54), CPos.New(44, 54), CPos.New(45, 54) } ParadropTriggerArea = { CPos.New(81, 60), CPos.New(82, 60), CPos.New(83, 60), CPos.New(63, 63), CPos.New(64, 63), CPos.New(65, 63), CPos.New(66, 63), CPos.New(67, 63), CPos.New(68, 63), CPos.New(69, 63), CPos.New(70, 63), CPos.New(71, 63), CPos.New(72, 63) } ReinforcementsTriggerArea = { CPos.New(96, 55), CPos.New(97, 55), CPos.New(97, 56), CPos.New(98, 56) } if Map.Difficulty == "Easy" then TanyaType = "e7" else TanyaType = "e7.noautotarget" ChangeStance = true end IdleHunt = function(actor) Trigger.OnIdle(actor, function(a) if a.IsInWorld then a.Hunt() end end) end ProduceUnits = function(factory, count) if ussr.IsProducing("e1") then Trigger.AfterDelay(DateTime.Seconds(5), function() ProduceUnits(factory, count) end) return end local units = { } for i = 0, count, 1 do local type = Utils.Random(ProductionUnits) units[i] = type end if not factory.IsDead then factory.IsPrimaryBuilding = true ussr.Build(units, function(soldiers) Utils.Do(soldiers, function(unit) IdleHunt(unit) end) end) end end SendAlliedUnits = function() Camera.Position = TanyaWaypoint.CenterPosition local Artillery = Actor.Create("arty", true, { Owner = player, Location = AlliedUnitsEntry.Location }) local Tanya = Actor.Create(TanyaType, true, { Owner = player, Location = AlliedUnitsEntry.Location }) if ChangeStance then Tanya.Stance = "HoldFire" Trigger.AfterDelay(DateTime.Seconds(2), function() Media.DisplayMessage("According to the rules of engagement I need your explicit orders to fire, Commander!", "Tanya") end) end Artillery.Stance = "HoldFire" Tanya.Move(TanyaWaypoint.Location) Artillery.Move(ArtilleryWaypoint.Location) Trigger.OnKilled(Tanya, function() player.MarkFailedObjective(TanyaSurvive) end) end SendUSSRParadrops = function() local powerproxy = Actor.Create("powerproxy.paratroopers", false, { Owner = ussr }) local unitsA = powerproxy.SendParatroopers(ParadropLZ.CenterPosition, false, 128 + 32) local unitsB = powerproxy.SendParatroopers(ParadropLZ.CenterPosition, false, 128 - 32) Utils.Do(unitsA, function(unit) IdleHunt(unit) end) Utils.Do(unitsB, function(unit) IdleHunt(unit) end) powerproxy.Destroy() end SendUSSRWaterTransport = function() local units = Reinforcements.ReinforceWithTransport(ussr, "lst", TransportReinforcements, { WaterTransportEntry.Location, WaterTransportLoadout.Location }, { WaterTransportExit.Location })[2] Utils.Do(units, function(unit) IdleHunt(unit) end) end SendUSSRTankReinforcements = function() local camera = Actor.Create("camera", true, { Owner = player, Location = USSRReinforcementsCameraWaypoint.Location }) local ussrTank = Reinforcements.Reinforce(ussr, { "3tnk" }, { USSRReinforcementsEntryWaypoint.Location, USSRReinforcementsRallyWaypoint1.Location, USSRReinforcementsRallyWaypoint2.Location })[1] Trigger.OnRemovedFromWorld(ussrTank, function() Trigger.AfterDelay(DateTime.Seconds(3), function() if not camera.IsDead then camera.Destroy() end end) end) end InitPlayers = function() player = Player.GetPlayer("Greece") ussr = Player.GetPlayer("USSR") ussr.Cash = 10000 end InitObjectives = function() Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) KillBridges = player.AddPrimaryObjective("Destroy all bridges.") TanyaSurvive = player.AddPrimaryObjective("Tanya must survive.") KillUSSR = player.AddSecondaryObjective("Destroy all Soviet oil pumps.") FreePrisoners = player.AddSecondaryObjective("Free all Allied soldiers and keep them alive.") ussr.AddPrimaryObjective("Bridges must not be destroyed.") Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "MissionFailed") end) end) Trigger.OnPlayerWon(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "MissionAccomplished") end) end) end InitTriggers = function() Utils.Do(ussr.GetGroundAttackers(), function(unit) Trigger.OnDamaged(unit, function() IdleHunt(unit) end) end) Trigger.OnAnyKilled(Prisoners, function() player.MarkFailedObjective(FreePrisoners) end) Trigger.OnKilled(USSRTechCenter, function() Actor.Create("moneycrate", true, { Owner = ussr, Location = USSRMoneyCrateSpawn.Location }) end) Trigger.OnKilled(ExplosiveBarrel, function() local bridge = Map.ActorsInBox(USSRReinforcementsCameraWaypoint.CenterPosition, USSRReinforcementsEntryWaypoint.CenterPosition, function(self) return self.Type == "bridge1" end) if not bridge[1].IsDead then bridge[1].Kill() end end) Utils.Do(FirstUSSRBase, function(unit) Trigger.OnDamaged(unit, function() if not FirstBaseAlert then FirstBaseAlert = true if not baseCamera then -- TODO: remove the Trigger baseCamera = Actor.Create("camera", true, { Owner = player, Location = BaseCameraWaypoint.Location }) end Utils.Do(FirstUSSRBase, function(unit) if unit.HasProperty("Move") then IdleHunt(unit) end end) for i = 0, 2 do Trigger.AfterDelay(DateTime.Seconds(i), function() Media.PlaySoundNotification(player, "AlertBuzzer") end) end ProduceUnits(ProductionBuildings[1], Utils.RandomInteger(4, 8)) end end) end) Trigger.OnAllRemovedFromWorld(FirstUSSRBase, function() -- The camera can remain when one building is captured if baseCamera then baseCamera.Destroy() end end) Utils.Do(SecondUSSRBase, function(unit) Trigger.OnDamaged(unit, function() if not SecondBaseAlert then SecondBaseAlert = true Utils.Do(SecondUSSRBase, function(unit) if unit.HasProperty("Move") then IdleHunt(unit) end end) for i = 0, 2 do Trigger.AfterDelay(DateTime.Seconds(i), function() Media.PlaySoundNotification(player, "AlertBuzzer") end) end ProduceUnits(ProductionBuildings[2], Utils.RandomInteger(5, 7)) end end) end) Trigger.OnCapture(USSRRadarDome, function(self) largeCamera = Actor.Create("camera.verylarge", true, { Owner = player, Location = LargeCameraWaypoint.Location }) Trigger.ClearAll(self) Trigger.AfterDelay(DateTime.Seconds(1), function() Trigger.OnRemovedFromWorld(self, function() Trigger.ClearAll(self) if largeCamera.IsInWorld then largeCamera.Destroy() end end) end) end) Trigger.OnEnteredFootprint(CameraTriggerArea, function(a, id) if a.Owner == player and not baseCamera then Trigger.RemoveFootprintTrigger(id) baseCamera = Actor.Create("camera", true, { Owner = player, Location = BaseCameraWaypoint.Location }) end end) Trigger.OnEnteredFootprint(WaterTransportTriggerArea, function(a, id) if a.Owner == player and not waterTransportTriggered then waterTransportTriggered = true Trigger.RemoveFootprintTrigger(id) SendUSSRWaterTransport() end end) Trigger.OnEnteredFootprint(ParadropTriggerArea, function(a, id) if a.Owner == player and not paradropsTriggered then paradropsTriggered = true Trigger.RemoveFootprintTrigger(id) SendUSSRParadrops() end end) Trigger.OnEnteredFootprint(ReinforcementsTriggerArea, function(a, id) if a.Owner == player and not reinforcementsTriggered then reinforcementsTriggered = true Trigger.RemoveFootprintTrigger(id) Trigger.AfterDelay(DateTime.Seconds(1), function() SendUSSRTankReinforcements() end) end end) Trigger.AfterDelay(0, function() local bridges = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(self) return self.Type == "bridge1" end) Trigger.OnAllKilled(bridges, function() player.MarkCompletedObjective(KillBridges) player.MarkCompletedObjective(TanyaSurvive) player.MarkCompletedObjective(FreePrisoners) end) local oilPumps = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(self) return self.Type == "v19" end) Trigger.OnAllKilled(oilPumps, function() player.MarkCompletedObjective(KillUSSR) end) end) end WorldLoaded = function() InitPlayers() InitObjectives() InitTriggers() SendAlliedUnits() end
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Temenos/mobs/Temenos_Weapon.lua
7
1276
----------------------------------- -- Area: Temenos Central 1floor -- NPC: Temenos_Weapon ----------------------------------- 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) if (IsMobDead(16929048)==true) then mob:addStatusEffect(EFFECT_REGAIN,7,3,0); mob:addStatusEffect(EFFECT_REGEN,50,3,0); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if (IsMobDead(16929046)==true and IsMobDead(16929047)==true and IsMobDead(16929048)==true and IsMobDead(16929049)==true and IsMobDead(16929050)==true and IsMobDead(16929051)==true) then GetNPCByID(16928768+71):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+71):setStatus(STATUS_NORMAL); GetNPCByID(16928770+471):setStatus(STATUS_NORMAL); end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Davoi/npcs/Disused_Well.lua
13
1333
----------------------------------- -- Area: Davoi -- NPC: Disused Well -- Involved in Quest: A Knight's Test -- @pos -221 2 -293 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(KNIGHTS_SOUL) == false and player:hasKeyItem(BOOK_OF_TASKS) and player:hasKeyItem(BOOK_OF_THE_WEST) and player:hasKeyItem(BOOK_OF_THE_EAST)) then player:addKeyItem(KNIGHTS_SOUL); player:messageSpecial(KEYITEM_OBTAINED, KNIGHTS_SOUL); else player:messageSpecial(A_WELL); 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
luveti/Urho3D
bin/Data/LuaScripts/Utilities/ScriptCompiler.lua
29
1247
-- Script to recursively compile lua files located in specified rootFolder to luc (bytecode) -- Usage: require "LuaScripts/Utilities/LuaScriptCompiler" -- Set root folder containing lua files to convert local rootFolder = "Data/LuaScripts/" -- Starting from bin folder if not fileSystem:DirExists(rootFolder) then log:Write(LOG_WARNING, "Cannot find " .. rootFolder) return end -- Ensure that rootFolder exists -- Get lua files recursively local files = fileSystem:ScanDir(fileSystem:GetProgramDir() .. rootFolder, "*.lua", SCAN_FILES, true) if table.maxn(files) == 0 then log:Write(LOG_WARNING, "No lua file found in " .. rootFolder .. " and subfolders") return end -- Ensure that at least one file was found -- Compile each lua file found in rootFolder and subfolders to luc for i=1, table.maxn(files) do local filename = rootFolder .. files[i] -- Get file with its path if not fileSystem:FileExists(filename) then log:Write(LOG_WARNING, "Cannot find " .. filename) return end print(filename .. "\n") local args = {"-b", filename, ReplaceExtension(filename, ".luc")} -- Set arguments to pass to the luajit command line app fileSystem:SystemRun(fileSystem:GetProgramDir() .. "luajit", args) -- Compile lua file to luc end
mit
AdamGagorik/darkstar
scripts/globals/items/cup_of_chocomilk.lua
18
1139
----------------------------------------- -- ID: 4498 -- Item: cup_of_chocomilk -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic Regen While Healing 3 ----------------------------------------- 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,4498); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 3); end;
gpl-3.0
sjznxd/lc-20130204
modules/niu/luasrc/model/cbi/niu/network/ddns1.lua
37
1993
--[[ 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$ ]]-- local nxo = require "nixio" m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that this device can be reached with a fixed hostname while having a dynamically changing IP-Address.")) s = m:section(TypedSection, "service", "") s:depends("enabled", "1") s.addremove = true s.defaults.enabled = "1" s.defaults.ip_network = "wan" s.defaults.ip_url = "http://checkip.dyndns.org http://www.whatismyip.com/automation/n09230945.asp" s:tab("general", translate("General Settings")) svc = s:taboption("general", ListValue, "service_name", translate("Service")) svc:value("dyndns.org") svc:value("no-ip.com") svc:value("changeip.com") svc:value("zoneedit.com") s:taboption("general", Value, "username", translate("Username")) pw = s:taboption("general", Value, "password", translate("Password")) pw.password = true local dom = s:taboption("general", Value, "domain", translate("Hostname")) local current = s:taboption("general", DummyValue, "_current", "Current IP-Address") function current.render(self, section, ...) if dom:cfgvalue(section) then return DummyValue.render(self, section, ...) end end function current.value(self, section) local dns = nxo.getaddrinfo(dom:cfgvalue(section)) if dns then for _, v in ipairs(dns) do if v.family == "inet" then return v.address end end end return "" end s:tab("expert", translate("Expert Settings")) local src = s:taboption("expert", ListValue, "ip_source", "External IP Determination") src.default = "web" src:value("web", "CheckIP / WhatIsMyIP webservice") src:value("network", "External Address as seen locally") return m
apache-2.0
Dynosaur/dynosaur
system/modules/lualibs/socket/ltn12.lua
33
8589
----------------------------------------------------------------------------- -- LTN12 - Filters, sources, sinks and pumps. -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local table = require("table") local base = _G local _M = {} if module then -- heuristic for exporting a global package table ltn12 = _M end local filter,source,sink,pump = {},{},{},{} _M.filter = filter _M.source = source _M.sink = sink _M.pump = pump -- 2048 seems to be better in windows... _M.BLOCKSIZE = 2048 _M._VERSION = "LTN12 1.0.3" ----------------------------------------------------------------------------- -- Filter stuff ----------------------------------------------------------------------------- -- returns a high level filter that cycles a low-level filter function filter.cycle(low, ctx, extra) base.assert(low) return function(chunk) local ret ret, ctx = low(ctx, chunk, extra) return ret end end -- chains a bunch of filters together -- (thanks to Wim Couwenberg) function filter.chain(...) local arg = {...} local n = select('#',...) local top, index = 1, 1 local retry = "" return function(chunk) retry = chunk and retry while true do if index == top then chunk = arg[index](chunk) if chunk == "" or top == n then return chunk elseif chunk then index = index + 1 else top = top+1 index = top end else chunk = arg[index](chunk or "") if chunk == "" then index = index - 1 chunk = retry elseif chunk then if index == n then return chunk else index = index + 1 end else base.error("filter returned inappropriate nil") end end end end end ----------------------------------------------------------------------------- -- Source stuff ----------------------------------------------------------------------------- -- create an empty source local function empty() return nil end function source.empty() return empty end -- returns a source that just outputs an error function source.error(err) return function() return nil, err end end -- creates a file source function source.file(handle, io_err) if handle then return function() local chunk = handle:read(_M.BLOCKSIZE) if not chunk then handle:close() end return chunk end else return source.error(io_err or "unable to open file") end end -- turns a fancy source into a simple source function source.simplify(src) base.assert(src) return function() local chunk, err_or_new = src() src = err_or_new or src if not chunk then return nil, err_or_new else return chunk end end end -- creates string source function source.string(s) if s then local i = 1 return function() local chunk = string.sub(s, i, i+_M.BLOCKSIZE-1) i = i + _M.BLOCKSIZE if chunk ~= "" then return chunk else return nil end end else return source.empty() end end -- creates rewindable source function source.rewind(src) base.assert(src) local t = {} return function(chunk) if not chunk then chunk = table.remove(t) if not chunk then return src() else return chunk end else table.insert(t, chunk) end end end -- chains a source with one or several filter(s) function source.chain(src, f, ...) if ... then f=filter.chain(f, ...) end base.assert(src and f) local last_in, last_out = "", "" local state = "feeding" local err return function() if not last_out then base.error('source is empty!', 2) end while true do if state == "feeding" then last_in, err = src() if err then return nil, err end last_out = f(last_in) if not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end elseif last_out ~= "" then state = "eating" if last_in then last_in = "" end return last_out end else last_out = f(last_in) if last_out == "" then if last_in == "" then state = "feeding" else base.error('filter returned ""') end elseif not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end else return last_out end end end end end -- creates a source that produces contents of several sources, one after the -- other, as if they were concatenated -- (thanks to Wim Couwenberg) function source.cat(...) local arg = {...} local src = table.remove(arg, 1) return function() while src do local chunk, err = src() if chunk then return chunk end if err then return nil, err end src = table.remove(arg, 1) end end end ----------------------------------------------------------------------------- -- Sink stuff ----------------------------------------------------------------------------- -- creates a sink that stores into a table function sink.table(t) t = t or {} local f = function(chunk, err) if chunk then table.insert(t, chunk) end return 1 end return f, t end -- turns a fancy sink into a simple sink function sink.simplify(snk) base.assert(snk) return function(chunk, err) local ret, err_or_new = snk(chunk, err) if not ret then return nil, err_or_new end snk = err_or_new or snk return 1 end end -- creates a file sink function sink.file(handle, io_err) if handle then return function(chunk, err) if not chunk then handle:close() return 1 else return handle:write(chunk) end end else return sink.error(io_err or "unable to open file") end end -- creates a sink that discards data local function null() return 1 end function sink.null() return null end -- creates a sink that just returns an error function sink.error(err) return function() return nil, err end end -- chains a sink with one or several filter(s) function sink.chain(f, snk, ...) if ... then local args = { f, snk, ... } snk = table.remove(args, #args) f = filter.chain(unpack(args)) end base.assert(f and snk) return function(chunk, err) if chunk ~= "" then local filtered = f(chunk) local done = chunk and "" while true do local ret, snkerr = snk(filtered, err) if not ret then return nil, snkerr end if filtered == done then return 1 end filtered = f(done) end else return 1 end end end ----------------------------------------------------------------------------- -- Pump stuff ----------------------------------------------------------------------------- -- pumps one chunk from the source to the sink function pump.step(src, snk) local chunk, src_err = src() local ret, snk_err = snk(chunk, src_err) if chunk and ret then return 1 else return nil, src_err or snk_err end end -- pumps all data from a source to a sink, using a step function function pump.all(src, snk, step) base.assert(src and snk) step = step or pump.step while true do local ret, err = step(src, snk) if not ret then if err then return nil, err else return 1 end end end end return _M
gpl-3.0
gnosygnu/luaj_xowa
test/lua/errors.lua
7
6006
-- tostring replacement that assigns ids local ts,id,nid,types = tostring,{},0,{table='tbl',thread='thr',userdata='uda',['function']='func'} tostring = function(x) if not x or not types[type(x)] then return ts(x) end if not id[x] then nid=nid+1; id[x]=types[type(x)]..'.'..nid end return id[x] end -- test of common types of errors -- local function c(f,...) return f(...) end -- local function b(...) return c(...) end --local function a(...) return (pcall(b,...)) end local function a(...) local s,e=pcall(...) if s then return s,e else return false,type(e) end end s = 'some string' local t = {} -- error message tests print( 'a(error)', a(error) ) print( 'a(error,"msg")', a(error,"msg") ) print( 'a(error,"msg",0)', a(error,"msg",0) ) print( 'a(error,"msg",1)', a(error,"msg",1) ) print( 'a(error,"msg",2)', a(error,"msg",2) ) print( 'a(error,"msg",3)', a(error,"msg",3) ) print( 'a(error,"msg",4)', a(error,"msg",4) ) print( 'a(error,"msg",5)', a(error,"msg",5) ) print( 'a(error,"msg",6)', a(error,"msg",6) ) -- call errors print( 'a(nil())', a(function() return n() end) ) print( 'a(t()) ', a(function() return t() end) ) print( 'a(s()) ', a(function() return s() end) ) print( 'a(true())', a(function() local b = true; return b() end) ) -- arithmetic errors print( 'a(nil+1)', a(function() return nil+1 end) ) print( 'a(a+1) ', a(function() return a+1 end) ) print( 'a(s+1) ', a(function() return s+1 end) ) print( 'a(true+1)', a(function() local b = true; return b+1 end) ) -- table errors print( 'a(nil.x)', a(function() return n.x end) ) print( 'a(a.x) ', a(function() return a.x end) ) print( 'a(s.x) ', a(function() return s.x end) ) print( 'a(true.x)', a(function() local b = true; return b.x end) ) print( 'a(nil.x=5)', a(function() n.x=5 end) ) print( 'a(a.x=5) ', a(function() a.x=5 end) ) print( 'a(s.x=5) ', a(function() s.x=5 end) ) print( 'a(true.x=5)', a(function() local b = true; b.x=5 end) ) -- len operator print( 'a(#nil) ', a(function() return #n end) ) print( 'a(#t) ', a(function() return #t end) ) print( 'a(#s) ', a(function() return #s end) ) print( 'a(#a) ', a(function() return #a end) ) print( 'a(#true)', a(function() local b = true; return #b end) ) -- comparison errors print( 'a(nil>1)', a(function() return nil>1 end) ) print( 'a(a>1) ', a(function() return a>1 end) ) print( 'a(s>1) ', a(function() return s>1 end) ) print( 'a(true>1)', a(function() local b = true; return b>1 end) ) -- unary minus errors print( 'a(-nil)', a(function() return -n end) ) print( 'a(-a) ', a(function() return -a end) ) print( 'a(-s) ', a(function() return -s end) ) print( 'a(-true)', a(function() local b = true; return -b end) ) -- string concatenation local function concatsuite(comparefunc) print( '"a".."b"', comparefunc("a","b") ) print( '"a"..nil', comparefunc("a",nil) ) print( 'nil.."b"', comparefunc(nil,"b") ) print( '"a"..{}', comparefunc("a",{}) ) print( '{}.."b"', comparefunc({},"b") ) print( '"a"..2', comparefunc("a",2) ) print( '2.."b"', comparefunc(2,"b") ) print( '"a"..print', comparefunc("a",print) ) print( 'print.."b"', comparefunc(print,"b") ) print( '"a"..true', comparefunc("a",true) ) print( 'true.."b"', comparefunc(true,"b") ) print( 'nil..true', comparefunc(nil,true) ) print( '"a"..3.5', comparefunc("a",3.5) ) print( '3.5.."b"', comparefunc(3.5,"b") ) end local function strconcat(a,b) return (pcall( function() return a..b end) ) end local function tblconcat(a,b) local t={a,b} return (pcall( function() return table.concat(t,'-',1,2) end )) end print( '-------- string concatenation' ) concatsuite(strconcat) print( '-------- table concatenation' ) concatsuite(tblconcat) -- pairs print( '-------- pairs tests' ) print( 'a(pairs(nil))', a(function() return pairs(nil,{}) end) ) print( 'a(pairs(a)) ', a(function() return pairs(a,{}) end) ) print( 'a(pairs(s)) ', a(function() return pairs(s,{}) end) ) print( 'a(pairs(t)) ', a(function() return pairs(t,{}) end) ) print( 'a(pairs(true))', a(function() local b = true; return pairs(b,{}) end) ) -- setmetatable print( '-------- setmetatable tests' ) function sm(...) return tostring(setmetatable(...)) end print( 'a(setmetatable(nil))', a(function() return sm(nil,{}) end) ) print( 'a(setmetatable(a)) ', a(function() return sm(a,{}) end) ) print( 'a(setmetatable(s)) ', a(function() return sm(s,{}) end) ) print( 'a(setmetatable(true))', a(function() local b = true; return sm(b,{}) end) ) print( 'a(setmetatable(t)) ', a(function() return sm(t,{}) end) ) print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) ) print( 'a(setmetatable(t*)) ', a(function() return sm(t,{__metatable={}}) end) ) print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) ) print( 'a(setmetatable(t)) ', a(function() return sm(t,{}) end) ) print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) ) t = {} print( 'a(setmetatable(t)) ', a(function() return sm(t,{}) end) ) print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) ) print( 'a(setmetatable(t*)) ', a(function() return sm(t,{__metatable='some string'}) end) ) print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) ) print( 'a(setmetatable(t)) ', a(function() return sm(t,{}) end) ) print( 'a(getmetatable(t)) ', a(function() return getmetatable(t),type(getmetatable(t)) end) ) print( 'a(setmetatable(t,nil)) ', a(function() return sm(t,nil) end) ) print( 'a(setmetatable(t)) ', a(function() return sm(t) end) ) print( 'a(setmetatable({},"abc")) ', a(function() return sm({},'abc') end) ) -- bad args to error! print( 'error("msg","arg")', a(function() error('some message', 'some bad arg') end) ) -- loadfile, dofile on missing files print( 'loadfile("bogus.txt")', a(function() return loadfile("bogus.txt") end) ) print( 'dofile("bogus.txt")', a(function() return dofile("bogus.txt") end) )
mit
AdamGagorik/darkstar
scripts/zones/Port_Bastok/npcs/Kurando.lua
12
2343
----------------------------------- -- Area: Port Bastok -- NPC: Kurando -- Type: Quest Giver -- @zone: 236 -- @pos -23.887 3.898 0.870 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Bastok/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,FEAR_OF_FLYING) == QUEST_ACCEPTED) then if (trade:hasItemQty(4526,1) and trade:getItemCount() == 1) then player:startEvent(0x00AB); -- Quest Completion Dialogue end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local FearofFlying = player:getQuestStatus(BASTOK,FEAR_OF_FLYING); -- csid 0x00Ad ? if (FearofFlying == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >=3) then player:startEvent(0x00AA); -- Quest Start Dialogue elseif (FearofFlying == QUEST_COMPLETED) then player:startEvent(0x00AC); -- Dialogue after Completion else player:startEvent(0x001c); -- Default Dialogue 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 == 0x00AA) then player:addQuest(BASTOK,FEAR_OF_FLYING); elseif (csid == 0x00AB) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13113); else player:tradeComplete(); player:addItem(13113,1); player:messageSpecial(ITEM_OBTAINED,13113); player:setTitle(AIRSHIP_DENOUNCER); player:completeQuest(BASTOK,FEAR_OF_FLYING); player:addFame(BASTOK,30); end end end;
gpl-3.0
sjznxd/lc-20130204
contrib/luadoc/lua/luadoc/taglet/standard.lua
93
16319
------------------------------------------------------------------------------- -- @release $Id: standard.lua,v 1.39 2007/12/21 17:50:48 tomas Exp $ ------------------------------------------------------------------------------- local assert, pairs, tostring, type = assert, pairs, tostring, type local io = require "io" local posix = require "nixio.fs" local luadoc = require "luadoc" local util = require "luadoc.util" local tags = require "luadoc.taglet.standard.tags" local string = require "string" local table = require "table" module 'luadoc.taglet.standard' ------------------------------------------------------------------------------- -- Creates an iterator for an array base on a class type. -- @param t array to iterate over -- @param class name of the class to iterate over function class_iterator (t, class) return function () local i = 1 return function () while t[i] and t[i].class ~= class do i = i + 1 end local v = t[i] i = i + 1 return v end end end -- Patterns for function recognition local identifiers_list_pattern = "%s*(.-)%s*" local identifier_pattern = "[^%(%s]+" local function_patterns = { "^()%s*function%s*("..identifier_pattern..")%s*%("..identifiers_list_pattern.."%)", "^%s*(local%s)%s*function%s*("..identifier_pattern..")%s*%("..identifiers_list_pattern.."%)", "^()%s*("..identifier_pattern..")%s*%=%s*function%s*%("..identifiers_list_pattern.."%)", } ------------------------------------------------------------------------------- -- Checks if the line contains a function definition -- @param line string with line text -- @return function information or nil if no function definition found local function check_function (line) line = util.trim(line) local info = table.foreachi(function_patterns, function (_, pattern) local r, _, l, id, param = string.find(line, pattern) if r ~= nil then return { name = id, private = (l == "local"), param = { } --util.split("%s*,%s*", param), } end end) -- TODO: remove these assert's? if info ~= nil then assert(info.name, "function name undefined") assert(info.param, string.format("undefined parameter list for function `%s'", info.name)) end return info end ------------------------------------------------------------------------------- -- Checks if the line contains a module definition. -- @param line string with line text -- @param currentmodule module already found, if any -- @return the name of the defined module, or nil if there is no module -- definition local function check_module (line, currentmodule) line = util.trim(line) -- module"x.y" -- module'x.y' -- module[[x.y]] -- module("x.y") -- module('x.y') -- module([[x.y]]) -- module(...) local r, _, modulename = string.find(line, "^module%s*[%s\"'(%[]+([^,\"')%]]+)") if r then -- found module definition logger:debug(string.format("found module `%s'", modulename)) return modulename end return currentmodule end -- Patterns for constant recognition local constant_patterns = { "^()%s*([A-Z][A-Z0-9_]*)%s*=", "^%s*(local%s)%s*([A-Z][A-Z0-9_]*)%s*=", } ------------------------------------------------------------------------------- -- Checks if the line contains a constant definition -- @param line string with line text -- @return constant information or nil if no constant definition found local function check_constant (line) line = util.trim(line) local info = table.foreachi(constant_patterns, function (_, pattern) local r, _, l, id = string.find(line, pattern) if r ~= nil then return { name = id, private = (l == "local"), } end end) -- TODO: remove these assert's? if info ~= nil then assert(info.name, "constant name undefined") end return info end ------------------------------------------------------------------------------- -- Extracts summary information from a description. The first sentence of each -- doc comment should be a summary sentence, containing a concise but complete -- description of the item. It is important to write crisp and informative -- initial sentences that can stand on their own -- @param description text with item description -- @return summary string or nil if description is nil local function parse_summary (description) -- summary is never nil... description = description or "" -- append an " " at the end to make the pattern work in all cases description = description.." " -- read until the first period followed by a space or tab local summary = string.match(description, "(.-%.)[%s\t]") -- if pattern did not find the first sentence, summary is the whole description summary = summary or description return summary end ------------------------------------------------------------------------------- -- @param f file handle -- @param line current line being parsed -- @param modulename module already found, if any -- @return current line -- @return code block -- @return modulename if found local function parse_code (f, line, modulename) local code = {} while line ~= nil do if string.find(line, "^[\t ]*%-%-%-") then -- reached another luadoc block, end this parsing return line, code, modulename else -- look for a module definition modulename = check_module(line, modulename) table.insert(code, line) line = f:read() end end -- reached end of file return line, code, modulename end ------------------------------------------------------------------------------- -- Parses the information inside a block comment -- @param block block with comment field -- @return block parameter local function parse_comment (block, first_line, modulename) -- get the first non-empty line of code local code = table.foreachi(block.code, function(_, line) if not util.line_empty(line) then -- `local' declarations are ignored in two cases: -- when the `nolocals' option is turned on; and -- when the first block of a file is parsed (this is -- necessary to avoid confusion between the top -- local declarations and the `module' definition. if (options.nolocals or first_line) and line:find"^%s*local" then return end return line end end) -- parse first line of code if code ~= nil then local func_info = check_function(code) local module_name = check_module(code) local const_info = check_constant(code) if func_info then block.class = "function" block.name = func_info.name block.param = func_info.param block.private = func_info.private elseif const_info then block.class = "constant" block.name = const_info.name block.private = const_info.private elseif module_name then block.class = "module" block.name = module_name block.param = {} else block.param = {} end else -- TODO: comment without any code. Does this means we are dealing -- with a file comment? end -- parse @ tags local currenttag = "description" local currenttext table.foreachi(block.comment, function (_, line) line = util.trim_comment(line) local r, _, tag, text = string.find(line, "@([_%w%.]+)%s+(.*)") if r ~= nil then -- found new tag, add previous one, and start a new one -- TODO: what to do with invalid tags? issue an error? or log a warning? tags.handle(currenttag, block, currenttext) currenttag = tag currenttext = text else currenttext = util.concat(currenttext, line) assert(string.sub(currenttext, 1, 1) ~= " ", string.format("`%s', `%s'", currenttext, line)) end end) tags.handle(currenttag, block, currenttext) -- extracts summary information from the description block.summary = parse_summary(block.description) assert(string.sub(block.description, 1, 1) ~= " ", string.format("`%s'", block.description)) if block.name and block.class == "module" then modulename = block.name end return block, modulename end ------------------------------------------------------------------------------- -- Parses a block of comment, started with ---. Read until the next block of -- comment. -- @param f file handle -- @param line being parsed -- @param modulename module already found, if any -- @return line -- @return block parsed -- @return modulename if found local function parse_block (f, line, modulename, first) local block = { comment = {}, code = {}, } while line ~= nil do if string.find(line, "^[\t ]*%-%-") == nil then -- reached end of comment, read the code below it -- TODO: allow empty lines line, block.code, modulename = parse_code(f, line, modulename) -- parse information in block comment block, modulename = parse_comment(block, first, modulename) return line, block, modulename else table.insert(block.comment, line) line = f:read() end end -- reached end of file -- parse information in block comment block, modulename = parse_comment(block, first, modulename) return line, block, modulename end ------------------------------------------------------------------------------- -- Parses a file documented following luadoc format. -- @param filepath full path of file to parse -- @param doc table with documentation -- @return table with documentation function parse_file (filepath, doc, handle, prev_line, prev_block, prev_modname) local blocks = { prev_block } local modulename = prev_modname -- read each line local f = handle or io.open(filepath, "r") local i = 1 local line = prev_line or f:read() local first = true while line ~= nil do if string.find(line, "^[\t ]*%-%-%-") then -- reached a luadoc block local block, newmodname line, block, newmodname = parse_block(f, line, modulename, first) if modulename and newmodname and newmodname ~= modulename then doc = parse_file( nil, doc, f, line, block, newmodname ) else table.insert(blocks, block) modulename = newmodname end else -- look for a module definition local newmodname = check_module(line, modulename) if modulename and newmodname and newmodname ~= modulename then parse_file( nil, doc, f ) else modulename = newmodname end -- TODO: keep beginning of file somewhere line = f:read() end first = false i = i + 1 end if not handle then f:close() end if filepath then -- store blocks in file hierarchy assert(doc.files[filepath] == nil, string.format("doc for file `%s' already defined", filepath)) table.insert(doc.files, filepath) doc.files[filepath] = { type = "file", name = filepath, doc = blocks, -- functions = class_iterator(blocks, "function"), -- tables = class_iterator(blocks, "table"), } -- local first = doc.files[filepath].doc[1] if first and modulename then doc.files[filepath].author = first.author doc.files[filepath].copyright = first.copyright doc.files[filepath].description = first.description doc.files[filepath].release = first.release doc.files[filepath].summary = first.summary end end -- if module definition is found, store in module hierarchy if modulename ~= nil then if modulename == "..." then assert( filepath, "Can't determine name for virtual module from filepatch" ) modulename = string.gsub (filepath, "%.lua$", "") modulename = string.gsub (modulename, "/", ".") end if doc.modules[modulename] ~= nil then -- module is already defined, just add the blocks table.foreachi(blocks, function (_, v) table.insert(doc.modules[modulename].doc, v) end) else -- TODO: put this in a different module table.insert(doc.modules, modulename) doc.modules[modulename] = { type = "module", name = modulename, doc = blocks, -- functions = class_iterator(blocks, "function"), -- tables = class_iterator(blocks, "table"), author = first and first.author, copyright = first and first.copyright, description = "", release = first and first.release, summary = "", } -- find module description for m in class_iterator(blocks, "module")() do doc.modules[modulename].description = util.concat( doc.modules[modulename].description, m.description) doc.modules[modulename].summary = util.concat( doc.modules[modulename].summary, m.summary) if m.author then doc.modules[modulename].author = m.author end if m.copyright then doc.modules[modulename].copyright = m.copyright end if m.release then doc.modules[modulename].release = m.release end if m.name then doc.modules[modulename].name = m.name end end doc.modules[modulename].description = doc.modules[modulename].description or (first and first.description) or "" doc.modules[modulename].summary = doc.modules[modulename].summary or (first and first.summary) or "" end -- make functions table doc.modules[modulename].functions = {} for f in class_iterator(blocks, "function")() do if f and f.name then table.insert(doc.modules[modulename].functions, f.name) doc.modules[modulename].functions[f.name] = f end end -- make tables table doc.modules[modulename].tables = {} for t in class_iterator(blocks, "table")() do if t and t.name then table.insert(doc.modules[modulename].tables, t.name) doc.modules[modulename].tables[t.name] = t end end -- make constants table doc.modules[modulename].constants = {} for c in class_iterator(blocks, "constant")() do if c and c.name then table.insert(doc.modules[modulename].constants, c.name) doc.modules[modulename].constants[c.name] = c end end end if filepath then -- make functions table doc.files[filepath].functions = {} for f in class_iterator(blocks, "function")() do if f and f.name then table.insert(doc.files[filepath].functions, f.name) doc.files[filepath].functions[f.name] = f end end -- make tables table doc.files[filepath].tables = {} for t in class_iterator(blocks, "table")() do if t and t.name then table.insert(doc.files[filepath].tables, t.name) doc.files[filepath].tables[t.name] = t end end end return doc end ------------------------------------------------------------------------------- -- Checks if the file is terminated by ".lua" or ".luadoc" and calls the -- function that does the actual parsing -- @param filepath full path of the file to parse -- @param doc table with documentation -- @return table with documentation -- @see parse_file function file (filepath, doc) local patterns = { "%.lua$", "%.luadoc$" } local valid = table.foreachi(patterns, function (_, pattern) if string.find(filepath, pattern) ~= nil then return true end end) if valid then logger:info(string.format("processing file `%s'", filepath)) doc = parse_file(filepath, doc) end return doc end ------------------------------------------------------------------------------- -- Recursively iterates through a directory, parsing each file -- @param path directory to search -- @param doc table with documentation -- @return table with documentation function directory (path, doc) for f in posix.dir(path) do local fullpath = path .. "/" .. f local attr = posix.stat(fullpath) assert(attr, string.format("error stating file `%s'", fullpath)) if attr.type == "reg" then doc = file(fullpath, doc) elseif attr.type == "dir" and f ~= "." and f ~= ".." then doc = directory(fullpath, doc) end end return doc end -- Recursively sorts the documentation table local function recsort (tab) table.sort (tab) -- sort list of functions by name alphabetically for f, doc in pairs(tab) do if doc.functions then table.sort(doc.functions) end if doc.tables then table.sort(doc.tables) end end end ------------------------------------------------------------------------------- function start (files, doc) assert(files, "file list not specified") -- Create an empty document, or use the given one doc = doc or { files = {}, modules = {}, } assert(doc.files, "undefined `files' field") assert(doc.modules, "undefined `modules' field") table.foreachi(files, function (_, path) local attr = posix.stat(path) assert(attr, string.format("error stating path `%s'", path)) if attr.type == "reg" then doc = file(path, doc) elseif attr.type == "dir" then doc = directory(path, doc) end end) -- order arrays alphabetically recsort(doc.files) recsort(doc.modules) return doc end
apache-2.0
delram/inx
plugins/dic.lua
31
1662
--[[ -- Translate text using Google Translate. -- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello --]] do function translate(source_lang, target_lang, text) local path = "http://translate.google.com/translate_a/single" -- URL query parameters local params = { client = "t", ie = "UTF-8", oe = "UTF-8", hl = "en", dt = "t", tl = target_lang or "fa", sl = source_lang or "auto", text = URL.escape(text) } local query = format_http_params(params, true) local url = path..query local res, code = https.request(url) -- Return nil if error if code > 200 then return nil end local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "") return trans end function run(msg, matches) -- Third pattern if #matches == 1 then print("First") local text = matches[1] return translate(nil, nil, text) end -- Second pattern if #matches == 2 then print("Second") local target = matches[1] local text = matches[2] return translate(nil, target, text) end -- First pattern if #matches == 3 then print("Third") local source = matches[1] local target = matches[2] local text = matches[3] return translate(source, target, text) end end return { description = "Translate Text, Default Persian", usage = { "/dic (txt) : translate txt en to fa", "/dic (lang) (txt) : translate en to other", "/dic (lang1,lang2) (txt) : translate lang1 to lang2", }, patterns = { "^[!/]dic ([%w]+),([%a]+) (.+)", "^[!/]dic ([%w]+) (.+)", "^[!/]dic (.+)", }, run = run } end
gpl-2.0
AdamGagorik/darkstar
scripts/globals/mobskills/Prishe_Item_2.lua
53
1486
--------------------------------------------- -- Prishe Item 2 --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/zones/Empyreal_Paradox/TextIDs"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (target:hasStatusEffect(EFFECT_PHYSICAL_SHIELD) or target:hasStatusEffect(EFFECT_MAGIC_SHIELD)) then return 1; elseif (mob:hasStatusEffect(EFFECT_PLAGUE) or mob:hasStatusEffect(EFFECT_CURSE_I) or mob:hasStatusEffect(EFFECT_MUTE)) then return 0; elseif (math.random() < 0.25) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) skill:setMsg(0); if (mob:hasStatusEffect(EFFECT_PLAGUE) or mob:hasStatusEffect(EFFECT_CURSE_I) or mob:hasStatusEffect(EFFECT_MUTE)) then -- use Remedy! mob:messageText(mob, PRISHE_TEXT + 12, false); mob:delStatusEffect(EFFECT_PLAGUE); mob:delStatusEffect(EFFECT_CURSE_I); mob:delStatusEffect(EFFECT_MUTE); elseif (math.random() < 0.5) then -- Carnal Incense! mob:messageText(mob, PRISHE_TEXT + 10, false); mob:addStatusEffect(EFFECT_PHYSICAL_SHIELD, 0, 0, 30); else -- Spiritual Incense! mob:messageText(mob, PRISHE_TEXT + 11, false); mob:addStatusEffect(EFFECT_MAGIC_SHIELD, 0, 0, 30); end return 0; end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/mobskills/Corrosive_ooze.lua
34
1192
--------------------------------------------------- -- Corrosive Ooze -- Family: Slugs -- Description: Deals water damage to an enemy. Additional Effect: Attack Down and Defense Down. -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Radial -- Notes: --------------------------------------------------- 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 typeEffectOne = EFFECT_ATTACK_DOWN; local typeEffectTwo = EFFECT_DEFENSE_DOWN; local duration = 120; MobStatusEffectMove(mob, target, typeEffectOne, 15, 0, duration); MobStatusEffectMove(mob, target, typeEffectTwo, 15, 0, duration); local dmgmod = 1; local baseDamage = mob:getWeaponDmg()*4.2; local info = MobMagicalMove(mob,target,skill,baseDamage,ELE_WATER,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WATER,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Mount_Zhayolm/mobs/Brass_Borer.lua
29
1544
----------------------------------- -- Area: Mount Zhayolm -- MOB: Brass Borer ----------------------------------- require("scripts/globals/status"); -- TODO: Damage resistances in streched and curled stances. Halting movement during stance change. ----------------------------------- -- OnMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("formTime", os.time() + math.random(43,47)); end; ----------------------------------- -- onMobRoam Action -- Autochange stance ----------------------------------- function onMobRoam(mob) local roamTime = mob:getLocalVar("formTime"); if (mob:AnimationSub() == 0 and os.time() > roamTime) then mob:AnimationSub(1); mob:setLocalVar("formTime", os.time() + math.random(43,47)); elseif (mob:AnimationSub() == 1 and os.time() > roamTime) then mob:AnimationSub(0); mob:setLocalVar("formTime", os.time() + math.random(43,47)); end end; ----------------------------------- -- OnMobFight Action -- Stance change in battle ----------------------------------- function onMobFight(mob,target) local fightTime = mob:getLocalVar("formTime"); if (mob:AnimationSub() == 0 and os.time() > fightTime) then mob:AnimationSub(1); mob:setLocalVar("formTime", os.time() + math.random(43,47)); elseif (mob:AnimationSub() == 1 and os.time() > fightTime) then mob:AnimationSub(0); mob:setLocalVar("formTime", os.time() + math.random(43,47)); end end; function onMobDeath(mob) end;
gpl-3.0
rigeirani/bbb
plugins/stats.lua
8
4194
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'sultan' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /idetergent ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "sultan" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { usage = { "stats: Return Stats Group.", "statslist: Return Stats Group.", "stats group [id]: Return Stats Group[id].", "stats megasatan: Return Users And Groups Stats.", "megasatan: Return About Text.", }, patterns = { "^([Ss]tats)$", "^([Ss]tatslist)$", "^([Ss]tats) (group) (%d+)", "^([Ss]tats) (sultan)",-- Put everything you like :) "^([Ss]ultan)"-- Put everything you like :) }, run = run } end
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Qufim_Island/npcs/Singing_Blade_IM.lua
13
3326
----------------------------------- -- Area: Qufim Island -- NPC: Singing Blade, I.M. -- Type: Border Conquest Guards -- @pos 179.093 -21.575 -15.282 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; local csid = 0x7ff8; ----------------------------------- -- 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_SIGIL); player:delStatusEffect(EFFECT_SANCTION); 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
AdamGagorik/darkstar
scripts/zones/Port_Windurst/npcs/Ten_of_Clubs.lua
13
1054
----------------------------------- -- Area: Port Windurst -- NPC: Ten of Clubs -- Type: Standard NPC -- @zone: 240 -- @pos -229.393 -9.2 182.696 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x004b); 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
persandstrom/packages
net/acme/files/acme-cbi.lua
20
3086
--[[ LuCI - Lua Configuration Interface Copyright 2016 Toke Høiland-Jørgensen <toke@toke.dk> # This program 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 of the License, or (at your option) any later # version. ]]-- m = Map("acme", translate("ACME certificates"), translate("This configures ACME (Letsencrypt) automatic certificate installation. " .. "Simply fill out this to have the router configured with Letsencrypt-issued " .. "certificates for the web interface. " .. "Note that the domain names in the certificate must already be configured to " .. "point at the router's public IP address. " .. "Once configured, issuing certificates can take a while. " .. "Check the logs for progress and any errors.")) s = m:section(TypedSection, "acme", translate("ACME global config")) s.anonymous = true st = s:option(Value, "state_dir", translate("State directory"), translate("Where certs and other state files are kept.")) st.rmempty = false st.datatype = "directory" ae = s:option(Value, "account_email", translate("Account email"), translate("Email address to associate with account key.")) ae.rmempty = false ae.datatype = "minlength(1)" d = s:option(Flag, "debug", translate("Enable debug logging")) d.rmempty = false cs = m:section(TypedSection, "cert", translate("Certificate config")) cs.anonymous = false cs.addremove = true e = cs:option(Flag, "enabled", translate("Enabled")) e.rmempty = false us = cs:option(Flag, "use_staging", translate("Use staging server"), translate("Get certificate from the Letsencrypt staging server " .. "(use for testing; the certificate won't be valid).")) us.rmempty = false kl = cs:option(Value, "keylength", translate("Key length"), translate("Number of bits (minimum 2048).")) kl.rmempty = false kl.datatype = "and(uinteger,min(2048))" u = cs:option(Flag, "update_uhttpd", translate("Use for uhttpd"), translate("Update the uhttpd config with this certificate once issued " .. "(only select this for one certificate).")) u.rmempty = false wr = cs:option(Value, "webroot", translate("Webroot directory"), translate("Webserver root directory. Set this to the webserver " .. "document root to run Acme in webroot mode. The web " .. "server must be accessible from the internet on port 80.")) wr.rmempty = false dom = cs:option(DynamicList, "domains", translate("Domain names"), translate("Domain names to include in the certificate. " .. "The first name will be the subject name, subsequent names will be alt names. " .. "Note that all domain names must point at the router in the global DNS.")) dom.datatype = "list(string)" return m
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Mount_Zhayolm/npcs/qm4.lua
30
1342
----------------------------------- -- Area: Mount Zhayolm -- NPC: ??? (Spawn Khromasoul Bhurborlor(ZNM T3)) -- @pos 88 -22 70 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mount_Zhayolm/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 17027474; if (trade:hasItemQty(2585,1) and trade:getItemCount() == 1) then -- Trade Vinegar Pie if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end 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
AdamGagorik/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/Wooden_Ladder.lua
13
3273
----------------------------------- -- Area: Phomiuna Aqueducts -- NPC: Wooden Ladder -- @pos 101.9 -1.5 -101.9 -- @pos 101.948 -1.5 -18.016 -- @pos -61.888 -1.5 -18.079 -- @pos -218.109 -1.499 18.081 -- @pos -61.903 -1.5 138.099 -- @pos 21.901 -1.5 138.096 -- @pos 101.902 -1.5 181.902 -- @pos -159.32 -2.5 60 -- @pos -159.38 -22.559 60 -- @pos 199.317 -2.5 60 -- @pos 199.38 -22.559 60 -- @pos -200.679 -8.57 60 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Y = player:getYPos(); local Z = player:getZPos(); if ((X <= 107.9 and X >= 95.9) and (Y >= -1 and Y <= 1) and (Z >= -108.9 and Z <= -98)) then player:startEvent(0x0015); elseif ((X <= 107.9 and X >= 95.9) and (Y >= -1 and Y <= 1) and (Z >= -24 and Z <= -12)) then player:startEvent(0x0016); elseif ((X <= -55.888 and X >= -67.888) and (Y >= -1 and Y <= 1) and (Z >= -24 and Z <= -12)) then player:startEvent(0x0017); elseif ((X <= -212.1 and X >= -224.1) and (Y >= -1 and Y <= 1) and (Z >= 12 and Z <= 24)) then player:startEvent(0x0018); elseif ((X <= -55.9 and X >= -67.9) and (Y >= -1 and Y <= 1) and (Z >= 132 and Z <= 144)) then player:startEvent(0x0019); elseif ((X <= 27.9 and X >= 15.9) and (Y >= -1 and Y <= 1) and (Z >= 132 and Z <= 144)) then player:startEvent(0x001a); elseif ((X <= 107.9 and X >= 95.9) and (Y >= -1 and Y <= 1) and (Z >= 175.9 and Z <= 187.9)) then player:startEvent(0x001b); elseif ((X <= -153.3 and X >= -168.3) and (Y >= -2 and Y <= 0) and (Z >= 54 and Z <= 66)) then if (player:getCurrentMission(COP) == DISTANT_BELIEFS and player:getVar("PromathiaStatus") == 1) then player:setVar("PromathiaStatus",2); player:startEvent(0x0023); else player:startEvent(0x001c); end elseif ((X <= -153.3 and X >= -168.3) and (Y >= -24 and Y <= -22) and (Z >= 54 and Z <= 66)) then player:startEvent(0x001d); elseif ((X <= 205.3 and X >= 193.3) and (Y >= -2 and Y <= 0) and (Z >= 54 and Z <= 66)) then player:startEvent(0x001e); elseif ((X <= 205.3 and X >= 193.3) and (Y >= -24 and Y <= -22) and (Z >= 54 and Z <= 66)) then player:startEvent(0x001f); elseif ((X <= -194.6 and X >= -206.6) and (Y >= -8 and Y <= -6) and (Z >= 54 and Z <= 66)) then player:messageSpecial(DOOR_SEALED_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
AdamGagorik/darkstar
scripts/zones/Northern_San_dOria/npcs/Lotine.lua
13
1027
----------------------------------- -- Area: Northern San d'Oria -- NPC: Lotine -- Type: Standard Info NPC -- @zone: 231 -- @pos -137.504 11.999 171.090 -- ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) rand = math.random(1,2); if (rand == 1) then player:startEvent(0x028c); else player:startEvent(0x0290); 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
AdamGagorik/darkstar
scripts/zones/Everbloom_Hollow/Zone.lua
17
1071
----------------------------------- -- -- Zone: Everbloom_Hollow -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Everbloom_Hollow/TextIDs"] = nil; require("scripts/zones/Everbloom_Hollow/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; 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
paritoshmmmec/kong
spec/unit/tools/syslog_spec.lua
23
1838
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local syslog = require "kong.tools.syslog" local utils = require "kong.tools.utils" local UDP_PORT = 8889 describe("Syslog", function() it("should log", function() local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server -- Override constants constants.SYSLOG.ADDRESS = "127.0.0.1" constants.SYSLOG.PORT = UDP_PORT -- Make the request syslog.log({hello="world"}) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) local PRIORITY = "<14>" assert.truthy(stringy.startswith(res, PRIORITY)) res = string.sub(res, string.len(PRIORITY) + 1) local args = stringy.split(res, ";") assert.are.same(5, utils.table_size(args)) local has_uname = false local has_cores = false local has_hostname = false local has_hello = false local has_version = false for _, v in ipairs(args) do local parts = stringy.split(v, "=") if parts[1] == "uname" and parts[2] and parts[2] ~= "" then has_uname = true elseif parts[1] == "cores" and parts[2] and parts[2] ~= "" then has_cores = true elseif parts[1] == "hostname" and parts[2] and parts[2] ~= "" then has_hostname = true elseif parts[1] == "hello" and parts[2] and parts[2] == "world" then has_hello = true elseif parts[1] == "version" and parts[2] and parts[2] == constants.VERSION then has_version = true end end assert.truthy(has_uname) assert.truthy(has_hostname) assert.truthy(has_cores) assert.truthy(has_hello) assert.truthy(has_version) thread:join() -- wait til it exists end) end)
mit
wez2020/roh
bot/creedbot.lua
1
16637
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "Boobs", "Feedback", "plugins", "lock_join", "antilink", "antitag", "gps", "auto_leave", "cpu", "calc", "bin", "block", "tagall", "text", "info", "bot_on_off", "welcome", "webshot", "google", "sms", "anti_spam", "add_bot", "owners", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban" }, sudo_users = {114875538},--Sudo users disabled_channels = {}, realm = {},--Realms Id moderation = {data = 'data/moderation.json'}, about_text = [[tele TEL LAMON 2.3 Hello my Good friends ‼️ this bot is made by : @omidtarh 〰〰〰〰〰〰〰〰 ߔࠀ our admins are : ߔࠀ @omidtarh ߔࠀ @TURK_WOLF1 ߔࠀ @SHAH_TELEGRAM 〰〰〰〰〰〰〰〰 ♻️ You can send your Ideas and messages to Us By sending them into bots account by this command : تمامی درخواست ها و همه ی انتقادات و حرفاتونو با دستور زیر بفرستین به ما !feedback (your ideas and messages) ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group گروه جدیدی بسازید !createrealm [Name] Create a realm گروه مادر جدیدی بسازید !setname [Name] Set realm name اسم گروه مادر را تغییر بدهید !setabout [GroupID] [Text] Set a group's about text در مورد آن گروه توضیحاتی را بنویسید (ای دی گروه را بدهید ) !setrules [GroupID] [Text] Set a group's rules در مورد آن گروه قوانینی تعیین کنید ( ای دی گروه را بدهید ) !lock [GroupID] [setting] Lock a group's setting تنظیکات گروهی را قفل بکنید !unlock [GroupID] [setting] Unock a group's setting تنظیمات گروهی را از قفل در بیاورید !wholist Get a list of members in group/realm لیست تمامی اعضای گروه رو با ای دی شون نشون میده !who Get a file of members in group/realm لیست تمامی اعضای گروه را با ای دی در فایل متنی دریافت کنید !type Get group type در مورد نقش گروه بگیرید !kill chat [GroupID] Kick all memebers and delete group ⛔️⛔️ ⛔️تمامی اعضای گروه را حذف میکند ⛔️ !kill realm [RealmID] Kick all members and delete realm⛔️⛔️ تمامی اعضای گروه مارد را حذف میکند !addadmin [id|username] Promote an admin by id OR username *Sudo only ادمینی را اضافه بکنید !removeadmin [id|username] Demote an admin by id OR username *Sudo only❗️❗️ ❗️❗️ادمینی را با این دستور صلب مقام میکنید ❗️❗️ !list groups Get a list of all groups لیست تمامی گروه هارو میده !list realms Get a list of all realms لیست گروه های مادر را میدهد !log Get a logfile of current group or realm تمامی عملیات گروه را میدهد !broadcast [text] Send text to all groups ✉️ ✉️ با این دستور به تمامی گروه ها متنی را همزمان میفرستید . !br [group_id] [text] This command will send text to [group_id]✉️ با این دستور میتونید به گروه توسط ربات متنی را بفرستید You Can user both "!" & "/" for them میتوانید از هردوی کاراکتر های ! و / برای دستورات استفاده کنید ]], help_text = [[ RLMON Help for mods : Plugins Banhammer : Help For Banhammer دستوراتی برای کنترل گروه !Kick @UserName or ID شخصی را از گروه حذف کنید . همچنین با ریپلی هم میشه !Ban @UserName or ID برای بن کردن شخص اسفاده میشود . با ریپلی هم میشه !Unban @UserName برای آنبن کردن شخصی استفاده میشود . همچنین با ریپلی هم میشه For Admins : !banall ID برای بن گلوبال کردن از تمامی گروه هاست باید ای دی بدین با ریپلی هم میشه !unbanall ID برای آنبن کردن استفاده میشود ولی فقط با ای دی میشود 〰〰〰〰〰〰〰〰〰〰 2. GroupManager :  360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 برای بن کردن شخص اسفاده میشود . با ریپلی هم میشه !Unban @UserName برای آنبن کردن شخصی استفاده میشود . همچنین با ریپلی هم میشه For Admins : !banall ID برای بن گلوبال کردن از تمامی گروه هاست باید ای دی بدین با ریپلی هم میشه !unbanall ID برای آنبن کردن استفاده میشود ولی فقط با ای دی میشود 〰〰〰〰〰〰〰〰〰〰 2. GroupManager : !lock leave اگر کسی از گروه برود نمیتواند برگردد !lock tag برای مجوز ندادن به اعضا از استفاده کردن @ و # برای تگ !Creategp "GroupName" you can Create group with this comman با این دستور برای ساخت گروه استفاده بکنید !lock leave اگر کسی از گروه برود نمیتواند برگردد !lock tag برای مجوز ندادن به اعضا از استفاده کردن @ و # برای تگ !Creategp "GroupName" you can Create group with this comman با این دستور برای ساخت گروه استفاده بکنید !lock member For locking Inviting users برای جلوگیری از آمدن اعضای جدید استفاده میشود !lock bots for Locking Bots invitation برای جلوگیری از ادد کردن ربا استفاده میشود !lock name ❤️ To lock the group name for every bodey برای قفل کردن اسم استفاده میشود !setfloodߘ㊓et the group flood control߈銙囌زان اسپم را در گروه تعیین میکنید !settings ❌ Watch group settings تنظیمات فعلی گروه را میبینید !owner watch group owner آیدی سازنده گروه رو میبینید !setowner user_id❗️ You can set someone to the group owner‼️ برای گروه سازنده تعیین میکنید !modlist catch Group mods لیست مدیران گروه را میگیرید !lock join to lock joining the group by link برای جلوگیری از وارد شدن به کروه با لینک !lock flood⚠️ lock group flood از اسپم دادن در گروه جلوگیری کنید !unlock (bots-member-flood-photo-name-tag-link-join-Arabic)✅ Unlock Something موارد بالا را با این دستور آزاد میسازید !rules && !set rules TO see group rules or set rules برای دیدن قوانین گروه و یا انتخاب قوانین !about or !set about watch about group or set about در مورد توضیحات گروه میدهد و یا توضیحات گروه رو تعیین کنید !res @username see Username INfo در مورد اسم و ای دی شخص بهتون میده !who♦️ Get Ids Chat امی ای دی های موجود در چت رو بهتون میده !log get members id ♠️ تمامی فعالیت های انجام یافته توسط شما و یا مدیران رو نشون میده !all Says every thing he knows about a group در مورد تمامی اطلاعات ثبت شده در مورد گروه میدهد !newlink Changes or Makes new group link لینک گروه رو عوض میکنه !getlink gets The Group link لینک گروه را در گروه نمایش میده !linkpv sends the group link to the PV برای دریافت لینک در پیوی استفاده میشه 〰〰〰〰〰〰〰〰 Admins :® !add to add the group as knows برای مجوز دادن به ربات برای استفاده در گروه !rem to remove the group and be unknown برای ناشناس کردن گروه برای ربات توسط مدیران اصلی !setgpowner (Gpid) user_id ⚫️ For Set a Owner of group from realm برای تعیین سازنده ای برای گروه از گروه مادر !addadmin [Username] to add a Global admin to the bot برای ادد کردن ادمین اصلی ربات !removeadmin [username] to remove an admin from global admins برای صلب ادمینی از ادمینای اصلی !plugins - [plugins] To Disable the plugin برای غیر فعال کردن پلاگین توسط سازنده !plugins + [plugins] To enable a plugins برای فعال کردن چلاگین توسط سازنده !plugins ? To reload al plugins رای تازه سازی تمامی پلاگین های فعال !plugins Shows the list of all plugins لیست تمامی پلاگین هارو نشون میده !sms [id] (text) To send a message to an account by his/her ID برای فرستادن متنی توسط ربات به شخصی با ای دی اون 〰〰〰〰〰〰〰〰〰〰〰 3. Stats :© !stats creedbot (sudoers)✔️ To see the stats of creed bot برای دیدن آمار ربات !stats To see the group stats برای دیدن آمار گروه 〰〰〰〰〰〰〰〰 4. Feedback⚫️ !feedback (text) To send your ideas to the Moderation group برای فرستادن انتقادات و پیشنهادات و حرف خود با مدیر ها استفاده میشه 〰〰〰〰〰〰〰〰〰〰〰 5. Tagall◻️ !tagall (text) To tags the every one and sends your message at bottom تگ کردن همه ی اعضای گروه و نوشتن پیام شما زیرش 〰〰〰〰〰〰〰〰〰 More plugins soon ... ⚠️ We are Creeds ⚠️ مدیران : حسن کبیر امید ویزارد سروش ولف You Can user both "!" & "/" for them می توانید از دو شکلک ! و / برای دادن دستورات استفاده کنید ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Bastok_Mines/npcs/Tami.lua
12
2870
----------------------------------- -- Area: Bastok Mines -- NPC: Tami -- Starts & Finishes Repeatable Quest: Groceries -- Note: Repeatable until proper completion ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) ViewedNote = player:getVar("GroceriesViewedNote"); if (ViewedNote == 1) then count = trade:getItemCount(); MeatJerky = trade:hasItemQty(4376,1); if (MeatJerky == true and count == 1) then player:startEvent(0x0071); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Groceries = player:getQuestStatus(BASTOK,GROCERIES); GroceriesVar = player:getVar("Groceries"); if (Groceries == QUEST_COMPLETED) then player:startEvent(0x0073); elseif (Groceries == QUEST_AVAILABLE or GroceriesVar == 0) then player:startEvent(0x006e); elseif (GroceriesVar == 1) then player:showText(npc,10510); elseif (GroceriesVar == 2) then player:startEvent(0x0070); 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 == 0x006e) then Groceries = player:getQuestStatus(BASTOK,GROCERIES); if (Groceries == QUEST_AVAILABLE) then player:addQuest(BASTOK,GROCERIES); end player:addKeyItem(0x98); player:messageSpecial(KEYITEM_OBTAINED,0x98); player:setVar("Groceries",1); elseif (csid == 0x0070) then player:addFame(BASTOK,8); player:setVar("Groceries",0); player:addGil(GIL_RATE*10); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10); elseif (csid == 0x0071) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:tradeComplete(); player:setVar("Groceries",0); player:setVar("GroceriesViewedNote",0); player:completeQuest(BASTOK,GROCERIES); player:addFame(BASTOK,75); player:addItem(13594); player:messageSpecial(ITEM_OBTAINED,13594); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,13594); end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Abyssea-Altepa/npcs/Cavernous_Maw.lua
29
1099
----------------------------------- -- Area: Abyssea Altepa -- NPC: Cavernous Maw -- @pos 444.000 -0.500 320.000 218 -- Notes Teleports Players to South Gustaberg ----------------------------------- package.loaded["scripts/zones/Abyssea-Altepa/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C8); 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 == 0x00C8 and option == 1) then player:setPos(343,0,-679,199,107) end end;
gpl-3.0
hadirahimi1380/-AhRiMaN-
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
ioiasff/awqp
plugins/stats.lua
1
3985
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'deathbot' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /creedbot ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "deathbot" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^([Ss]tats)$", "^([Ss]tatslist)$", "^([Ss]tats) (group) (%d+)", "^([Ss]tats) (deathbot)",-- Put everything you like :) "^[!/]([Dd]eathbot)"-- Put everything you like :) }, run = run } end
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Rolanberry_Fields/Zone.lua
10
4860
----------------------------------- -- -- Zone: Rolanberry_Fields (110) -- ----------------------------------- package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Rolanberry_Fields/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/zone"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 4450, 30, DIGREQ_NONE }, { 4566, 7, DIGREQ_NONE }, { 768, 164, DIGREQ_NONE }, { 748, 15, DIGREQ_NONE }, { 846, 97, DIGREQ_NONE }, { 17396, 75, DIGREQ_NONE }, { 749, 45, DIGREQ_NONE }, { 739, 3, DIGREQ_NONE }, { 17296, 216, DIGREQ_NONE }, { 4448, 15, DIGREQ_NONE }, { 638, 82, DIGREQ_NONE }, { 106, 37, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 656, 200, DIGREQ_BURROW }, { 750, 100, DIGREQ_BURROW }, { 4375, 60, DIGREQ_BORE }, { 4449, 15, DIGREQ_BORE }, { 4374, 52, DIGREQ_BORE }, { 4373, 10, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17228375,17228376}; local book = GetNPCByID(17228375); local rift = GetNPCByID(17228385) book:setPos(-98,-9,-655,216) rift:setPos(-90.707,-7.899,-663.99,216) SetFieldManual(manuals); -- Simurgh SetRespawnTime(17228242, 900, 10800); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if ( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -381.747, -31.068, -788.092, 211); end if ( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow cs = 0x0002; elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x0004; end return cs; 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; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onGameHour ----------------------------------- function onGameHour() local vanadielHour = VanadielHour(); local silkCaterpillarId = 17227782; --Silk Caterpillar should spawn every 6 hours from 03:00 --this is approximately when the Jeuno-Bastok airship is flying overhead towards Jeuno. if (vanadielHour % 6 == 3 and GetMobAction(silkCaterpillarId) == ACTION_NONE) then -- Despawn set to 210 seconds (3.5 minutes, approx when the Jeuno-Bastok airship is flying back over to Bastok). SpawnMob(silkCaterpillarId, 210); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if ( csid == 0x0002) then lightCutsceneUpdate( player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x0004) then if (player:getZPos() < 75) then player:updateEvent(0,0,0,0,0,1); else player:updateEvent(0,0,0,0,0,2); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if ( csid == 0x0002) then lightCutsceneFinish( player); -- Quest: I Can Hear A Rainbow end end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/spells/aurorastorm.lua
32
1189
-------------------------------------- -- Spell: Aurorastorm -- Changes the weather around target party member to "auroras." -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) target:delStatusEffectSilent(EFFECT_FIRESTORM); target:delStatusEffectSilent(EFFECT_SANDSTORM); target:delStatusEffectSilent(EFFECT_RAINSTORM); target:delStatusEffectSilent(EFFECT_WINDSTORM); target:delStatusEffectSilent(EFFECT_HAILSTORM); target:delStatusEffectSilent(EFFECT_THUNDERSTORM); target:delStatusEffectSilent(EFFECT_AURORASTORM); target:delStatusEffectSilent(EFFECT_VOIDSTORM); local merit = caster:getMerit(MERIT_STORMSURGE); local power = 0; if merit > 0 then power = merit + caster:getMod(MOD_STORMSURGE_EFFECT) + 2; end target:addStatusEffect(EFFECT_AURORASTORM,power,0,180); return EFFECT_AURORASTORM; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Bhaflau_Remnants/Zone.lua
19
1071
----------------------------------- -- -- Zone: Bhaflau_Remnants -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Bhaflau_Remnants/TextIDs"] = nil; require("scripts/zones/Bhaflau_Remnants/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; 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
AdamGagorik/darkstar
scripts/zones/Yhoator_Jungle/npcs/Logging_Point.lua
13
1068
----------------------------------- -- Area: Yhoator Jungle -- NPC: Logging Point ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ------------------------------------- require("scripts/globals/logging"); require("scripts/zones/Yhoator_Jungle/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startLogging(player,player:getZoneID(),npc,trade,0x000A); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021); 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
luveti/Urho3D
bin/Data/LuaScripts/16_Chat.lua
18
7649
-- Chat example -- This sample demonstrates: -- - Starting up a network server or connecting to it -- - Implementing simple chat functionality with network messages require "LuaScripts/Utilities/Sample" -- Identifier for the chat network messages local MSG_CHAT = 32 -- UDP port we will use local CHAT_SERVER_PORT = 2345 local chatHistory = {} local chatHistoryText = nil local buttonContainer = nil local textEdit = nil local sendButton = nil local connectButton = nil local disconnectButton = nil local startServerButton = nil function Start() -- Execute the common startup for samples SampleStart() -- Enable OS cursor input.mouseVisible = true -- Create the user interface CreateUI() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_FREE) -- Subscribe to UI and network events SubscribeToEvents() end function CreateUI() SetLogoVisible(false) -- We need the full rendering window local uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") -- Set style to the UI root so that elements will inherit it ui.root.defaultStyle = uiStyle local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") chatHistoryText = ui.root:CreateChild("Text") chatHistoryText:SetFont(font, 12) buttonContainer = ui.root:CreateChild("UIElement") buttonContainer:SetFixedSize(graphics.width, 20) buttonContainer:SetPosition(0, graphics.height - 20) buttonContainer.layoutMode = LM_HORIZONTAL textEdit = buttonContainer:CreateChild("LineEdit") textEdit:SetStyleAuto() sendButton = CreateButton("Send", 70) connectButton = CreateButton("Connect", 90) disconnectButton = CreateButton("Disconnect", 100) startServerButton = CreateButton("Start Server", 110) UpdateButtons() local size = (graphics.height - 20) / chatHistoryText.rowHeight for i = 1, size do table.insert(chatHistory, "") end -- No viewports or scene is defined. However, the default zone's fog color controls the fill color renderer.defaultZone.fogColor = Color(0.0, 0.0, 0.1) end function SubscribeToEvents() -- Subscribe to UI element events SubscribeToEvent(textEdit, "TextFinished", "HandleSend") SubscribeToEvent(sendButton, "Released", "HandleSend") SubscribeToEvent(connectButton, "Released", "HandleConnect") SubscribeToEvent(disconnectButton, "Released", "HandleDisconnect") SubscribeToEvent(startServerButton, "Released", "HandleStartServer") -- Subscribe to log messages so that we can pipe them to the chat window SubscribeToEvent("LogMessage", "HandleLogMessage") -- Subscribe to network events SubscribeToEvent("NetworkMessage", "HandleNetworkMessage") SubscribeToEvent("ServerConnected", "HandleConnectionStatus") SubscribeToEvent("ServerDisconnected", "HandleConnectionStatus") SubscribeToEvent("ConnectFailed", "HandleConnectionStatus") end function CreateButton(text, width) local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") local button = buttonContainer:CreateChild("Button") button:SetStyleAuto() button:SetFixedWidth(width) local buttonText = button:CreateChild("Text") buttonText:SetFont(font, 12) buttonText:SetAlignment(HA_CENTER, VA_CENTER) buttonText.text = text return button end function ShowChatText(row) table.remove(chatHistory, 1) table.insert(chatHistory, row) -- Concatenate all the rows in history local allRows = "" for i, r in ipairs(chatHistory) do allRows = allRows .. r .. "\n" end chatHistoryText.text = allRows end function UpdateButtons() local serverConnection = network.serverConnection local serverRunning = network.serverRunning -- Show and hide buttons so that eg. Connect and Disconnect are never shown at the same time sendButton.visible = serverConnection ~= nil connectButton.visible = (serverConnection == nil) and (not serverRunning) disconnectButton.visible = (serverConnection ~= nil) or serverRunning startServerButton.visible = (serverConnection == nil) and (not serverRunning) end function HandleLogMessage(eventType, eventData) ShowChatText(eventData["Message"]:GetString()) end function HandleSend(eventType, eventData) local text = textEdit.text if text == "" then return -- Do not send an empty message end local serverConnection = network.serverConnection if serverConnection ~= nil then -- A VectorBuffer object is convenient for constructing a message to send local msg = VectorBuffer() msg:WriteString(text) -- Send the chat message as in-order and reliable serverConnection:SendMessage(MSG_CHAT, true, true, msg) -- Empty the text edit after sending textEdit.text = "" end end function HandleConnect(eventType, eventData) local address = textEdit.text if address == "" then address = "localhost" -- Use localhost to connect if nothing else specified end -- Empty the text edit after reading the address to connect to textEdit.text = "" -- Connect to server, do not specify a client scene as we are not using scene replication, just messages. -- At connect time we could also send identity parameters (such as username) in a VariantMap, but in this -- case we skip it for simplicity network:Connect(address, CHAT_SERVER_PORT, nil) UpdateButtons() end function HandleDisconnect(eventType, eventData) local serverConnection = network.serverConnection -- If we were connected to server, disconnect if serverConnection ~= nil then serverConnection:Disconnect() -- Or if we were running a server, stop it else if network.serverRunning then network:StopServer() end end UpdateButtons() end function HandleStartServer(eventType, eventData) network:StartServer(CHAT_SERVER_PORT) UpdateButtons() end function HandleNetworkMessage(eventType, eventData) local msgID = eventData["MessageID"]:GetInt() if msgID == MSG_CHAT then local msg = eventData["Data"]:GetBuffer() local text = msg:ReadString() -- If we are the server, prepend the sender's IP address and port and echo to everyone -- If we are a client, just display the message if network.serverRunning then local sender = eventData["Connection"]:GetPtr("Connection") text = sender:ToString() .. " " .. text local sendMsg = VectorBuffer() sendMsg:WriteString(text) -- Broadcast as in-order and reliable network:BroadcastMessage(MSG_CHAT, true, true, sendMsg) end ShowChatText(text) end end function HandleConnectionStatus(eventType, eventData) UpdateButtons() end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button2']]\">" .. " <attribute name=\"Is Visible\" value=\"false\" />" .. " </add>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" .. " <attribute name=\"Is Visible\" value=\"false\" />" .. " </add>" .. "</patch>" end
mit
robertfoss/nodemcu-firmware
app/cjson/tests/bench.lua
145
3247
#!/usr/bin/env lua -- This benchmark script measures wall clock time and should be -- run on an unloaded system. -- -- Your Mileage May Vary. -- -- Mark Pulford <mark@kyne.com.au> local json_module = os.getenv("JSON_MODULE") or "cjson" require "socket" local json = require(json_module) local util = require "cjson.util" local function find_func(mod, funcnames) for _, v in ipairs(funcnames) do if mod[v] then return mod[v] end end return nil end local json_encode = find_func(json, { "encode", "Encode", "to_string", "stringify", "json" }) local json_decode = find_func(json, { "decode", "Decode", "to_value", "parse" }) local function average(t) local total = 0 for _, v in ipairs(t) do total = total + v end return total / #t end function benchmark(tests, seconds, rep) local function bench(func, iter) -- Use socket.gettime() to measure microsecond resolution -- wall clock time. local t = socket.gettime() for i = 1, iter do func(i) end t = socket.gettime() - t -- Don't trust any results when the run lasted for less than a -- millisecond - return nil. if t < 0.001 then return nil end return (iter / t) end -- Roughly calculate the number of interations required -- to obtain a particular time period. local function calc_iter(func, seconds) local iter = 1 local rate -- Warm up the bench function first. func() while not rate do rate = bench(func, iter) iter = iter * 10 end return math.ceil(seconds * rate) end local test_results = {} for name, func in pairs(tests) do -- k(number), v(string) -- k(string), v(function) -- k(number), v(function) if type(func) == "string" then name = func func = _G[name] end local iter = calc_iter(func, seconds) local result = {} for i = 1, rep do result[i] = bench(func, iter) end -- Remove the slowest half (round down) of the result set table.sort(result) for i = 1, math.floor(#result / 2) do table.remove(result, 1) end test_results[name] = average(result) end return test_results end function bench_file(filename) local data_json = util.file_load(filename) local data_obj = json_decode(data_json) local function test_encode() json_encode(data_obj) end local function test_decode() json_decode(data_json) end local tests = {} if json_encode then tests.encode = test_encode end if json_decode then tests.decode = test_decode end return benchmark(tests, 0.1, 5) end -- Optionally load any custom configuration required for this module local success, data = pcall(util.file_load, ("bench-%s.lua"):format(json_module)) if success then util.run_script(data, _G) configure(json) end for i = 1, #arg do local results = bench_file(arg[i]) for k, v in pairs(results) do print(("%s\t%s\t%d"):format(arg[i], k, v)) end end -- vi:ai et sw=4 ts=4:
mit
iotcafe/nodemcu-firmware
app/cjson/tests/bench.lua
145
3247
#!/usr/bin/env lua -- This benchmark script measures wall clock time and should be -- run on an unloaded system. -- -- Your Mileage May Vary. -- -- Mark Pulford <mark@kyne.com.au> local json_module = os.getenv("JSON_MODULE") or "cjson" require "socket" local json = require(json_module) local util = require "cjson.util" local function find_func(mod, funcnames) for _, v in ipairs(funcnames) do if mod[v] then return mod[v] end end return nil end local json_encode = find_func(json, { "encode", "Encode", "to_string", "stringify", "json" }) local json_decode = find_func(json, { "decode", "Decode", "to_value", "parse" }) local function average(t) local total = 0 for _, v in ipairs(t) do total = total + v end return total / #t end function benchmark(tests, seconds, rep) local function bench(func, iter) -- Use socket.gettime() to measure microsecond resolution -- wall clock time. local t = socket.gettime() for i = 1, iter do func(i) end t = socket.gettime() - t -- Don't trust any results when the run lasted for less than a -- millisecond - return nil. if t < 0.001 then return nil end return (iter / t) end -- Roughly calculate the number of interations required -- to obtain a particular time period. local function calc_iter(func, seconds) local iter = 1 local rate -- Warm up the bench function first. func() while not rate do rate = bench(func, iter) iter = iter * 10 end return math.ceil(seconds * rate) end local test_results = {} for name, func in pairs(tests) do -- k(number), v(string) -- k(string), v(function) -- k(number), v(function) if type(func) == "string" then name = func func = _G[name] end local iter = calc_iter(func, seconds) local result = {} for i = 1, rep do result[i] = bench(func, iter) end -- Remove the slowest half (round down) of the result set table.sort(result) for i = 1, math.floor(#result / 2) do table.remove(result, 1) end test_results[name] = average(result) end return test_results end function bench_file(filename) local data_json = util.file_load(filename) local data_obj = json_decode(data_json) local function test_encode() json_encode(data_obj) end local function test_decode() json_decode(data_json) end local tests = {} if json_encode then tests.encode = test_encode end if json_decode then tests.decode = test_decode end return benchmark(tests, 0.1, 5) end -- Optionally load any custom configuration required for this module local success, data = pcall(util.file_load, ("bench-%s.lua"):format(json_module)) if success then util.run_script(data, _G) configure(json) end for i = 1, #arg do local results = bench_file(arg[i]) for k, v in pairs(results) do print(("%s\t%s\t%d"):format(arg[i], k, v)) end end -- vi:ai et sw=4 ts=4:
mit
mynameiscraziu/karizma
plugins/anti_spam.lua
30
4161
do local NUM_MSG_MAX = 4 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood local kick = chat_del_user(chat_id , user_id, ok_cb, true) vardump(kick) if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false) print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
AdamGagorik/darkstar
scripts/zones/East_Ronfaure/npcs/Signpost.lua
13
2313
----------------------------------- -- Area: East Ronfaure -- NPC: Signpost -- Involved in Quest: To Cure a Cough -- @pos 257 -45 212 101 ----------------------------------- package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/East_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Z = player:getZPos(); if ((X > 251.6 and X < 263.6) and (Z < 219.7 and Z > 207.7)) then if (player:hasKeyItem(SCROLL_OF_TREASURE) == true) then player:startEvent(20); player:delKeyItem(SCROLL_OF_TREASURE); player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); else player:startEvent(5); end elseif ((X > 434.9 and X < 446.9) and (Z < 148.4 and Z > 136.4)) then player:startEvent(3); elseif ((X > 652.2 and X < 664.2) and (Z < 311.5 and Z > 299.5)) then player:startEvent(7); elseif ((X > 459.2 and X < 471.2) and (Z < -167.4 and Z > -179.4)) then player:startEvent(9); elseif ((X > 532 and X < 544) and (Z < -378.2 and Z > -390.2)) then player:startEvent(11); elseif ((X > 273.1 and X < 285.1) and (Z < -251.6 and Z > -263.6)) then player:startEvent(13); elseif ((X > 290.5 and X < 302.5) and (Z < -451.1 and Z > -463.1)) then player:startEvent(15); elseif ((X > 225.1 and X < 237.1) and (Z < 68.6 and Z > 56.6)) then player:startEvent(17); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID: %u",csid); --print("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Meriphataud_Mountains/npcs/Beastmen_s_Banner.lua
13
1028
----------------------------------- -- Area: Meriphataud_Mountains -- NPC: Beastmen_s_Banner -- @pos 592.850 -16.765 -518.802 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Meriphataud_Mountains/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(BEASTMEN_BANNER); 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); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/LaLoff_Amphitheater/mobs/Ark_Angel_s_Mandragora.lua
8
1252
----------------------------------- -- Area: LaLoff Amphitheater -- MOB: Ark Angel's Mandragora ----------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ----------------------------------- require("scripts/zones/LaLoff_Amphitheater/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- TODO: Determine spell list and behavior. Potentially includes Breakga and Bindga, unless they're TP moves. -- TODO: Implement shared spawn and victory conditions with Ark Angel's Tiger. ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local mobid = mob:getID() for member = mobid-3, mobid+4 do if (GetMobAction(member) == 16) then GetMobByID(member):updateEnmity(target); end end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath Action ----------------------------------- function onMobDeath(mob,killer,ally) end;
gpl-3.0
AdamGagorik/darkstar
scripts/commands/changesjob.lua
3
1883
--------------------------------------------------------------------------------------------------- -- func: changesjob -- desc: Changes the players current subjob. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "si" }; function onTrigger(player, job, level) local jobList = { ["war"] = 1, ["mnk"] = 2, ["whm"] = 3, ["blm"] = 4, ["rdm"] = 5, ["thf"] = 6, ["pld"] = 7, ["drk"] = 8, ["bst"] = 9, ["brd"] = 10, ["rng"] = 11, ["sam"] = 12, ["nin"] = 13, ["drg"] = 14, ["smn"] = 15, ["blu"] = 16, ["cor"] = 17, ["pup"] = 18, ["dnc"] = 19, ["sch"] = 20, ["geo"] = 21, ["run"] = 22 }; if (job == nil) then player:PrintToPlayer("You must enter a job id or short-name."); return; end local jobId = 0; if (tonumber(job) ~= nil and tonumber(job) ~= 0) then jobId = job; else jobId = jobList[ string.lower( job ) ]; if (jobId == nil) then player:PrintToPlayer( string.format( "Invalid job '%s' given. Use short name or id. e.g. WAR", job ) ); return; end end -- Ensure player entered a valid id.. if (jobId <= 0 or jobId > 22) then player:PrintToPlayer( "Invalid job id given; must be between 1 and 22. Or use a short name e.g. WAR" ); return; end -- Change the players subjob.. player:changesJob( jobId ); -- Attempt to set the players subjob level.. if (level ~= nil and level > 0 and level <= 99) then player:setsLevel( level ); else player:PrintToPlayer( "Invalid level given. Level must be between 1 and 99!" ); end end
gpl-3.0
AdamGagorik/darkstar
scripts/globals/abilities/shikikoyo.lua
11
1076
----------------------------------- -- Ability: Shikikoyo -- Share TP above 1000 with a party member. -- Obtained: Samurai Level 75 -- Recast Time: 5:00 -- Duration: Instant -- Target: Party member, cannot target self. ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/utils"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getID() == target:getID()) then return MSGBASIC_CANNOT_PERFORM_TARG,0; elseif (player:getTP() < 1000) then return MSGBASIC_NOT_ENOUGH_TP, 0; else return 0,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) local pTP = player:getTP() - 1000 + (player:getMerit(MERIT_SHIKIKOYO) - 12); pTP = utils.clamp(pTP, 0, 3000 - target:getTP()); player:setTP(1000); target:setTP(target:getTP() + pTP); return pTP; end;
gpl-3.0
Nathan22Miles/sile
languages/cs.lua
4
32886
SILE.hyphenator.languages["cs"] = {}; SILE.hyphenator.languages["cs"].patterns = { ".a2", ".a4da", ".a4de", ".a4di", ".a4do", ".a4dé", ".a4kl", ".a4ko", ".a4kr", ".a4ku", ".ale3x", ".a4ra", ".a4re", ".a4ri", ".a4ro", ".a4ry", ".a4rá", ".a4sa", ".a4se", ".a4so", ".as3t3", ".a4sy", ".a4ta", ".a4te", ".at3l", ".a4to", ".a4tr", ".a4ty", ".a4ve", ".b2", ".c2", ".ch2", ".cyk3", ".d2", ".dez3", ".d4na", ".dne4", ".dneš4k", ".d4ny", ".dos4", ".d4ve", ".d4vě", ".d4ví", ".e2", ".e4ch", ".e4ko", ".es3k", ".es3t", ".e4ve", ".f4ri", ".g2", ".h2", ".h4le", ".h4ne", ".i2", ".i4na", ".i4ni", ".i4no", ".is3l", ".j2", ".j4ak", ".je4dl", ".j4se", ".j4zd", ".jád4", ".k2", ".k4li", ".k4ly", ".kří3d", ".l2", ".le4gr", ".li3kv", ".m2", ".mi3st4", ".moud3", ".na3č4", ".ne3c", ".neč4", ".ne3š", ".ni2t", ".no4s3t", ".n4vp", ".ná1", ".nář4k", ".o2", ".o4bé", ".ode3", ".od3l", ".od3rá", ".o4ka", ".o4ko", ".o4na", ".o4ne", ".o4ni", ".o4no", ".o4nu", ".o4ny", ".o4ně", ".o4ní", ".o4pe", ".o4po", ".o4se", ".o4sl", ".os4to", ".os3t3r", ".os4tě", ".ot3rá", ".ot3v", ".o4tí", ".o4tř", ".ově4t", ".o4za", ".oz3do", ".o4zi", ".o4zo", ".o4zu", ".o4šk", ".o4šl", ".o4ži", ".p2", ".pa4re", ".pa3tř", ".polk4l", ".po3č4", ".p4ro", ".p4rý", ".p4se", ".pu3b", ".r2", ".rej4", ".re3s", ".ro4k", ".roze3", ".roz3r", ".ru4dl", ".s2", ".s4ch", ".s4ci", ".sem4", ".se3pn", ".s4ke", ".sk4l", ".s4ká", ".s4le", ".s4na", ".s4ny", ".s4pe", ".s4po", ".st2", ".s4tá", ".s4ži", ".t2", ".u2", ".u4ba", ".u4be", ".u4bi", ".u4bo", ".u4de", ".u4di", ".u4do", ".u4du", ".u4dí", ".uh4n", ".uj4m", ".u4ko", ".u4ku", ".ul4h", ".u4ma", ".u4me", ".u4mi", ".u4mu", ".u4ne", ".u4ni", ".u4pa", ".u4pe", ".u4pi", ".up4n", ".u4po", ".u4pu", ".u4pá", ".u4pě", ".u4pí", ".u4ra", ".u4ro", ".u4rá", ".us2", ".u4so", ".u4st", ".u4sy", ".u4sí", ".ut2", ".u4vi", ".u4ze", ".u4če", ".u4či", ".u4čí", ".u4še", ".u4ši", ".u4šk", ".uš4t", ".u4ší", ".u4ži", ".už4n", ".u4žo", ".u4ží", ".v2", ".va4dl", ".v4po", ".vy3", ".v4zá", ".vý1", ".v4ži", ".y4or", ".y4ve", ".z2", ".za3", ".zao3s", ".zar2", ".zač2", ".zd2", ".z4di", ".z4dr", ".z4ky", ".z4mn", ".z4no", ".z4nu", ".z4ně", ".z4ní", ".z4pe", ".z4po", ".z4tř", ".z4ve", ".z4vi", ".č2", ".č4te", ".é2", ".í2", ".ó2", ".š2", ".še3t", ".š4ka", ".š4ke", ".š4ky", ".š4ťo", ".š4ťá", ".ú2", ".ú4dů", ".ž2", "a1", "2a.", "aa3t2", "ab3lon", "ab4lý", "ab3ri", "ab4sb", "ab2st", "ac4ci", "a2d", "a3da", "a3de", "a3di", "ad2la", "a4dli", "a4dlá", "a4dlé", "ad4me", "ad4mu", "a3do", "ado4s", "a3d3ra", "ad3ri", "a3drž", "a3du", "a4duž", "3a3dva", "ad3vo", "a3dy", "a3dá", "a3dé", "a3dě", "a3dí", "ad4úz", "ad4úř", "a3dů", "a3dý", "ae4vi", "afi2a", "a2g", "a3ga", "ag4fa", "a3go", "ag3ro", "a3gu", "a3gá", "ah4li", "ah3v", "a2i", "a3in", "ai4re", "a3iv", "a2jd", "a2jm", "aj4me", "aj2o", "a2k", "a3ke", "a3ki", "a3kl", "ak4ni", "a3ko", "a3kr", "a3ku", "a3ky", "a3ká", "a3ké", "a3kó", "a3ků", "a3ký", "al4fb", "al4kl", "al4tz", "al3ží", "am4bd", "am4kl", "am4nu", "amo3s", "am4ži", "a4nae", "a4name", "an4dt", "ane4sk", "aneu4", "an4sc", "an4sg", "an4sl", "an4sm", "an2sp", "an4sv", "an4tč", "an4žh", "ao4ed", "ao4hm", "ao4stř", "ao4tč", "ap4r.", "a4pso", "ap3t", "a4př.", "a2r", "a3ra", "ar4dw", "a3re", "a4rer", "ar4gl", "a3ri", "ar4kh", "a3ro", "a4rox", "ar3st", "a3ru", "ar2va", "a3ry", "a3rá", "a3ró", "ar3š2", "ar4šr", "a3rů", "arůs3", "a3rý", "a2s", "a3sa", "a3se", "a3sh", "a3sin", "as3ná", "a3so", "as3pi", "as4tat", "a4stk", "as4tm", "a4stru.", "as3tv", "a3su", "a3sv", "a3sy", "a3sá", "a3sé", "a3sí", "a3sů", "a2t", "a3ta", "at4ch", "a3te", "a3ti", "a4tio", "at4kl", "at3lo", "a3to", "a3tr", "at3re", "at3ron", "at3rov", "a4tru", "at4rá", "at4th", "a3tu", "a3tv", "a3ty", "a3tá", "a3té", "a3tě", "a3tí", "a3tó", "at1ř", "a4tří.", "a3tů", "a3tý", "a2u", "au4gs", "a3uj", "auj4m", "aus3t", "a3uč", "2av", "av3d", "av4d.", "av3lo", "a4vlu", "a4vlí", "av3t", "av4ti", "2ay", "ay4on", "az3k", "az3la", "az4lé", "az3ni", "a3zp", "a2č", "a3ča", "a3če", "a3či", "a3čl", "ač4má", "a3čo", "a3ču", "a3čá", "a3čí", "a3čů", "a2ň", "a3ňo", "a3ňu", "aře4k", "a3ří", "a4špl", "a4špy", "a2ť", "aú3t", "2b.", "3ba.", "ba4br", "ba4chr", "ba3ka", "ba4se", "2b1c", "b1d", "be4ef", "be4et", "bej4m", "be3p", "beu4r", "be2z3", "beze3", "b1h", "1bi", "bi2b3", "bis3", "bist4", "bi4tr", "b1j", "2bk", "3bl.", "bl4bl", "b2lem", "b2les", "3blk", "b4lán", "b2lém", "b1m", "2bn", "1bo", "bo4et", "bo4jm", "bo4ok", "bo4tr", "bou3s", "bo4šk", "b2ral", "b2ran", "2bri", "b4rodit", "b4rou", "broz4", "b2ru", "b3ru.", "b3rub", "b2rán", "2b1s2", "bs3tr", "2b1t", "btáh4", "bu2c", "bu4en", "3by.", "bys3", "by4sm", "by4tč", "by4zn", "b2z", "1bá", "2b1č", "bé4rc", "1bě.", "bě3ta", "1bí", "3bín", "bí4rc", "2bň", "b3řa", "b3ře.", "bře4s", "b1ří", "2bš2", "2c.", "1ca", "cad4l", "ca4es", "2cc", "1ce", "cech4", "ced4l", "celo3", "ce4ns", "ce4ov", "ce4ps", "cer4v", "ce2u", "2ch.", "1cha", "4chalg", "3che", "4che.", "2chl", "ch4ly", "ch4mb", "2ch3n", "2cht", "4chte", "1chu", "ch4u.", "1chy", "1chá", "2chř", "1ci", "cien4c", "cik4l", "2ck2", "c4ket", "ckte4rý", "2cl", "c3la", "c3lé", "2cn", "1co", "co4at", "co4mm", "co4žp", "c2p", "2ct", "c2ti", "ctis4", "ct4la", "ct2n", "c3tv", "c2tě", "cuk1", "1c2v", "cy2", "1cá", "1cí", "cí4pl", "2cň", "1ců", "2d.", "1da", "da3d", "da4jš", "da4kl", "da4tr", "d1b", "d2ba", "4dbat.", "d2bá", "2d1c", "dch4l", "3dch4n", "d1d", "dd4ha", "1de", "de4bre", "de3hn", "de3jd", "dej4mo", "de3kl", "de3kv", "de2na", "de2oz", "de3sl", "de4sm", "de4so", "de2sp", "des4t", "de3str", "de1x", "de4xt", "de2z", "de3zn", "dez3o", "de3čt", "de4žp", "2d1h", "1di", "di4gg", "4dind", "dis3k", "di4so", "d1j", "dj4us", "2dk", "d3kv", "3dl.", "d1la", "d4lab", "d4lak", "d3li", "1dln", "d2lou", "d3lou.", "d2lu", "d3luč", "d4láž", "d1lé", "2d1lí", "d2lů", "d1m", "1dmd", "dmýš4", "2dn", "1do", "4dobl", "4doboj", "dob4rat", "do3by", "do3bě", "do3bý", "do1d", "4do4dd", "4do4dj", "dod4n", "do3h", "doj4m", "4dokn", "4doly", "do3mn", "domoh4", "do3p", "do4pc", "dop4n", "dor2v", "do1s", "dos4p", "dos4tiv", "do3t", "do3uk", "do3uč", "do3z2", "doz4n", "do3č", "4do4čn", "doč4t", "do4žp", "4dran", "d4rap", "d1re", "d4ren", "3drobn", "d3ros", "d3rou", "d3roš", "dr4sc", "d3ruš", "d3ré", "d3rý", "d4rýv", "2d1s2", "ds4ků", "ds4po", "d1t", "d3tl", "d3tř", "1du", "dum3ř", "du3na", "du3p", "du4pn", "2dur", "du3si", "du4í.", "d2v", "d4vac", "d3ve", "d3vl", "d3vr", "d3vy", "d3vá", "d3vě", "d3ví", "1dy", "dy4su", "d3zb", "d3zd", "d3zn", "1dá", "2d1č", "1dé", "1dě", "3děj", "1dí", "2dň", "d1řa", "dře4k", "d4řep", "dře4pn", "d4řev", "d1ří", "d2řít", "2dš2", "d3šk", "d3št", "1dů", "3dů.", "dů3s", "1dý", "d2ž2", "2e.", "e1a", "ea3dr", "e2ar", "e1b", "eb4er", "ebez2", "eb4li", "e2bř", "e4ch.", "e3chl.", "e4chm", "e3cho", "e2chr", "e3chv", "e4chť", "ed4be", "ed4kv", "ed1l", "ed2ma", "e3dmn", "ed3v", "ed4ří", "e1e", "ee4th", "ee3xi", "eg4gi", "e1ha", "e1he", "ehno4", "eh4ně", "e1ho", "e1hr", "e1hu", "e1hy", "e1há", "e1hý", "e1i", "eilus3", "ej3ag", "e3jas", "e1je", "e3jed", "ej3ele", "e3jez", "ej3in", "e3jis", "ej1m", "ej3mo", "e3jmu", "ej1o", "ej1u", "eju3st", "ej3v", "e2k", "e3ka", "e3ke", "e4kly", "e3ko", "e3kr", "e3ku", "e3ky", "e3ká", "e3ké", "e3kó", "e3kř", "e3ků", "e1la", "e4lau", "el4dv", "e1le", "e1lo", "e1lu", "e1ly", "el4ze", "e1lá", "e1lé", "e1lí", "e1ml", "e4mlí", "emo3k", "e1mr", "e1my", "e3má", "e1mě", "e1mí", "e3mř", "e3mů", "e1mý", "em3že", "en4dv", "enitos4", "en4sc", "en4si", "ent3r", "e1o", "eo3by", "eoch3r", "eod3l", "eo4du", "e4ole", "eo1s", "eo2st", "eo4tř", "eo3z", "eo4zb", "eo4zd", "eoše3", "epa3t", "e2pl", "e4pni", "ep2no", "e4pný", "epoč3t", "epro4zř", "ep4tl", "ep4tm", "ep4tn", "e4ptu", "epy3", "2er", "e1ra", "er4a.", "e1re", "e1ri", "e1ro", "er3s", "er4s.", "er4sn", "e1ru", "e1ry", "e1rá", "e1ré", "e1rů", "e1rý", "e1s", "e4sag", "e2sce", "e4sin", "esi4s", "e2sk", "es4k.", "e4s4kn", "es3ku.", "es3ky", "es3ké", "e2sl", "e4s3li", "e4sly", "es2m", "e4sp.", "es4pe", "e2st", "e4st.", "e4ste", "es3tiž", "es4tol", "e4strou", "es3tán", "e1t", "e4tki", "e4tkr", "e4tli", "e4tly", "et3ri", "et3ro", "et3rů", "et1ř", "et4ún", "e1u", "eu3b", "eu3ct", "eu3d", "eu3k", "eu3m", "eu4m.", "eu3n", "eu3p", "eu3r", "eu4r.", "e4ura", "eu4ras", "eu4rg", "eu3s2", "eu3t", "e4u4t.", "eu4tra", "eu4ts", "eu3v", "eu3z", "eu3ž", "e3vd", "eve4š", "e3v2k", "e4vsk", "evy3", "evyjad4", "evypá4t", "evy4čk", "evě4tr", "ex4ta", "e3xu", "ey4or", "ey4ov", "ezaos3", "ez4ap", "ez4bo", "ez3de", "ez3dov", "ez3du", "ez4dě", "e3ze", "ez4ed2", "ez4ej", "ez4el", "ez4er", "ez4es", "ez4ez", "ez4eš", "ezis4", "ez4it", "ez4le", "ez4ná", "ez4ně", "ez4py", "ez2t", "ez4ác", "ez4áh", "ez4če", "e3zí", "e3zř", "ez4ře", "e1á", "eč4kat", "e1čt", "eč4te", "e4čti", "e4čtí", "e2ň", "e3ňo", "e3ňu", "e3ňá", "e3ón", "e1ř", "eře4k", "eř4ku", "e3ří", "e2š", "e3še", "e3ši", "e4ška", "e3šl", "eš4lá", "e3šo", "eš4to", "eštíh4", "e3ší", "eú1", "eúmy4", "eú3n", "eú3p", "eú3t", "eú3č", "ežíš4", "1f", "2f.", "fe4in", "fene4", "fe4ue", "fi4em", "fi4fl", "f2l", "f3lí", "fló4r", "fm4no", "2fn", "2fr", "f4ran", "f4ras", "3frek", "f1ri", "2fs", "fs4te", "2ft", "fu4ch", "2fé", "f2ú", "1g", "2g.", "ga4uč", "ge2s", "ghou4", "3gic", "3gin", "gi4ím", "g4lom", "2g1m", "2gn", "g4noi", "g4nos", "go1", "go4hm", "3graf", "gu4el", "gu4it", "gu3m", "gu4m.", "gus4t", "gu3v", "2h.", "ha4ag", "ha4ar", "ha4bl", "ha4br", "ha3dl", "ha4dla", "ha4ke", "has3t", "hatos4", "ha4yd", "h2b", "h2c", "2hd", "he4br", "he4id", "hej4s", "he2s", "he2u", "he3x", "hi4an", "hi3er", "hi4gh", "hi4re", "2hk", "4hla.", "h4led", "h3len", "2hli", "4h3lo.", "h3lob", "h3lop", "h3lov", "h3luj", "2h1ly", "4hlá.", "h4lás", "h3lí.", "4hlík", "2hlý", "h2m", "2h2n", "h3ne", "h4ned", "h3niv", "h4noj", "3hněd", "3hodin", "ho3str", "hos4tě", "4hove", "4hovna", "4hovny", "4hovná", "4hovně", "h2r", "hra4p", "2h1t", "h4tin", "h2tě", "h4tít", "hu4ch", "hu3mo", "hu4tň", "2h2v", "hyd1", "hy4do", "hy4ps", "hys3", "hy2t3r", "hy4zd", "h1č", "2hň", "hř2", "hř4by", "hý4bl", "h2ž", "2i.", "i1a", "ia3d", "ia3g2", "i4al.", "ias4t", "ia4tr", "i1b", "ib2l", "i2b1r", "i1ch", "i4chž", "i1d", "id4ge", "id2l", "id4lo.", "i4dlý", "i1em", "i1en", "i1et", "if1r", "ig4ne", "i1h", "i2hl", "i3hl.", "i4hli", "ih3n", "ih4na", "i3im", "i1j", "ijed4", "ij4me", "ij4mi", "i2kl", "ik3le", "ik3lo.", "ik3m", "ik4ry", "i4kve", "ik4úř", "i1l", "il4ba", "ilič4n", "i4lnu", "ilu3", "i1m", "i4mla", "i4mly", "i4mun", "i2n", "i3na", "ina3d", "in4cm", "in4dl", "i3ne", "3infe", "in4gh", "in4gp", "in4gs", "in4gt", "i3ni", "i3no", "i3nu", "i3ny", "i3ná", "i3né", "i3ně", "i3ní", "in4šp", "i3nů", "i3ný", "i1o", "io4sk", "i2ps", "i1r", "iro4s", "i1sa", "is3c", "is4ch", "is4k.", "is3ka", "is3ke", "is3ko.", "is3kr", "is3ku", "is3kv", "is3ky", "i3slav", "is3lo", "is3lé", "is3pl", "is3po", "is1t", "is4tal", "is4tat", "is4th", "ist3v", "is3tí", "i1sy", "i3sá", "i1t", "it1r", "it4rh", "it4rp", "it4se", "it4su", "i2tv", "i1um", "iv3d", "i1x", "ix4td", "i3zp", "iz1r", "i1á", "i1čl", "ič3t", "ič4tl", "ič4to", "i2ď", "i1é", "ié4re.", "i1íc", "i1ím", "i1ó", "i1ř", "iř4kl", "iř4če", "i2š", "i3še", "i3ši", "iš3k", "iš4kr", "iš4kv", "i3šo", "iš4to", "i3šu", "i3šá", "i3ší", "i2ž", "i3ža", "i3že", "i3ži", "i3žo", "i3žu", "i3žá", "2j.", "ja2b2", "jac4k", "ja4cq", "ja3d", "ja3g", "j3akt", "j1b2", "jbyst3", "2j1c", "j2d", "j3dob", "j3dok", "j3dos", "j3dr", "j3dá", "jd4ří", "j3dů", "jech4", "j3ef", "j3ex", "jez3dí", "jg4ra", "2j1h", "1ji", "ji4ch", "jih3l", "ji4mž", "j4ina", "jis3k", "jit4ro", "ji2zv", "j1j", "2jk", "j3kv", "2j1l", "j2m", "j3ma", "j3mi", "jmou3d", "2jmí", "2jn", "jne3", "j1ob", "j1od", "jod2ř", "j1oh", "j1op", "j4ora", "j1os", "jo3sv", "j2ov", "j3ovl", "j1o3z2", "2jp", "jpor4", "jpo4zv", "jpříz4", "2j1r", "2j1s2", "j4sem", "j4si.", "j4sk.", "js4ko", "js4ká", "j4s4ků", "j4s4me", "j3sn", "j4sou.", "j4souc", "js4po", "j4s4te", "2j1t", "j3tl", "ju4an", "ju3na", "ju3p", "j1us", "ju3sp", "ju3t", "ju4t.", "ju3v", "ju4xt", "ju3z", "j1už", "ju3ži", "2jv2", "j3vd", "j3vn", "2jz", "j3zb", "j3zd", "j3zk", "j3zn", "j3zp", "jád2r", "2j1č", "2jď", "1jí", "j3št", "jš4ti", "j3šť", "2jú1", "jú3n", "jú3č", "jú3ž", "2jž", "1k", "2k.", "ka4bl", "ka4ch", "ka3dl", "3kaj", "ka3ka", "3kami", "3kaně", "ka2p3l", "ka2p3r", "ka2ps", "ka4pv", "ka2př", "kas3t", "kast3r", "3kat", "ka4uč", "3kav", "3kač", "3kař", "kaš3l", "ka4šp", "2k1c", "k2d", "k2e", "ke4bl", "ke3jo", "ke4pr", "ke4ps", "3ket", "2kf", "2kk", "k2l", "3kl.", "4k3la.", "k3lej", "4k3li.", "k4lib", "k3lic", "4klička", "4klo.", "k3los", "2k3ly", "k3lá.", "k3lé", "k3ló", "k3lý", "2k2m", "k3mě", "2kn", "kna4s", "ko3by", "3kof", "ko4jm", "ko2př", "ko4sk", "ko2t3v", "kous3k", "3kov", "ko3zá", "4kroa", "k3rob", "k3rof", "kr2s", "kr4ú.", "2ks", "2k1t", "kt2r", "kuch4", "ku4fř", "ku4hr", "3kuj", "ku3se", "ku3si", "ku3su", "ku4th", "ku3v", "2k2v", "k4vrň", "3kyn", "ky2pr", "kyp3ř", "ky4zn", "3kác", "ká4pl", "3kár", "3kář", "2kč", "k2ň", "k2ř2", "k3řej", "kš4ti", "3ků.", "2l.", "1la.", "la4br", "lab4s", "la3ka", "la4nq", "la4ps", "4la3si", "la4vš", "la4y.", "la2zm", "2l1b", "2l1c", "2l1d", "ld4ne", "le4ad", "le4au", "lech3t", "leh3n", "le2i", "1lej", "le3jo", "4lejšk", "1lel", "4lench", "lepa3d", "lepo4s", "le4pr", "le4ps", "le4sc", "le4sm", "le4sv", "let4li", "let3m", "le2tr", "le4tč", "le4uk", "le4vh", "le4vk", "le3xi", "lez3n", "2lf", "2lg", "2lh", "3lhan", "1li", "li4az", "li4bl", "li4bv", "li4dm", "lind4", "3lio", "li4tň", "li4vr", "2liž", "2lj", "2lk", "l4kat", "l2kl", "lk4nu", "2ll", "2l1m", "2ln", "l4nul", "lo3br", "lo4id", "lo4is", "1los", "lo3sp", "lo3stř", "lo3sv", "lo2tr", "lo4tř", "lo4u.", "lo3z", "loz4d", "lo4šk", "2lp", "l2pě", "2l1s2", "l4sla", "ls3n", "lst4n", "l4stí", "2l1t", "lt4ra", "lt4ru", "lt4ry", "lu4id", "lu4j.", "lu4k.", "lu4lk", "lu4m.", "lu4mn", "lu3pr", "lu3va", "lu3vl", "lu3vy", "lu3ví", "2lv", "2lz", "1lá.", "lá4jš", "lá4vš", "2l1č", "1lé.", "1lík", "lí4pl", "lí4zn", "1líř", "2lň", "2lš2", "l3št", "l4štý", "1lů", "1lý", "lý2t", "2l2ž", "2m.", "1ma", "maj4s", "ma4kl", "ma4kr", "4mald", "mas3k", "mat3r", "ma4tra", "ma4vš", "maz3l", "2m1b", "2m1c", "2m1d2", "m2dl", "1me", "3me.", "me4go", "me4is", "met3re", "me3x", "mezi3s", "2mf", "mh4le", "1mi", "mid3l", "mik3r", "mi4xt", "2mk2", "3m2kl", "mk4la", "mk4li", "m2l", "4mla.", "2mle", "ml3h", "ml4h.", "2mli", "ml4sc", "ml4sk", "4mlu.", "2mn", "m3na", "mna4s", "m4noh", "m3nos", "m4noz", "3množ", "m3ná", "m3né", "m4néz", "m3něj", "m3ný", "1mo", "mod3r", "mo2hl", "mo2k", "mo2s", "mo4s.", "mot3ř", "4mout", "moza4", "mo3zř", "moú3", "2mp", "m4plo", "mpo4s", "m2ps", "mp4se", "mp2t", "mr2s", "2m1s2", "m4stl", "2m1t", "1mu", "mu4fl", "mu3n", "mu4n.", "mu4nd", "mu4nn", "mu4ns", "mu4nš", "2muš", "2mv", "mys3lo", "my4šk", "2mz", "3má.", "málo3", "má2s", "2mč", "m2če", "mí1c", "mí4rň", "2m2š", "mš4či", "mš3ť", "mš4ťan.", "3mů.", "3mý.", "m2ž", "1n", "2n.", "3na.", "na3ch", "na4do", "na4em", "na3h", "na4h.", "na3jd", "na3ka", "nam4ne", "na3p2", "na3s2", "na4s.", "nat2", "na3tl", "na3tř", "na3z", "naz4k", "na4zš", "na4č.", "na3š", "naž4n", "2nb", "2n1c", "n4chc", "2n1d", "nd4hi", "ndo4t", "nd2re", "nd4ri", "nd4ří", "ne1d", "ne4gl", "ne1h", "ne3h4n", "ne2j", "nej3t", "nej3u", "ne3kl", "ne4kro", "ne3kv", "ne4m.", "ne3p", "ne3s2", "ne4s.", "nes4le", "ne4ss", "4nesti", "ne3tl", "net4r", "ne3ud", "ne3v2", "ne4v.", "ne3z", "nez4n", "ne3šk", "ne3šť", "2nf", "n3fr", "2ng", "ng1l", "ng4la", "ng4le", "ng4lí", "n4gro", "ng4vi", "nik4t", "ni4mr", "ni4mž", "3nio", "3nisk", "2nitř", "n1j", "2nk", "2n1l", "2nn", "no3b2", "no4bs", "no3hn", "no4hs", "no4ir", "no4mž", "no4sky", "no3sm", "no3str", "not4r", "no3z", "no4zd", "no4šk", "2nož", "2n1s2", "n2sa", "ns3ak", "ns4ko", "n4soc", "ns3po", "nst4ra", "2n1t", "nte4r3a", "nt4lem", "nt4r.", "nt3ru", "nt3rá", "2nub", "nu4gg", "3ny.", "2nz", "3nák", "ná3s2", "ná4s.", "2n1č", "2nď", "2nív", "2níž", "2nó", "2nš2", "n3št", "nš4ťo", "nů2", "2nž", "2o.", "o1a", "oang4", "o1ba", "o1be", "obe3j", "obe3s", "obe3z", "ob1l", "ob1r", "ob4rň", "o1bu", "obys4", "ob3z", "o3bé", "ob3řez", "o1c", "o4chl", "o2chr", "oc4ke", "oc4ko", "o4ct.", "oct3n", "ocy3", "oc4ún", "od3b", "odej4m", "ode3p", "ode3s", "od1l", "o4doc", "odos4", "odo4tk", "od3ra", "od4ran", "od3rů", "o3drž", "od3v", "od1ř", "o1e2", "oe3g", "oe3ti", "o2fl", "ofrek4", "og2", "o3gn", "o1h", "oh4ne", "o1i", "oi4ce", "o4int", "o1j", "o4jar", "oje4dl", "o4jmi", "o4jmov", "o4jmu", "o4jmů", "oj2o", "o4juz", "2oka", "ok2te", "o1l", "ol4gl", "ol4to", "o1m", "om4kl", "om2n", "o2n", "o3na", "ona4s", "o3ne", "o3ni", "o3no", "ont4ra", "o3nu", "o3ny", "o3ná", "onář4ka", "o3ně", "o3ní", "o3nů", "o3ný", "o1o", "oo4hř", "oote2", "opoč3t", "opro4s", "o2ps", "o4ptu", "opá4t", "o4př.", "opřej4", "opře4jm", "o1ra", "o4rae", "or4dm", "o1re", "o1ri", "o1ro", "or3st", "o1ru", "or4vá", "o1ry", "o1rá", "o3ré", "o1rů", "orůs3", "o3rý", "o1sa", "o4sai", "ose4s", "osi4d", "o1sk", "o4s3ke", "o4sku", "osk3v", "o4ská", "o4ský", "o1sl", "os4la", "os4li", "os4lý", "os3mo", "os4mu", "o4st.", "o4stg", "o4stm", "os4tor", "os3trů", "o4sté", "o4stš", "o4stý", "o1sy", "o1t", "ot4kl", "o4tlý", "oto3s", "ot3ro", "ot3ví", "o3tí", "o3tř", "ot3ři", "o2u", "ou3bě", "ou3dě", "ou4fl", "ou4il", "ou4is", "ou4k.", "ou3ka", "o4ukl", "ou3kr", "ou3ká", "ou3m", "oup3n", "oupo4", "ou4s.", "ou3sa", "ou3se", "ou4sk", "ou3sm", "ou4tv", "ou3v", "ou4vl", "ou4vn", "ouz3d", "o4učk", "ou3ži", "ovi4dla", "o4vsk", "ovy2p", "o2všt", "o1x", "o2z", "o3za", "oz1b", "oz4d.", "oz3dá", "oz3dě", "oz3dí", "o3ze", "oze3d2", "ozer4", "oz1h", "o3zi", "oz3j", "oz3k", "oz4ko", "oz1l", "oz3m", "o4zn.", "o3zo", "oz3p", "oz4py", "oz4pě", "oz4pí", "oz3ro", "oz3ru", "oz3rů", "oz3t", "o3zu", "o4zut", "oz3vr", "oz3vá", "o3zí", "o3zů", "ozů4s", "o1č", "oč2k", "oč4ka", "o2ň", "o3ňa", "o3ňo", "o1ř", "oři2s", "o3šk", "o4šku", "o4šky", "o3šl", "oš4lá", "oš4mo", "oš4ti", "oš4ťu", "o3žl", "ož4mo", "1p", "2p.", "pa4ed", "pa4es", "pa4kl", "pa3si", "pa4t.", "pat4ri", "2p1c", "pe4al", "pede4", "pe4ig", "pe4np", "peri3", "pes3t3", "pe4tra", "3peč", "pi4kr", "pi4pl", "2pk", "p2kl", "p2l", "3pl.", "4p3la.", "pl3h", "pl4h.", "4p3li.", "4plo.", "2pn", "p2nu", "po1b2", "po3c2", "3pod", "podbě4h", "pod4nes", "po3dru", "po3drá", "po3h", "poly3", "po3m2", "po4mp", "po4ol", "po3p", "po4p.", "po4pm", "po1s2", "pos4p", "post4r", "po3t2", "po4t.", "po4tn", "po3uk", "po3uč", "po3už", "3po3v", "po3z2", "po4zd", "poč2", "po3čk", "poč3te", "po3ří", "po4šv", "2pp", "4pra.", "pra3st", "pr2c", "pro1", "prob2", "pro3p", "pro3t4", "pro3z", "pr2s", "4prán", "prů3", "pse4s", "2p1sk", "p4sut", "2pt", "p4tej", "p4ter", "p4tev", "pt4ri", "p3tu", "p4tá.", "pu4dl", "pu4tr", "pyt3l", "pá1", "pá2c", "pád3l", "pá4nv", "pá4sl", "2pč", "pé4rh", "2př.", "pře3h", "pře3j", "pře3t4", "pře3z", "pře3č2", "při3", "přih4", "2pš", "pš4ti", "2pť", "qu2", "2r.", "1ra.", "ra4br", "ra4em", "ra4es", "ra4ff", "ra4hl", "ra4hm", "ra4jg", "ra4jš", "2rak", "ra4nh", "ra3si", "rast4r", "ra4vv", "ra4wl", "ra4y.", "ra4yo", "ra4ďm", "4raži", "r1b", "r2bl", "r1c", "rca3", "r3cha", "r3cho", "rc4ki", "r1d", "r4dla", "rdo2s", "re4ad", "re4au", "red4r", "re4et", "re3kl", "re3kvi", "re4mr", "re2sb", "res3l", "retis4", "ret4r", "re4um", "r1ha", "r3hl.", "rh3n", "r1ho", "r3hu", "r1há", "ri4bb", "1ric", "ric4ku", "ri4dg", "ri4dr", "ri4fl", "ri4gh", "ri4zm", "2rk", "r2kl", "r1l", "2r1m", "r4mio", "2rn", "rna4vš", "rn4dr", "ro4ad", "ro3by", "rod2l", "ro3d4r", "3rofy", "ro3h", "ro4h.", "ro4jb", "ro4kš", "rom3n", "romy4s", "ropát4", "ro2sb", "ro4skv", "ro4sky", "ro3sv", "ro3ti", "ro3tl", "ro4tč", "ro3vd", "rově4t", "3rový", "roz3d", "roz3n", "ro4zo", "roz3v", "ro3zá", "ro4čp", "rpa3d", "2rr", "rr4ha", "rr4ho", "2r1s", "r2st", "r4stu", "rs3tvě", "rs3tvý", "2r1t", "r2th", "r4trá", "rt4sm", "rtu3", "r2t3v", "rt4zu", "1ru.", "ru3se", "ru3si", "rus3k", "ru3ži", "3rvaní", "r1x", "1ry.", "rych3", "ryd2", "rys3ky", "rys3t", "ry4zk", "ry4zn", "ry4í.", "ry4šk", "2rz", "rz3d", "rz3l", "rád4l", "rá4dž", "1rák", "rá3ri", "1rář", "r1č", "4rčitý.", "rč3t", "3ré.", "2ró", "2rš", "rš4ní", "rů4m.", "růs3ta", "rů4v.", "3rý.", "rý4zn", "2s.", "sa4pf", "sa4pr", "sas3k", "s2b2", "s2c", "s3ca", "s3ce.", "sch2", "sch4l", "sch4n", "3schop", "s3ci", "sci4e", "s3cí", "s2d", "1se", "se4au", "se3h", "se4ig", "se4il", "sej4m", "se4ku", "3sel", "se3lh", "3sem", "ser4va", "se3s2", "ses4k", "se4ss", "se4stra", "se4stru", "se4stř", "set2", "se3tk", "se3tř", "se4ur", "se3z", "se3čt", "2sf", "s3fo", "3sfé", "s3fú", "1si", "3sic", "3sif", "si4fl", "sig4no", "3sik", "si3ste", "3sit", "s2j", "s3ju", "s2k", "4skac", "s4kak", "4skam", "s4kok", "2skon", "skos4", "4skot", "sk4ra", "sk4ru", "sk4ry", "4skve", "sk4vo", "s3kán", "s3ků", "3sl.", "4s3la.", "s4lav", "s3le.", "s4led", "s3lem", "s3len", "s3let", "s4lib", "s4liči", "3sln", "4s3lo.", "s2ly", "s3ly.", "s1lí", "s2ma", "s4mek", "s2mo", "2sn", "s2na", "s3nat", "s2ne", "s3ne.", "sn4tl", "s2ná", "s3ná.", "s4níd", "1so", "sob4l", "so3br", "so4sk", "so4tv", "sou3h", "sou3s", "souz4", "so4šk", "s2p", "s4pol", "spro4s", "1sr", "2ss", "ss4sr", "2st.", "4sta.", "s3taj", "s2tan", "st4at", "4stec", "s4tep", "st4er", "s4tero", "s4tich", "2stil", "s4tink", "4stit.", "4stič", "st3lo", "2stn", "4sto.", "s4tona", "4stou.", "4str.", "4stram", "s4trik", "4strn", "4strác", "4stupni", "s2tv", "st4ve", "3ství", "4sty.", "s4tyl", "3styš", "s2tá", "4stá.", "s3tář", "4stě.", "s4těd", "3stěh", "s2těr", "s2těž", "s1tí", "2stí.", "s3třej", "1su", "su4ba", "su4bo", "suma4", "su3ve", "s2v", "sy3c", "sych3r", "sy4nes", "sá2d", "3sáh", "sá2kl", "2s2č", "s3či", "1sé", "1sí", "2sň", "2sť", "s3ťo", "1sů", "s2ž", "2t.", "1ta.", "ta2bl", "tac4tvo", "t2a3d", "1taj", "ta4jf", "ta4jg", "4talt", "4tand", "3taně", "t1ao", "2tark", "tast4", "ta3str", "ta4čk", "2t1b", "2t1c", "1te", "3te.", "te4ak", "te4fl", "te4in", "4teném", "teob4", "tep3l", "ters4", "tes3ta", "te4tr", "te4uc", "te4ur", "te4ut", "2tf", "2tg", "1ti", "ti4gr", "2tih", "ti3kl", "tin4g", "ti4pl", "ti3sl", "tis4tr", "ti4tr", "2titu", "tiz4r", "4tizí", "tiú3", "2tiž", "2tk2", "t4kal", "4t2kan", "t4kat", "t2kl", "tk4la", "tk4li", "4tkně", "t2ká", "2tl", "3tl.", "4tla.", "t1le", "tles3", "3tlm", "t3lo.", "t4lou", "tlu3", "tlu4s", "t1ly", "t1lé", "2tm", "t2ma", "2tn", "t3ní", "1to", "to4as", "to3b", "tob4l", "to3dr", "to4hm", "to4ir", "2toj", "tol4s", "to4ol", "4top.", "4topt", "4topu", "2torn", "2toup", "2tp", "t3rant", "t4rea", "t4ref", "tre4t", "4tric.", "trip4", "t4rit", "t4rog", "t3rol", "tro4sk", "t4rou", "4trouh", "4troň.", "4trun", "t4rus", "4t4ruž", "t3ráln", "4tráš", "2trč", "t3rům", "t3rův", "2trý", "2t1s", "ts4ko", "ts2t", "2t1t", "tt4ch", "tt4ri", "1tu.", "tu4ff", "1tuj", "tu4lk", "2tup", "tu4r.", "tu3ry", "tu4s.", "tu4ť.", "tu3ži", "t2v", "2tve", "2t3vi", "t4vinn", "t4viš", "t4výc", "1ty.", "ty4gř", "ty2la", "ty4ře", "ty4řh", "ty4řj", "ty4řo", "ty4řr", "ty4řú", "3tá.", "tá4fl", "t2č", "t3či", "2tčí", "1té", "té2bl", "3tém", "1tě", "tě3d4l", "2těh", "2těnn", "2těp", "1tíc", "4tíc.", "4tíce", "1tím", "2tín", "2tír", "2tř", "t4řeb", "třeh3n", "t2řel", "t2řic", "t3řil", "tř4ti", "t1řu", "t2řá", "3třáb", "tří4s", "2tš", "t3št", "tš4ti", "1tů", "1tý.", "1tým", "1týř", "3týš", "u1", "2u.", "u2at", "u2b", "u3ba", "u3be", "u3bi", "u3bo", "ubs4t", "u3bu", "u3bá", "u3bí.", "u3bů", "uc4tí", "2u2d", "u3de", "u3di", "u3do", "u3dru", "u3du", "u3dy", "u3dí", "ue4fa", "2uf", "u2hl", "uh3lá", "uh3no", "u2in", "u2jm", "u2k", "u3ka.", "uk4aj", "uk4al", "uk4at", "u3ke", "uk3la", "uk3le", "u3ko", "u3ku", "u3ky", "uk4á.", "u3ků", "ul4fa", "ul1h", "ul4pí", "u2m", "u3ma", "u3me", "u3mi", "um4pl", "um4ru", "u3mu", "u3má", "3umř", "u2n", "un4dl", "u3ne", "u3no", "u3nu", "u3ně", "u3ní", "u3nů", "un4žr", "u2p", "u3pa", "u3pe", "upe2r3", "u3pi", "u3pln", "u3pu", "u3py", "u3pá", "u3pě", "u3pí", "u3pů", "u2r", "u3ra", "u3re", "u3ri", "2u3ro", "u3ru", "u3ry.", "u3rá", "1urč", "u3rů", "u2s", "us3ky", "us3ká", "us3ké", "us3ký", "us1l", "us2lo", "u3so", "u4ste", "u4sty", "u4sté", "u4stě", "u3stř", "u4stš", "u4stý", "u3su.", "u3sy", "u3sá", "u3sí", "u3sů", "u4tro", "u4trá", "u2v", "u3vi", "u3vu", "u2z", "u3ze", "u3zi", "uz1l", "u3zo", "u3zu", "u3zí", "u2č", "u3ča", "u3če", "u3či", "u3čo", "uč3t", "u3ču", "u3čá", "u3čí", "u2ď", "u2ň", "u2š", "u3še", "u3ši", "uš4kl", "u3šo", "uš3tí", "u3šu", "u3šá", "u3ší", "u2ž", "u3že", "u3žo", "u3žu", "u3žá", "u3ží", "1v", "2v.", "va3dl", "va4jť", "va4kl", "2v1b", "2v1c", "v2ch", "2v2d", "v4dal", "v3di", "v4děk", "v4děč", "ve3dle", "ve3jd", "3ven", "ve2p", "ve3ps", "vep3ř", "ves3l", "ve4sm", "ves4p", "ve3sta", "ve3t4ř", "ve2z3m", "vi4ch", "vide2", "vi4dr", "vi4et", "vi4kr", "vi2tr", "2vk", "v2kr", "v2l", "2v3la.", "4vle.", "4vlem", "2vlo", "2vm", "2vn", "v4nad", "vo3b", "vo4ic", "vo4ja", "vo4jb", "vo4jd", "vo4jj", "vo4jm", "vo4jř", "vo2s", "vo4tř", "vou3", "vous2", "v2p", "vr2c", "vr2dl", "4vrny", "v1ro", "vr4st", "vrst3v", "vrs4tvě", "2vs2", "v1sk", "v3stv", "2v2t", "vy3c", "vy3d2", "vy4dra", "vyp2", "vy3s2", "vy4sn", "vys4t", "vy3t", "vy3č", "vyč4k", "vyš2", "vy4š.", "vy4šm", "vy4šš", "vy4žl", "v2z2", "vz4no", "vz4né", "vz4ně", "vz4ní", "vá3ri", "2v2č", "v3čá", "v3čí", "v4čír", "vě4cm", "vě3t4a", "více3", "ví4hat", "3vín", "2vň", "2vří", "v3řín", "v2š2", "vše3s", "v3ští.", "3výs", "vý3t", "3vý3z", "v2ž2", "wa4fd", "3war", "wa4re", "we2", "2x.", "xand4", "2xf", "xisk4", "2xn", "3xov", "x1t", "xt4ra", "xy4sm", "y1", "y2a", "y2bl", "yb3ri", "y2ch", "y4chr", "y2d1l", "yd4lá", "y2dr", "yd4y.", "y2e", "y2gr", "y3hn", "yh4ne", "yj4ma", "yj4me", "y2kl", "yk3la", "y3klop", "yk4ly", "ymané4", "ym4kl", "yna4s", "y3ni", "ype4r", "yp4si", "yp4tá", "y2př", "yr2v", "y2s", "y3sa", "y3se", "y3si", "ys3lu", "y3sm", "y3so", "y3sp", "ys2t", "ys3te", "yst4r", "y3su", "y3sv", "y3sy", "y3sá", "y3sé", "y3sí", "yt4me", "yu3ž", "y3vs", "yvě4t", "y3zb", "y3zd", "y3zk", "y3zn", "yz4ně", "yz4ní", "y3zp", "yz4po", "yč2k", "y2ň", "yř3b", "yřk4n", "yř4če", "y3ří", "y2š", "y3še", "y3ši", "y3šk", "yš1l", "y3šo", "y3šp", "y3šu", "y3ší", "yž2", "y3žd", "1z", "2z.", "zab2l", "za4bs", "za4dk", "za3dl", "za4dn", "za3h", "za3i", "za3j", "za4jk", "za3k", "za4kt", "zal4k", "zam4n", "za3p2", "za3s2", "zat2", "za3tl", "zat4r", "za4ut", "za3z", "zaz4n", "za4zš", "za4č.", "za3š", "zaš4k", "za4šs", "2zb", "zban4", "z2by", "zbys4", "2z1c", "2z2d", "z3di", "zdně4ní", "z4doba", "z4dobný", "zd4re", "zd4ví", "z2e", "ze3h", "ze3p2", "4zerot", "ze3s2", "zes4p", "zet2", "zev2", "ze3vn", "ze3z", "ze4z.", "2z2f", "z1há", "z4ine", "z2j", "z3jí", "2z2k", "z3ka.", "z3ky", "z3ké", "z3ků", "z3ký", "2zl", "3zl.", "zlhos4", "zlik3", "z3ly.", "z2m2", "2zme", "z3mn", "z3my", "z4měn", "2z2n", "3znak", "z4nal", "z3ne.", "z3nic", "z3no", "z3nu", "z3ny", "z3né", "z3ně", "z4něl", "z3ní", "z4nít", "z4nív", "z3ný", "zo4tr", "zo4šk", "2z2p", "z3pt", "z4pát", "3zrak", "2z1s2", "2zt", "ztros3", "z4trá", "z3tř", "3zu.", "zu3mo", "zu3mě", "zu3mí", "zu3š", "z2v", "zva4d", "z3vař", "z3vi", "zvik4", "zv4ně", "z3vod", "z3voj", "z4von", "zv4ro", "z4ván", "z4věs", "z3víj", "3zy.", "2zz", "zá1", "záh2", "zá4kl.", "3záp", "zá3s2", "zá3z", "záš2", "2zč", "z3čl", "2zň", "z2ř", "zřej3", "z3řez", "z3řeš", "2zš2", "z3šk", "zš4ka", "z3št", "2z2ú1", "zú3č", "zú3ž", "zů3s", "á1b", "á2bl", "áb4ry", "á4bř.", "á3cho", "ác3ti3", "á1d", "á2dl", "ádo4s", "ádos4ti", "ád1ř", "á1ha", "á3he", "áh1l", "á3hl.", "áh3n", "á1ho", "á1hr", "á1há", "á1j", "á4jmu", "áj4mů", "á4kli", "ák4ni", "á1la", "á1le", "á1lo", "á1lu", "á1ly", "á3lé", "á1lí", "á3my", "á3mé", "á1mě", "á3mí", "á3mý", "áne4v", "á1ra", "á1re", "ár2m", "á1ro", "á1ru", "á3rů", "á1s", "á2sc", "á2s3k", "ás4k.", "ás4kl", "ás4kn", "á2sla", "ás4ly", "á2sm", "ás4po", "á2st", "át3k", "át1r", "á1tu", "á1ty", "á1tí", "á3tý", "áv4si", "áv4sí", "áz3k", "áz3ni", "ázni4c", "áz4vi", "á2ň", "á1ř", "ář4ke", "ář4ků", "á2š", "á3še", "á3ší", "2č.", "1ča", "ča4br", "2čb", "2č1c", "1če", "3če.", "če1c", "čes3k", "1či", "2čk", "č3ka.", "č3ko", "č3ku", "č3ky", "2č1m", "2čn", "č2ne", "1čo", "č2p", "2čs", "č1sk", "čs4la", "čs4sr", "2č2t", "č4tené.", "č4tený", "čt4la", "č4tový.", "3čtv", "4čtěn", "č3tí", "1ču", "1čá", "1čí", "čís3l", "1čů", "2ď.", "1ďa", "1ďo", "ďs4te", "2ď1t", "3ďuj", "é1", "é2d", "é3di", "é3do", "é2f", "é3fo", "éf1r", "é2kl", "é2l", "é2m", "é3ma", "é3me", "é3mi", "é3mo", "é3mu", "é3mů", "4ére.", "é2s", "é2t", "é3ta", "é3to", "é3tá", "é2š", "é2ž", "ě1c", "ěd3r", "ě3ha", "ě3he", "ě3hl.", "ěh3lo", "ěh3n", "ě1ho", "ě3hu", "ě3hů", "ě3ja", "ě1je", "ě1jo", "ě3jů", "ě4klé", "ě3k2t", "ě1l", "ě1ra", "ěra3d", "ě1re", "ě1ro", "ěr3s", "ěrs4t", "ě1ru", "ě1ry", "ě1rů", "ěs3k", "ěs3n", "ět1a3", "ět4ac", "ět1l", "ě1tr", "ět3ra", "ě4traj", "ět3v", "ě1tí", "ět3ří", "ě2v", "ě3va", "ě3ve", "ě3vl", "ě3vo", "ě3vu", "ě3vá", "ěv3č", "ě2z", "ě3ze", "ě3zi", "ěz3n", "ě3zo", "ě3zí", "ě1ř", "ě2š", "ě3še", "ě3ši", "ě3šo", "ě3šu", "ě3šá", "ě3ší", "ěš3ť", "ěš4ťs", "ě2ť", "ě3ťo", "ě2ž", "ě3že", "ě3ži", "ě3žo", "ě3žu", "ě3ží", "í1b", "íb3ř", "í3cho", "ích4t", "íd1l", "í1h", "í2hl", "íh3n", "í1j", "íjed4", "íj4mů", "í2kr", "í1l", "í1má", "í3mé", "í1mě", "í1r", "í1sa", "í2s3k", "ís4kl", "ís4kn", "ís4l.", "ís3le", "ís4ln", "ísáh2", "í1t", "ít3k", "í3t3ře", "íz3da", "íz3de", "íz3k", "í3zna", "í3z3ni", "í3zněn", "í2ň", "í1ř", "í2š", "í3še", "í3ši", "í3šo", "í3ší", "1ň", "2ň.", "2ňa", "ňa3d", "2ňk", "2ňm", "3ňov", "ň1s", "2ň1t", "ó1", "ó2z", "ó3za", "ó3zi", "ó3zo", "ó3zy", "2ř.", "řa4pl", "řa4ďm", "2ř2b", "2řc", "2řd", "ře3ch", "ře4dob", "ře1h", "ře3jd", "ře3kl", "ře3kv", "ře4kří", "řeo4r", "ře3p2", "ře4p.", "ře4pk", "ře4pč", "řer4v", "2řes", "ře3ska", "ře3sko", "ře2sp", "řes3po", "ře4sr", "ře3sta", "ře3stu", "ře3stá", "ře3stř", "ře3tl", "řet4ř", "ře3zd", "ře3zk", "4řezl", "ře3čt", "ři1", "řia3", "ři3h", "ři4h.", "ři4hn", "ři4jď", "ři4l.", "ři4lb", "řil2n", "4řine", "řis2", "3ři4t.", "ři4v.", "ři4vk", "ři4vn", "ři3z", "řič4t", "ři3ř", "ři4š.", "2řk", "ř2kl", "řk4la", "řk4li", "řk4ly", "řk4no", "2ř1l", "2ř1m", "2řn", "1řo", "2řou", "2ř2p", "2ř1s", "řs4to", "2ř1t", "ř2v", "2řz", "řá4pl", "řá2sl", "2ř1č", "2říd", "ří4kř", "ří1s", "2řš", "ř3št", "řš4ti", "1š", "2š.", "šab3", "ša4vl", "2š1c", "šej4d", "šep3t", "ši4mr", "2š2k", "š3ka", "š3ke", "š3k3li", "4š3kou", "4škov", "3škr", "šk4ro", "š3ku.", "š3ky", "2šl", "š2la", "š2li", "š3liv", "š2lo", "šlá2", "š2lé", "š2lý", "2š1m", "šmi4d", "2šn", "š2p", "2š1s", "2št", "š4tip", "št4ka", "št4kl", "š4těk", "š2těs", "š4těv", "š4típ", "š2v", "ší3d", "š2ň", "š3ší", "2š2ť", "š3ťo", "š3ťu", "š3ťá", "1ť", "2ť.", "3ťal", "2ťk", "2ťm", "2ťt", "ťáč4k", "1ú", "ú2c2", "ú2d", "új4ma", "ú2k", "ú2l", "ú2n", "ú2p", "ú2t", "út4ko", "ú2v", "ú2z", "úz3k", "ú2č", "3úče", "úře4z", "úš4ti", "ú2ž", "ů1b", "ů1c", "ů1hl", "ů3jd", "ů4jmový", "ů1le", "ů1my", "ů1mě", "ů1ra", "ůr4va", "ůr4vy", "ů1s2", "ů2st", "ůs3te", "ůs3tán", "ůt2", "ů3tkl", "ů2v", "ů3va", "ů3vo", "ů3vě", "ů2z", "ů3zo", "ů2ž", "ů3že", "ů3ži", "ů3žo", "ý1b", "ý3cho", "ý1d", "ýd4la", "ý1h", "ý1j", "ý1l", "ý1ml", "ý1mě", "ý2n", "ý3no", "ýpo3č4", "ý1r", "ý1s2", "ý2sk", "ý1t", "ýt4ku", "ýt4ky", "ý1u", "ý4vli", "ý3zk", "ý3zn", "ý4zvu", "ýč4ně", "ý1ř", "ýš3l", "1ž", "2ž.", "ža3d", "ža4tv", "3žač", "2ž1b", "2ž1c", "2ž1d", "že2b3", "žeh3n", "že4ml", "že4zg", "ži4dl", "ži4jm", "3žil", "ži2vl", "2žk", "žk4ni", "2žl", "ž4lic", "3žlo", "2ž1m", "2žn", "žon2", "2ž1s2", "2ž1t", "ž2v", "žá4br", "žá4nr", "2žď", "ží4zn", "2žň", "2žš", "žš4ti", "žš4tě", }; SILE.hyphenator.languages["cs"].exceptions = { "koe-fi-ci-ent", "koe-fi-ci-en-ty", "pro-jek-ční", "úhlo-příč-ka", "úhlo-příč-ky", };
mit
AdamGagorik/darkstar
scripts/zones/Bastok_Mines/npcs/Explorer_Moogle.lua
13
1711
----------------------------------- -- Area: Bastok Mines -- NPC: Explorer Moogle -- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/teleports"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) accept = 0; event = 0x0249; if (player:getGil() < 300) then accept = 1; end if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then event = event + 1; end player:startEvent(event,player:getZoneID(),0,accept); 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); local price = 300; if (csid == 0x0249) then if (option == 1 and player:delGil(price)) then toExplorerMoogle(player,231); elseif (option == 2 and player:delGil(price)) then toExplorerMoogle(player,234); elseif (option == 3 and player:delGil(price)) then toExplorerMoogle(player,240); elseif (option == 4 and player:delGil(price)) then toExplorerMoogle(player,248); elseif (option == 5 and player:delGil(price)) then toExplorerMoogle(player,249); end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Mazuro-Oozuro.lua
13
1256
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Mazuro-Oozuro -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MAZUROOOZURO_SHOP_DIALOG); stock = {0x426d,108, -- Lufaise Fly 0x43e7,2640, -- Clothespole 0x02b0,200, -- Arrowwood Log 0x02b2,7800, -- Elm Log 0x0b37,10000} -- Safehold 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
AdamGagorik/darkstar
scripts/globals/mobskills/Stormwind.lua
30
2237
--------------------------------------------- -- Stormwind -- -- Description: Creates a whirlwind that deals Wind damage to targets in an area of effect. -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown radial -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- -- onMobSkillCheck --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; --------------------------------------------- -- onMobWeaponSkill --------------------------------------------- function onMobWeaponSkill(target, mob, skill) local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); if (mob:getName() == "Kreutzet") then if (mob:actionQueueAbility() == true) then if (mob:getLocalVar("Stormwind") == 0) then mob:setLocalVar("Stormwind", 1); dmgmod = 1.25; info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); elseif (mob:getLocalVar("Stormwind") == 1) then mob:setLocalVar("Stormwind", 0); dmgmod = 1.6; info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); end elseif (mob:actionQueueAbility() == false) then for i = 0, 1 do -- Stormwind 3 times per use. Gets stronger each use. -- TODO: Should be some sort of delay here between ws's.. mob:useMobAbility(926); mob:setLocalVar("Stormwind", 0); end end end target:delHP(dmg); return dmg; end;
gpl-3.0
aquileia/wesnoth
data/ai/lua/patrol.lua
9
1107
function patrol_gen(n, wp) -- n is the name of the unit, like Kiressh -- wp - a table of waypoint tables of form {x,y} wesnoth.message('data/ai/lua/patrol.lua is deprecated. Use the Patrols Micro AI instead.') local unit = wesnoth.get_units({name=n})[1] local x, y = unit.x, unit.y local wpn = 1 --WayPoint Number - we have to remember which waypoint we are heading to if (x == wp[1].x and y == wp[1].y) then wpn = wpn + 1 --w1, w2 = w2, w2 -- if we are standing on the first waypoint, swap them end --local waypoints = {w1, w2} -- this form might be just received from the args local wpcount = # wp local patrol = {} patrol.exec = function() x, y = unit.x, unit.y if (x == wp[wpn].x and y == wp[wpn].y) then wpn = wpn % wpcount + 1 -- advance by one waypoint(this construct loops in range [1, wpcount]) end ai.move_full(unit, wp[wpn].x, wp[wpn].y) -- @note: should we change this to ai.move()? end patrol.eval = function() return 300000 end return patrol end
gpl-2.0
AdamGagorik/darkstar
scripts/globals/items/bunch_of_wild_pamamas.lua
3
2389
----------------------------------------- -- ID: 4596 -- Item: Bunch of Wild Pamamas -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Intelligence 1 -- Additional Effect with Opo-Opo Crown -- HP 50 -- MP 50 -- CHR 14 -- Additional Effect with Kinkobo or -- Primate Staff -- DELAY -90 -- ACC 10 -- Additional Effect with Primate Staff +1 -- DELAY -80 -- ACC 12 ----------------------------------------- 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,PamamasEquip(target),0,1800,4596); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); if (power == 1 or power == 4 or power == 5) then target:addMod(MOD_HP, 50); target:addMod(MOD_MP, 50); target:addMod(MOD_AGI, -3); target:addMod(MOD_CHR, 14); end if (power == 2 or power == 4) then target:addMod(MOD_DELAY, -90); target:addMod(MOD_ACC, 10); end if (power == 3 or power == 5) then target:addMod(MOD_DELAY, -80); target:addMod(MOD_ACC, 12); end target:addMod(MOD_STR, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); if (power == 1 or power == 4 or power == 5) then target:delMod(MOD_HP, 50); target:delMod(MOD_MP, 50); target:delMod(MOD_AGI, -3); target:delMod(MOD_CHR, 14); end if (power == 2 or power == 4) then target:delMod(MOD_DELAY, -90); target:delMod(MOD_ACC, 10); end if (power == 3 or power == 5) then target:delMod(MOD_DELAY, -80); target:delMod(MOD_ACC, 12); end target:delMod(MOD_STR, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Toraimarai_Canal/npcs/qm10.lua
13
1607
----------------------------------- -- Area: Toraimarai Canal -- NPC: ??? -- Involved In Quest: Wild Card -- @zone 169 // not accurate -- @pos 220 16 -50 // not accurate ----------------------------------- 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"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("rootProblem") == 2) then if (player:getVar("rootProblemQ2") <= 1) then if (player:hasStatusEffect(EFFECT_MANAFONT) == true) then player:startEvent(0x2F); else player:startEvent(0x2E); end else player:startEvent(0x2A); end 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 == 0x2F) then player:setVar("rootProblemQ2",2); end end;
gpl-3.0
githubtelebot/Bot-telebot
plugins/filterword.lua
8
2738
local function addword(msg, name) local hash = 'chat:'..msg.to.id..':badword' redis:hset(hash, name, 'newword') return "انجام شد" end local function get_variables_hash(msg) return 'chat:'..msg.to.id..':badword' end local function list_variablesbad(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = 'لیست کلمات ممنوع:\n______________________________\n' for i=1, #names do text = text..'> '..names[i]..'\n' end return text else return end end function clear_commandbad(msg, var_name) --Save on redis local hash = get_variables_hash(msg) redis:del(hash, var_name) return 'پاک شدند' end local function list_variables2(msg, value) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do if string.match(value, names[i]) and not is_momod(msg) then if msg.to.type == 'channel' then delete_msg(msg.id,ok_cb,false) else kick_user(msg.from.id, msg.to.id) return 'شما به دلیل استفاده از کمله غیر مجاز\nاز ادامه گفتگو در این گروه محروم میشوید' end return end --text = text..names[i]..'\n' end end end local function get_valuebad(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return else return value end end end function clear_commandsbad(msg, cmd_name) --Save on redis local hash = get_variables_hash(msg) redis:hdel(hash, cmd_name) return ''..cmd_name..' پاک شد' end local function run(msg, matches) if matches[2] == '+' then if not is_momod(msg) then return 'شما مدیر نیستید' end local name = string.sub(matches[3], 1, 50) local text = addword(msg, name) return text end if matches[1]:lower() == 'filterlist' or matches[1]:lower() == 'لیست فیلتر' then return list_variablesbad(msg) elseif matches[1]:lower() == 'clean' or matches[1] == 'حذف' then if not is_momod(msg) then return end local asd = '1' return clear_commandbad(msg, asd) elseif matches[2] == '-' then if not is_momod(msg) then return '_|_' end return clear_commandsbad(msg, matches[3]) else return list_variables2(msg, matches[1]) end end return { patterns = { "^([Ff]ilter) (.*) (.*)$", "^[/#!]([Ff]ilter) (.*) (.*)$", "^[/#!]([Ff]ilterlist)$", "^([Ff]ilterlist)$", "^[/#!]([Cc]lean) filterlist$", "^([Cc]lean) filterlist$", "^(فیلتر) (.*) (.*)$", "^(لیست فیلتر)$", "^(حذف) لیست فیلتر$", "^(.+)$", }, run = run }
gpl-2.0
AdamGagorik/darkstar
scripts/globals/spells/bluemagic/spiral_spin.lua
31
2001
----------------------------------------- -- Spell: Spiral Spin -- Chance of effect varies with TP. Additional Effect: Accuracy Down -- Spell cost: 39 MP -- Monster Type: Vermin -- Spell Type: Physical (Slashing) -- Blue Magic Points: 3 -- Stat Bonus: STR+1 HP+5 -- Level: 60 -- Casting Time: 4 seconds -- Recast Time: 45 seconds -- Skillchain property: Transfixion (can open Compression, Reverberation, or Distortion) -- Combos: Plantoid Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_SLASH; params.scattr = SC_TRANSFIXION; params.numhits = 1; params.multiplier = 1.925; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 60; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.30; params.int_wsc = 0.10; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if (damage > 0 and chance > 4) then local typeEffect = EFFECT_ACCURACY_DOWN; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Vunkerl_Inlet_[S]/Zone.lua
12
2365
----------------------------------- -- -- Zone: Vunkerl_Inlet_[S] (83) -- ----------------------------------- package.loaded["scripts/zones/Vunkerl_Inlet_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Vunkerl_Inlet_[S]/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/weather"); require("scripts/globals/status"); ----------------------------------- -- 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(-393.238,-50.034,741.199,2); end return cs; end; ----------------------------------- -- onZoneWeatherChange ----------------------------------- function onZoneWeatherChange(weather) local npc = GetNPCByID(17118004); -- Indescript Markings if (npc ~= nil) then if (weather == WEATHER_FOG or weather == WEATHER_THUNDER) then npc:setStatus(STATUS_DISAPPEAR); elseif (VanadielHour() >= 16 or VanadielHour() <= 6) then npc:setStatus(STATUS_NORMAL); end end end; ----------------------------------- -- onGameHour ----------------------------------- function onGameHour() local npc = GetNPCByID(17118004); -- Indescript Markings if (npc ~= nil) then if (VanadielHour() == 16) then npc:setStatus(STATUS_DISAPPEAR); end if (VanadielHour() == 6) then npc:setStatus(STATUS_NORMAL); end end 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
luveti/Urho3D
Source/Urho3D/LuaScript/pkgs/ToCppHook.lua
1
7914
-- -- Copyright (c) 2008-2016 the Urho3D project. -- -- 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. -- local toWrite = {} local currentString = '' local out local WRITE, OUTPUT = write, output function output(s) out = _OUTPUT output = OUTPUT -- restore output(s) end function write(a) if out == _OUTPUT then currentString = currentString .. a if string.sub(currentString,-1) == '\n' then toWrite[#toWrite+1] = currentString currentString = '' end else WRITE(a) end end function post_output_hook(package) local result = table.concat(toWrite) local function replace(pattern, replacement) local k = 0 local nxt, currentString = 1, '' repeat local s, e = string.find(result, pattern, nxt, true) if e then currentString = currentString .. string.sub(result, nxt, s-1) .. replacement nxt = e + 1 k = k + 1 end until not e result = currentString..string.sub(result, nxt) end replace("\t", " ") replace([[#ifndef __cplusplus #include "stdlib.h" #endif #include "string.h" #include "tolua++.h"]], [[// // Copyright (c) 2008-2016 the Urho3D project. // // 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. // #include "Precompiled.h" #include <toluapp/tolua++.h> #include "LuaScript/ToluaUtils.h" #if __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif]]) if not _extra_parameters["Urho3D"] then replace([[#include "LuaScript/ToluaUtils.h"]], [[#include <Urho3D/LuaScript/ToluaUtils.h>]]) end -- Special handling for vector to table conversion which would simplify the implementation of the template functions result = string.gsub(result, "ToluaIs(P?O?D?)Vector([^\"]-)\"c?o?n?s?t? ?P?O?D?Vector<([^*>]-)%*?>\"", "ToluaIs%1Vector%2\"%3\"") result = string.gsub(result, "ToluaPush(P?O?D?)Vector([^\"]-)\"c?o?n?s?t? ?P?O?D?Vector<([^*>]-)%*?>\"", "ToluaPush%1Vector%2\"%3\"") result = string.gsub(result, "@1%(", "(\"\",") -- is_pointer overload uses const char* as signature result = string.gsub(result, "@2%(", "(0.f,") -- is_arithmetic overload uses double as signature WRITE(result) WRITE([[ #if __clang__ #pragma clang diagnostic pop #endif]]) end _push_functions['Component'] = "ToluaPushObject" _push_functions['Resource'] = "ToluaPushObject" _push_functions['UIElement'] = "ToluaPushObject" -- Is Urho3D Vector type. function urho3d_is_vector(t) return t:find("Vector<") ~= nil end -- Is Urho3D PODVector type. function urho3d_is_podvector(t) return t:find("PODVector<") ~= nil end local old_get_push_function = get_push_function local old_get_to_function = get_to_function local old_get_is_function = get_is_function function is_pointer(t) return t:find("*>") end function is_arithmetic(t) for _, type in pairs({ "char", "short", "int", "unsigned", "long", "float", "double", "bool" }) do _, pos = t:find(type) if pos ~= nil and t:sub(pos + 1, pos + 1) ~= "*" then return true end end return false end function overload_if_necessary(t) return is_pointer(t) and "@1" or (is_arithmetic(t) and "@2" or "") end function get_push_function(t) if not urho3d_is_vector(t) then return old_get_push_function(t) end local T = t:match("<.*>") if not urho3d_is_podvector(t) then return "ToluaPushVector" .. T else return "ToluaPushPODVector" .. T .. overload_if_necessary(T) end end function get_to_function(t) if not urho3d_is_vector(t) then return old_get_to_function(t) end local T = t:match("<.*>") if not urho3d_is_podvector(t) then return "ToluaToVector" .. T else return "ToluaToPODVector" .. T .. overload_if_necessary(T) end end function get_is_function(t) if not urho3d_is_vector(t) then return old_get_is_function(t) end local T = t:match("<.*>") if not urho3d_is_podvector(t) then return "ToluaIsVector" .. T else return "ToluaIsPODVector" .. T .. overload_if_necessary(T) end end function get_property_methods_hook(ptype, name) if ptype == "get_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Get"..Name, "Set"..Name end if ptype == "is_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Is"..Name, "Set"..Name end if ptype == "has_set" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return "Has"..Name, "Set"..Name end if ptype == "no_prefix" then local Name = string.upper(string.sub(name, 1, 1))..string.sub(name, 2) return Name, "Set"..Name end end -- Rudimentary checker to prevent function overloads being declared in a wrong order -- The checker assumes function overloads are declared in group one after another within a same pkg file -- The checker only checks for single argument function at the moment, but it can be extended to support more when it is necessary local overload_checker = {name="", has_number=false} function pre_call_hook(self) if table.getn(self.args) ~= 1 then return end if overload_checker.name ~= self.name then overload_checker.name = self.name overload_checker.has_number = false end local t = self.args[1].type if overload_checker.has_number then if t:find("String") or t:find("char*") then warning(self:inclass() .. ":" .. self.name .. " has potential binding problem: number overload becomes dead code if it is declared before string overload") end else overload_checker.has_number = t ~= "bool" and is_arithmetic(t) end end
mit
AdamGagorik/darkstar
scripts/zones/Lufaise_Meadows/TextIDs.lua
15
1194
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. NOTHING_OUT_OF_THE_ORDINARY = 6398; -- There is nothing out of the ordinary here. FISHING_MESSAGE_OFFSET = 7547; -- You can't fish here. -- Conquest CONQUEST = 7213; -- You've earned conquest points! -- Logging LOGGING_IS_POSSIBLE_HERE = 7719; -- Logging is possible here if you have -- Other Texts SURVEY_THE_SURROUNDINGS = 7726; -- You survey the surroundings but see nothing out of the ordinary. MURDEROUS_PRESENCE = 7727; -- Wait, you sense a murderous presence...! YOU_CAN_SEE_FOR_MALMS = 7728; -- You can see for malms in every direction. SPINE_CHILLING_PRESENCE = 7730; -- You sense a spine-chilling presence! KI_STOLEN = 7671; -- The ?Possible Special Code: 01??Possible Special Code: 05?3??BAD CHAR: 80??BAD CHAR: 80? has been stolen! -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results...
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Stellar_Fulcrum/mobs/Kam_lanaut.lua
6
1453
----------------------------------- -- Area: Stellar Fulcrum -- MOB: Kam'lanaut -- Zilart Mission 8 BCNM Fight ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); local blades = {823, 826, 828, 825, 824, 827}; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local changeTime = mob:getLocalVar("changeTime"); local element = mob:getLocalVar("element"); if (changeTime == 0) then mob:setLocalVar("changeTime",math.random(1,3)*15) return; end if (mob:getBattleTime() >= changeTime) then local newelement = element; while (newelement == element) do newelement = math.random(1,6); end if (element ~= 0) then mob:delMod(absorbMod[element], 100); end mob:useMobAbility(blades[newelement]); mob:addMod(absorbMod[newelement], 100); mob:setLocalVar("changeTime", mob:getBattleTime() + math.random(1,3)*15); mob:setLocalVar("element", newelement); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) ally:addTitle(DESTROYER_OF_ANTIQUITY); end;
gpl-3.0
githubtelebot/Bot-telebot
plugins/setstick.lua
7
1261
local function tosticker(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'sticker.webp' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) send_document(get_receiver(msg), file, ok_cb, false) send_large_msg(receiver, 'Done!', ok_cb, false) redis:del("photo:setsticker") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and redis:get("photo:setsticker") then if redis:get("photo:setsticker") == 'waiting' then load_photo(msg.id, tosticker, msg) end end end if matches[1] == "setsticker" and is_sudo(msg) then redis:set("photo:setsticker", "waiting") return 'Please send your photo now' end if matches[1]:lower() == 'beyond' then --[[Your bot name]] send_document(get_receiver(msg), "sticker.webp", ok_cb, false) end end return { patterns = { "^[!#/](setsticker)$", "^([Bb][Ee][Yy][Oo][Nn][Dd])$", "^[!#/]([Bb]eyond)$", "%[(photo)%]", }, run = run, }
gpl-2.0
githubtelebot/Bot-telebot
plugins/help_pv.lua
4
2255
do function run(msg, matches) if msg.to.type == 'user' then return 'Tele Bd Team Command List'..[[ 🔘دستورات پیوی ربات برای اداره کردن گروه🔘 این دستورات فقط مخصوص صاحبان گروه ها هستند: ♨اخراج،بن و حذف بن فرد مورد نظر♨ 💭 [!/]owners group_id [kick|ban|unban] user_id مثال : 💭 [!/]owners 1234567 kick 1234567 ♨پاک کردن قوانین،توضیحات و لیست مدیران♨ 💭 [!/]owners [ایدی گروه] clean [modlist|rules|about] مثال : 💭 [!/]owners 1234567 clean modlist ✅تنظیم حساسیت اسپم✅ 💭 [!/]owners [ایدی گروه] setflood [تعداد] مثال : 💭 [!/]owners 1234567 setflood 17 💡قفل نام و اعضا💡 💭 [!/]owners [ایدی گروه] lock [member|name] مثال : 💭 [!/]owners 1234567 lock member 💡باز کردن نام و اعضا💡 💭 [!/]owner [ایدی گروه] unlock [member|name] مثال : 💭 [!/]owners 1234567 unlock name ▶دریافت لینک و ساخت لینک جدید◀ 💭 [!/]owners [ایدی گروه] get link مثال : 💭 [!/]owners 1234567 get link 💭 [!/]owners [ایدی گروه] new link مثال : 💭 [!/]owners 1234567 new link ⚪تغییر نام،قوانین و توضیحات گروه⚪ 💭 [!/]changename [اسم] [ایدی گروه] مثال : 💭 [!/]changename 123456789 دورهمی 💭 [!/]changrules [متن] [ایدی گروه] مثال : 💭 [!/]changrules 123456789 دعوا ممنوع 💭 [!/]changeabout [متن] [ایدی گروه] مثال 💭 [!/]changeabout 123456789 دورهمی ✴گزارشات گروه✴ 💭 [!/]loggroup [ایدی گروه] مثال : 💭 [!/]loggroup 123456789 🔶جوین به گروه🔶 💭 [!/]join [ایدی گروه] مثال : 💭 [!/]join 123456789 ▶با این دستور ربات شمارو به گروه مورد نظر دعوت میکند ➖➖➖➖➖➖➖ Final Version @TeleBeyond Team Channel : @BeyondTeam Sudo Users : 👤 @SoLiD021 @MrHalix]] end end return { description = "Robot About", usage = "help: View Robot About", patterns = { "^[#!/]help$" }, run = run } end
gpl-2.0
killa78/ForgeUI
ForgeUI/Libs/LibJSON/LibJSON-2.5.lua
13
18391
--[==[ David Kolf's JSON module for Lua 5.1/5.2 Version 2.5 For the documentation see the corresponding readme.txt or visit <http://dkolf.de/src/dkjson-lua.fsl/>. You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. Copyright (C) 2010-2013 David Heiko Kolf 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. --]==] local MAJOR, MINOR = "Lib:dkJSON-2.5", 2 -- Get a reference to the package information if any local APkg = Apollo.GetPackage(MAJOR) -- If there was an older version loaded we need to see if this is newer if APkg and (APkg.nVersion or 0) >= MINOR then return -- no upgrade needed end -- Set a reference to the actual package or create an empty table local JSON = APkg and APkg.tPackage or {} -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, debug.getmetatable, setmetatable, rawset local error, pcall, select = error, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat JSON.version = "dkjson 2.5" local _ENV = nil -- blocking globals in Lua 5.2 JSON.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end JSON.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function JSON.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder, state) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder, state) end local function appendcustom(res, buffer, state) local buflen = state.bufferlen if type (res) == 'string' then buflen = buflen + 1 buffer[buflen] = res end return buflen end local function exception(reason, value, state, buffer, buflen, defaultmessage) defaultmessage = defaultmessage or reason local handler = state.exception if not handler then return nil, defaultmessage else state.bufferlen = buflen local ret, msg = handler (reason, value, state, defaultmessage) if not ret then return nil, msg or defaultmessage end return appendcustom(ret, buffer, state) end end function JSON.encodeexception(reason, value, state, defaultmessage) return quotestring("<" .. defaultmessage .. ">") end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder, state) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return exception('reference cycle', value, state, buffer, buflen) end tables[value] = true state.bufferlen = buflen local ret, msg = valtojson (value, state) if not ret then return exception('custom encoder failed', value, state, buffer, buflen, msg) end tables[value] = nil buflen = appendcustom(ret, buffer, state) elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return exception('reference cycle', value, state, buffer, buflen) end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder, state) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return exception ('unsupported type', value, state, buffer, buflen, "type '" .. valtype .. "' is not supported by JSON.") end return buflen end function JSON.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} state.buffer = buffer updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder, state) if not ret then error (msg, 2) elseif oldbuffer == buffer then state.bufferlen = ret return true else state.bufferlen = nil state.buffer = nil return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end local sub2 = strsub (str, pos, pos + 1) if sub2 == "\239\187" and strsub (str, pos + 2, pos + 2) == "\191" then -- UTF-8 Byte Order Mark pos = pos + 3 elseif sub2 == "//" then pos = strfind (str, "[\n\r]", pos + 2) if not pos then return nil end elseif sub2 == "/*" then pos = strfind (str, "*/", pos + 2) if not pos then return nil end pos = pos + 2 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function JSON.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function JSON:OnLoad() end Apollo.RegisterPackage(JSON, MAJOR, MINOR, {})
mit
AdamGagorik/darkstar
scripts/zones/Port_San_dOria/npcs/Eddy.lua
13
1053
----------------------------------- -- Area: Port San d'Oria -- NPC: Eddy -- Type: NPC Quest Giver -- @zone: 232 -- @pos -5.209 -8.999 39.833 -- -- 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(0x02d3); 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
Anarchid/Zero-K-Infrastructure
Benchmarker/Benchmarks/games/path_test.sdd/Luaui/pathTests/Config/Crossing_4_final.lua
12
1412
local test = { { delayToNextTest = 300, unitList = {}, }, { delayToNextTest = 300, unitList = {}, }, { delayToNextTest = 300, unitList = {}, }, { delayToNextTest = 300, unitList = {}, }, } local MAX_DELAY_FACTOR = 1.75 local stepSize = 128 local units = { "corak", "corraid", "corsh", "correap", "corak", "corraid", "corsh", "correap", } local x1 = 128 local x2 = Game.mapSizeX - x1 for testNum = 1,#test do if units[testNum] and UnitDefNames[units[testNum]] then local unitDef = UnitDefNames[units[testNum]] local unitList = test[testNum].unitList local maxTravelTime = ((x1 - x2))/unitDef.speed * 30 * MAX_DELAY_FACTOR if maxTravelTime < 0 then maxTravelTime = -maxTravelTime end for z = stepSize, Game.mapSizeZ - stepSize, stepSize do local y1 = Spring.GetGroundHeight(x1, z) local y2 = Spring.GetGroundHeight(x2, z) unitList[#unitList+1] = { unitName = units[testNum], teamID = 0, startCoordinates = {x1, y1, z}, destinationCoordinates = {{x2, y2, z}}, maxTargetDist = 40, maxTravelTime = maxTravelTime, } end --Spring.Echo("Max travel time for " .. units[testNum] .. ": " .. maxTravelTime) --Spring.Log(widget:GetInfo().name, "info", "Max travel time for " .. units[testNum] .. ": " .. maxTravelTime) else Spring.Log(widget:GetInfo().name, "warning", "invalid unit name for path test") end end return test
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Wajaom_Woodlands/mobs/Tinnin.lua
2
5519
----------------------------------- -- Area: Wajoam Woodlands -- MOB: Tinnin -- @pos 276 0 -694 -- Spawned with Monkey Wine: @additem 2573 -- Wiki: http://ffxiclopedia.wikia.com/wiki/Tinnin ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_MAIN_2HOUR, 1); mob:setMobMod(MOBMOD_GIL_MIN, 12000); mob:setMobMod(MOBMOD_GIL_MAX, 30000); mob:setMobMod(MOBMOD_MUG_GIL, 8000); mob:setMobMod(MOBMOD_DRAW_IN, 1); mob:setMod(MOD_UDMGBREATH, 0); -- immune to breath damage end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setHP(mob:getMaxHP()/2); mob:setUnkillable(true); mob:setMod(MOD_REGEN, 50); -- Regen Head every 1.5-4 minutes 90-240 mob:setLocalVar("headTimer", os.time() + math.random(60,190)); -- Number of crits to lose a head mob:setLocalVar("CritToTheFace", math.random(10,30)); mob:setLocalVar("crits", 0); end; ----------------------------------- -- onMobRoam Action -- Regen head ----------------------------------- function onMobRoam(mob) local headTimer = mob:getLocalVar("headTimer"); if (mob:AnimationSub() == 2 and os.time() > headTimer) then mob:AnimationSub(1); mob:setLocalVar("headTimer", os.time() + math.random(60,190)); -- First time it regens second head, 25%. Reduced afterwards. if (mob:getLocalVar("secondHead") == 0) then mob:addHP(mob:getMaxHP() * .25); mob:setLocalVar("secondHead", 1); else mob:addHP(mob:getMaxHP() * .05); end elseif (mob:AnimationSub() == 1 and os.time() > headTimer) then mob:AnimationSub(0); mob:setLocalVar("headTimer", os.time() + math.random(60,190)); -- First time it regens third head, 25%. Reduced afterwards. if (mob:getLocalVar("thirdHead") == 0) then mob:addHP(mob:getMaxHP() * .25); mob:setMod(MOD_REGEN, 10); mob:setLocalVar("thirdHead", 1); mob:setUnkillable(false); -- It can be killed now that has all his heads else mob:addHP(mob:getMaxHP() * .05); end end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local headTimer = mob:getLocalVar("headTimer"); if (mob:AnimationSub() == 2 and os.time() > headTimer) then mob:AnimationSub(1); mob:setLocalVar("headTimer", os.time() + math.random(60,190)); -- First time it regens second head, 25%. Reduced afterwards. if (mob:getLocalVar("secondHead") == 0) then mob:addHP(mob:getMaxHP() * .25); mob:setLocalVar("secondHead", 1); else mob:addHP(mob:getMaxHP() * .05); end if (bit.band(mob:getBehaviour(),BEHAVIOUR_NO_TURN) > 0) then -- disable no turning for the forced mobskills upon head growth mob:setBehaviour(bit.band(mob:getBehaviour(), bit.bnot(BEHAVIOUR_NO_TURN))) end mob:useMobAbility(1832); -- Barofield mob:useMobAbility(1830); -- Polar Blast elseif (mob:AnimationSub() == 1 and os.time() > headTimer) then mob:AnimationSub(0); mob:setLocalVar("headTimer", os.time() + math.random(60,190)); -- First time it regens third head, 25%. Reduced afterwards. if (mob:getLocalVar("thirdHead") == 0) then mob:setMod(MOD_REGEN, 10); mob:addHP(mob:getMaxHP() * .25); mob:setLocalVar("thirdHead", 1); mob:setUnkillable(false); -- It can be killed now that has all his heads else mob:addHP(mob:getMaxHP() * .05); end if (bit.band(mob:getBehaviour(),BEHAVIOUR_NO_TURN) > 0) then -- disable no turning for the forced mobskills upon head growth mob:setBehaviour(bit.band(mob:getBehaviour(), bit.bnot(BEHAVIOUR_NO_TURN))) end mob:useMobAbility(1832); -- Barofield mob:useMobAbility(1830); -- Polar Blast mob:useMobAbility(1828); -- Pyric Blast end end; ----------------------------------- -- onCriticalHit ----------------------------------- function onCriticalHit(mob) local critNum = mob:getLocalVar("crits"); if ((critNum+1) > mob:getLocalVar("CritToTheFace")) then -- Lose a head if (mob:AnimationSub() == 0) then mob:AnimationSub(1); mob:setLocalVar("headTimer", os.time() + math.random(60,190)); elseif (mob:AnimationSub() == 1) then mob:AnimationSub(2); mob:setLocalVar("headTimer", os.time() + math.random(60,190)); else -- Meh end -- Number of crits to lose a head, re-randoming mob:setLocalVar("CritToTheFace", math.random(10,30)); critNum = 0; -- reset the crits on the NM else critNum = critNum + 1; end mob:setLocalVar("crits", critNum); end; ----------------------------------- -- onMobDrawIn ----------------------------------- function onMobDrawIn(mob, target) mob:addTP(3000); -- Uses a mobskill upon drawing in a player. Not necessarily on the person drawn in. end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/spells/sheepfoe_mambo.lua
27
1608
----------------------------------------- -- Spell: Sheepfoe Mambo -- Grants evasion bonus to all members. ----------------------------------------- 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); -- Since nobody knows the evasion values for mambo, I'll just make shit up! (aka - same as madrigal) local power = 5; if (sLvl+iLvl > 85) then power = power + math.floor((sLvl+iLvl-85) / 18); end if (power >= 15) then power = 15; end local iBoost = caster:getMod(MOD_MAMBO_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end 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_MAMBO,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(75); end return EFFECT_MAMBO; end;
gpl-3.0
sjznxd/lc-20130204
libs/core/luasrc/ccache.lua
82
1863
--[[ 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$ ]]-- local io = require "io" local fs = require "nixio.fs" local util = require "luci.util" local nixio = require "nixio" local debug = require "debug" local string = require "string" local package = require "package" local type, loadfile = type, loadfile module "luci.ccache" function cache_ondemand(...) if debug.getinfo(1, 'S').source ~= "=?" then cache_enable(...) end end function cache_enable(cachepath, mode) cachepath = cachepath or "/tmp/luci-modulecache" mode = mode or "r--r--r--" local loader = package.loaders[2] local uid = nixio.getuid() if not fs.stat(cachepath) then fs.mkdir(cachepath) end local function _encode_filename(name) local encoded = "" for i=1, #name do encoded = encoded .. ("%2X" % string.byte(name, i)) end return encoded end local function _load_sane(file) local stat = fs.stat(file) if stat and stat.uid == uid and stat.modestr == mode then return loadfile(file) end end local function _write_sane(file, func) if nixio.getuid() == uid then local fp = io.open(file, "w") if fp then fp:write(util.get_bytecode(func)) fp:close() fs.chmod(file, mode) end end end package.loaders[2] = function(mod) local encoded = cachepath .. "/" .. _encode_filename(mod) local modcons = _load_sane(encoded) if modcons then return modcons end -- No cachefile modcons = loader(mod) if type(modcons) == "function" then _write_sane(encoded, modcons) end return modcons end end
apache-2.0
AdamGagorik/darkstar
scripts/zones/Crawlers_Nest/Zone.lua
13
1919
----------------------------------- -- -- Zone: Crawlers_Nest (197) -- ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Crawlers_Nest/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17584492,17584493}; SetGroundsTome(tomes); UpdateTreasureSpawnPoint(17584471); UpdateTreasureSpawnPoint(17584472); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(380.617,-34.61,4.581,59); end return cs; 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; ----------------------------------- -- 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
likeleon/Cnc
mods/cnc/maps/cnc64gdi01/cnc64gdi01.lua
19
6339
CommandoReinforcements = { "rmbo" } MCVReinforcements = { "mcv" } inf1 = { "e4" } AutocreateSquads = { { "stnk", "stnk" }, { "ftnk", "ftnk" }, { "ltnk", "ltnk", "bike" }, { "arty", "arty", "bike", "bike" }, { "ltnk", "ltnk" }, { "stnk", "stnk" }, { "ltnk", "ltnk" }, { "arty", "arty" } } HeliPatrolPaths = { { HeliPatrol1.Location, HeliPatrol2.Location, HeliPatrol3.Location, HeliPatrol4.Location, HeliPatrol5.Location, HeliPatrol6.Location }, { HeliPatrol5.Location, HeliPatrol4.Location, HeliPatrol3.Location, HeliPatrol2.Location, HeliPatrol1.Location, HeliPatrol6.Location } } AttackTriggers = { AttackTrigger1, AttackTrigger2, AttackTrigger3, AttackTrigger4 } harvester = { "harv" } SamSites = { SAM01, SAM02 } WorldLoaded = function() player = Player.GetPlayer("GDI") enemy = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) destroySAMsCenterObjective = player.AddPrimaryObjective("Destroy the SAM sites protecting the Obelisk.") destroyObeliskObjective = player.AddPrimaryObjective("Destroy the Obelisk.") destroyBiotechCenterObjective = player.AddPrimaryObjective("Destroy the biotech facility.") Trigger.OnAllKilled(SamSites, function() AirSupport = Actor.Create("airstrike.proxy", true, { Owner = player }) AirSupportEnabled = true player.MarkCompletedObjective(destroySAMsCenterObjective) end) Trigger.OnDamaged(Obelisk01, function() Trigger.AfterDelay(DateTime.Seconds(1), Obelisk01.Kill) end) Trigger.OnKilled(Obelisk01, function() player.MarkCompletedObjective(destroyObeliskObjective) Trigger.AfterDelay(DateTime.Seconds(5), function() Reinforce(MCVReinforcements) end) ObeliskFlare.Destroy() if AirSupportEnabled then AirSupport.Destroy() end end) Trigger.OnKilled(Biolab, function() player.MarkCompletedObjective(destroyBiotechCenterObjective) end) Trigger.OnCapture(Biolab, function() Biolab.Kill() end) Trigger.OnDamaged(Biolab, HuntTriggerFunction) AIRepairBuildings(enemy) AIRebuildHarvesters(enemy) Utils.Do(AttackTriggers, function(a) Trigger.OnKilledOrCaptured(a, function() NodVehicleProduction(Utils.Random(AutocreateSquads)) end) end) Trigger.AfterDelay(DateTime.Seconds(150), AutoCreateTeam) Trigger.AfterDelay(DateTime.Minutes(5), HeliHunt) NodInfantryProduction() Camera.Position = UnitsRally.CenterPosition ObeliskFlare = Actor.Create('flare', true, { Owner = player, Location = Flare.Location }) Reinforce(CommandoReinforcements) end Tick = function() if DateTime.GameTime > DateTime.Seconds(5) and player.HasNoRequiredUnits() then player.MarkFailedObjective(destroyBiotechCenterObjective) end end Reinforce = function(units) Media.PlaySpeechNotification(player, "Reinforce") ReinforceWithLandingCraft(units, lstStart.Location, lstEnd.Location, UnitsRally.Location) end ReinforceWithLandingCraft = function(units, transportStart, transportUnload, rallypoint) local transport = Actor.Create("oldlst", true, { Owner = player, Facing = 0, Location = transportStart }) local subcell = 0 Utils.Do(units, function(a) transport.LoadPassenger(Actor.Create(a, false, { Owner = transport.Owner, Facing = transport.Facing, Location = transportUnload, SubCell = subcell })) subcell = subcell + 1 end) transport.ScriptedMove(transportUnload) transport.CallFunc(function() Utils.Do(units, function() local a = transport.UnloadPassenger() a.IsInWorld = true a.MoveIntoWorld(transport.Location - CVec.New(0, 1)) if rallypoint ~= nil then a.Move(rallypoint) end end) end) transport.Wait(5) transport.ScriptedMove(transportStart) transport.Destroy() end HuntTriggerFunction = function() local list = enemy.GetGroundAttackers() Utils.Do(list, function(unit) IdleHunt(unit) end) end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, function() unit.AttackMove(UnitsRally.Location, 50) unit.Hunt() end) end end NodInfantryProduction = function() if HandOfNod.IsDead or HandOfNod.Owner == player then return end HandOfNod.Build(inf1, SquadHunt) Trigger.AfterDelay(DateTime.Seconds(15), NodInfantryProduction) end NodVehicleProduction = function(Squad) if Airfield.IsDead or not Airfield.Owner == enemy then return end Airfield.Build(Squad, SquadHunt) end AIRepairBuildings = function(ai) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == ai and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == ai and building.Health < 0.9 * building.MaxHealth then building.StartBuildingRepairs() end end) end end) end HeliHunt = function() local helicopters = enemy.GetActorsByType("heli") local patrolpath = Utils.Random(HeliPatrolPaths) Utils.Do(helicopters, function(actor) Trigger.OnIdle(actor, function() actor.Patrol(patrolpath) end) end) end SquadHunt = function(actors) Utils.Do(actors, function(actor) Trigger.OnIdle(actor, function() actor.AttackMove(UnitsRally.Location, 50) actor.Hunt() end) end) end AIRebuildHarvesters = function(ai) if AIHarvesterCount == NIL or AIHarvesterCount == 0 then AIHarvesterCount = #ai.GetActorsByType("harv") IsBuildingHarvester = false end local CurrentHarvesterCount = #ai.GetActorsByType("harv") if CurrentHarvesterCount < AIHarvesterCount and Airfield.Owner == enemy and not IsBuildingHarvester and not Airfield.IsDead then IsBuildingHarvester = true Airfield.Build(harvester, function() IsBuildingHarvester = false end) end Trigger.AfterDelay(DateTime.Seconds(5), function() AIRebuildHarvesters(ai) end) end AutoCreateTeam = function() NodVehicleProduction(Utils.Random(AutocreateSquads)) Trigger.AfterDelay(DateTime.Seconds(150), AutoCreateTeam) end
gpl-2.0
adib1380/anti2
bot/bot.lua
2
7076
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '0.14.6' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then print('\27[36mNot valid: Telegram message\27[39m') return false end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then if plugins[disabled_plugin].hidden then print('Plugin '..disabled_plugin..' is disabled on this chat') else local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) end return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "echo", "get", "google", "groupmanager", "help", "id", "images", "img_google", "location", "media", "plugins", "channels", "set", "stats", "time", "version", "weather", "youtube", "media_handler", "moderation"}, sudo_users = {105521224}, disabled_channels = {}, moderation = {data = 'data/moderation.json'} } serialize_to_file(config, './data/config.lua') print ('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 5 mins postpone (cron_plugins, false, 5*60.0) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
Hostle/luci
protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_pppoe.lua
47
3729
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local username, password, ac, service local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true ac = section:taboption("general", Value, "ac", translate("Access Concentrator"), translate("Leave empty to autodetect")) ac.placeholder = translate("auto") service = section:taboption("general", Value, "service", translate("Service Name"), translate("Leave empty to autodetect")) service.placeholder = translate("auto") if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6") ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_failure.write = keepalive_interval.write keepalive_failure.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
apache-2.0
robertfoss/nodemcu-firmware
lua_examples/irsend.lua
88
1803
------------------------------------------------------------------------------ -- IR send module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- dofile("irsend.lua").nec(4, 0x00ff00ff) ------------------------------------------------------------------------------ local M do -- const local NEC_PULSE_US = 1000000 / 38000 local NEC_HDR_MARK = 9000 local NEC_HDR_SPACE = 4500 local NEC_BIT_MARK = 560 local NEC_ONE_SPACE = 1600 local NEC_ZERO_SPACE = 560 local NEC_RPT_SPACE = 2250 -- cache local gpio, bit = gpio, bit local mode, write = gpio.mode, gpio.write local waitus = tmr.delay local isset = bit.isset -- NB: poorman 38kHz PWM with 1/3 duty. Touch with care! ) local carrier = function(pin, c) c = c / NEC_PULSE_US while c > 0 do write(pin, 1) write(pin, 0) c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c * 1 c = c * 1 c = c * 1 c = c - 1 end end -- tsop signal simulator local pull = function(pin, c) write(pin, 0) waitus(c) write(pin, 1) end -- NB: tsop mode allows to directly connect pin -- inplace of TSOP input local nec = function(pin, code, tsop) local pulse = tsop and pull or carrier -- setup transmitter mode(pin, 1) write(pin, tsop and 1 or 0) -- header pulse(pin, NEC_HDR_MARK) waitus(NEC_HDR_SPACE) -- sequence, lsb first for i = 31, 0, -1 do pulse(pin, NEC_BIT_MARK) waitus(isset(code, i) and NEC_ONE_SPACE or NEC_ZERO_SPACE) end -- trailer pulse(pin, NEC_BIT_MARK) -- done transmitter --mode(pin, 0, tsop and 1 or 0) end -- expose M = { nec = nec, } end return M
mit
likeleon/Cnc
mods/cnc/maps/funpark01/scj01ea.lua
19
3578
RifleReinforcments = { "e1", "e1", "e1", "bike" } BazookaReinforcments = { "e3", "e3", "e3", "bike" } BikeReinforcments = { "bike" } ReinforceWithLandingCraft = function(units, transportStart, transportUnload, rallypoint) local transport = Actor.Create("oldlst", true, { Owner = player, Facing = 0, Location = transportStart }) local subcell = 0 Utils.Do(units, function(a) transport.LoadPassenger(Actor.Create(a, false, { Owner = transport.Owner, Facing = transport.Facing, Location = transportUnload, SubCell = subcell })) subcell = subcell + 1 end) transport.ScriptedMove(transportUnload) transport.CallFunc(function() Utils.Do(units, function() local a = transport.UnloadPassenger() a.IsInWorld = true a.MoveIntoWorld(transport.Location - CVec.New(0, 1)) if rallypoint ~= nil then a.Move(rallypoint) end end) end) transport.Wait(5) transport.ScriptedMove(transportStart) transport.Destroy() Media.PlaySpeechNotification(player, "Reinforce") end WorldLoaded = function() player = Player.GetPlayer("Nod") dinosaur = Player.GetPlayer("Dinosaur") civilian = Player.GetPlayer("Civilian") InvestigateObj = player.AddPrimaryObjective("Investigate the nearby village for reports of \nstrange activity.") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) ReachVillageObj = player.AddPrimaryObjective("Reach the village.") Trigger.OnPlayerDiscovered(civilian, function(_, discoverer) if discoverer == player and not player.IsObjectiveCompleted(ReachVillageObj) then if not dinosaur.HasNoRequiredUnits() then KillDinos = player.AddPrimaryObjective("Kill all creatures in the area.") end player.MarkCompletedObjective(ReachVillageObj) end end) DinoTric.Patrol({WP0.Location, WP1.Location}, true, 3) DinoTrex.Patrol({WP2.Location, WP3.Location}, false) Trigger.OnIdle(DinoTrex, DinoTrex.Hunt) ReinforceWithLandingCraft(RifleReinforcments, SeaEntryA.Location, BeachReinforceA.Location, BeachReinforceA.Location) Trigger.AfterDelay(DateTime.Seconds(1), function() InitialUnitsArrived = true end) Trigger.AfterDelay(DateTime.Seconds(15), function() ReinforceWithLandingCraft(BazookaReinforcments, SeaEntryB.Location, BeachReinforceB.Location, BeachReinforceB.Location) end) if Map.Difficulty == "Easy" then Trigger.AfterDelay(DateTime.Seconds(25), function() ReinforceWithLandingCraft(BikeReinforcments, SeaEntryA.Location, BeachReinforceA.Location, BeachReinforceA.Location) end) Trigger.AfterDelay(DateTime.Seconds(30), function() ReinforceWithLandingCraft(BikeReinforcments, SeaEntryB.Location, BeachReinforceB.Location, BeachReinforceB.Location) end) end Camera.Position = CameraStart.CenterPosition end Tick = function() if InitialUnitsArrived then if player.HasNoRequiredUnits() then player.MarkFailedObjective(InvestigateObj) end if dinosaur.HasNoRequiredUnits() then if KillDinos then player.MarkCompletedObjective(KillDinos) end player.MarkCompletedObjective(InvestigateObj) end end end
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Port_Windurst/npcs/Shanruru.lua
13
2884
----------------------------------- -- Area: Port Windurst -- NPC: Shanruru -- Involved in Quest: Riding on the Clouds -- @zone 240 -- @pos -1 -6 187 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 5) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_4",0); player:tradeComplete(); player:addKeyItem(SPIRITED_STONE); player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET); OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS); if (player:getQuestStatus(WINDURST,THE_PROMISE) == QUEST_COMPLETED) then Message = math.random(0,1) if (Message == 1) then player:startEvent(0x0211); else player:startEvent(0x021d); end elseif (player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS) == QUEST_ACCEPTED) then player:startEvent(0x01f8); elseif (OnionRings == QUEST_COMPLETED) then player:startEvent(0x01be); elseif (OnionRings == QUEST_ACCEPTED ) then player:startEvent(0x01b7); elseif (InspectorsGadget == QUEST_COMPLETED) then player:startEvent(0x01ac); elseif (InspectorsGadget == QUEST_ACCEPTED) then player:startEvent(0x01a4); elseif (player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS) == QUEST_COMPLETED) then player:startEvent(0x019c); elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then player:startEvent(0x0180); elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then player:startEvent(0x0179); else player:startEvent(0x016f); 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); end;
gpl-3.0
Hostle/luci
applications/luci-app-pbx/luasrc/model/cbi/pbx-advanced.lua
18
14476
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx 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 of the License, or (at your option) any later version. luci-pbx 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. You should have received a copy of the GNU General Public License along with luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end appname = "PBX" modulename = "pbx-advanced" defaultbindport = 5060 defaultrtpstart = 19850 defaultrtpend = 19900 -- Returns all the network related settings, including a constructed RTP range function get_network_info() externhost = m.uci:get(modulename, "advanced", "externhost") ipaddr = m.uci:get("network", "lan", "ipaddr") bindport = m.uci:get(modulename, "advanced", "bindport") rtpstart = m.uci:get(modulename, "advanced", "rtpstart") rtpend = m.uci:get(modulename, "advanced", "rtpend") if bindport == nil then bindport = defaultbindport end if rtpstart == nil then rtpstart = defaultrtpstart end if rtpend == nil then rtpend = defaultrtpend end if rtpstart == nil or rtpend == nil then rtprange = nil else rtprange = rtpstart .. "-" .. rtpend end return bindport, rtprange, ipaddr, externhost end -- If not present, insert empty rules in the given config & section named PBX-SIP and PBX-RTP function insert_empty_sip_rtp_rules(config, section) -- Add rules named PBX-SIP and PBX-RTP if not existing found_sip_rule = false found_rtp_rule = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' then found_sip_rule = true elseif s1._name == 'PBX-RTP' then found_rtp_rule = true end end) if found_sip_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-SIP') end if found_rtp_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-RTP') end end -- Delete rules in the given config & section named PBX-SIP and PBX-RTP function delete_sip_rtp_rules(config, section) -- Remove rules named PBX-SIP and PBX-RTP commit = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' or s1._name == 'PBX-RTP' then m.uci:delete(config, s1['.name']) commit = true end end) -- If something changed, then we commit the config. if commit == true then m.uci:commit(config) end end -- Deletes QoS rules associated with this PBX. function delete_qos_rules() delete_sip_rtp_rules ("qos", "classify") end function insert_qos_rules() -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("qos", "classify") -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() -- Iterate through the QoS rules, and if there is no other rule with the same port -- range at the priority service level, insert this rule. commit = false m.uci:foreach("qos", "classify", function(s1) if s1._name == 'PBX-SIP' then if s1.ports ~= bindport or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", bindport) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end elseif s1._name == 'PBX-RTP' then if s1.ports ~= rtprange or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", rtprange) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end end end) -- If something changed, then we commit the qos config. if commit == true then m.uci:commit("qos") end end -- This function is a (so far) unsuccessful attempt to manipulate the firewall rules from here -- Need to do more testing and eventually move to this mode. function maintain_firewall_rules() -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() commit = false -- Only if externhost is set, do we control firewall rules. if externhost ~= nil and bindport ~= nil and rtprange ~= nil then -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("firewall", "rule") -- Iterate through the firewall rules, and if the dest_port and dest_ip setting of the\ -- SIP and RTP rule do not match what we want configured, set all the entries in the rule\ -- appropriately. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then if s1.dest_port ~= bindport then m.uci:set("firewall", s1['.name'], "dest_port", bindport) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end elseif s1._name == 'PBX-RTP' then if s1.dest_port ~= rtprange then m.uci:set("firewall", s1['.name'], "dest_port", rtprange) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end end end) else -- We delete the firewall rules if one or more of the necessary parameters are not set. sip_rule_name=nil rtp_rule_name=nil -- First discover the configuration names of the rules. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then sip_rule_name = s1['.name'] elseif s1._name == 'PBX-RTP' then rtp_rule_name = s1['.name'] end end) -- Then, using the names, actually delete the rules. if sip_rule_name ~= nil then m.uci:delete("firewall", sip_rule_name) commit = true end if rtp_rule_name ~= nil then m.uci:delete("firewall", rtp_rule_name) commit = true end end -- If something changed, then we commit the firewall config. if commit == true then m.uci:commit("firewall") end end m = Map (modulename, translate("Advanced Settings"), translate("This section contains settings that do not need to be changed under \ normal circumstances. In addition, here you can configure your system \ for use with remote SIP devices, and resolve call quality issues by enabling \ the insertion of QoS rules.")) -- Recreate the voip server config, and restart necessary services after changes are commited -- to the advanced configuration. The firewall must restart because of "Remote Usage". function m.on_after_commit(self) -- Make sure firewall rules are in place maintain_firewall_rules() -- If insertion of QoS rules is enabled if m.uci:get(modulename, "advanced", "qos_enabled") == "yes" then insert_qos_rules() else delete_qos_rules() end luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/firewall restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(NamedSection, "advanced", "settings", translate("Advanced Settings")) s.anonymous = true s:tab("general", translate("General Settings")) s:tab("remote_usage", translate("Remote Usage"), translatef("You can use your SIP devices/softphones with this system from a remote location \ as well, as long as your Internet Service Provider gives you a public IP. \ You will be able to call other local users for free (e.g. other Analog Telephone Adapters (ATAs)) \ and use your VoIP providers to make calls as if you were local to the PBX. \ After configuring this tab, go back to where users are configured and see the new \ Server and Port setting you need to configure the remote SIP devices with. Please note that if this \ PBX is not running on your router/gateway, you will need to configure port forwarding (NAT) on your \ router/gateway. Please forward the ports below (SIP port and RTP range) to the IP address of the \ device running this PBX.")) s:tab("qos", translate("QoS Settings"), translate("If you experience jittery or high latency audio during heavy downloads, you may want \ to enable QoS. QoS prioritizes traffic to and from your network for specified ports and IP \ addresses, resulting in better latency and throughput for sound in our case. If enabled below, \ a QoS rule for this service will be configured by the PBX automatically, but you must visit the \ QoS configuration page (Network->QoS) to configure other critical QoS settings like Download \ and Upload speed.")) ringtime = s:taboption("general", Value, "ringtime", translate("Number of Seconds to Ring"), translate("Set the number of seconds to ring users upon incoming calls before hanging up \ or going to voicemail, if the voicemail is installed and enabled.")) ringtime.datatype = "port" ringtime.default = 30 ua = s:taboption("general", Value, "useragent", translate("User Agent String"), translate("This is the name that the VoIP server will use to identify itself when \ registering to VoIP (SIP) providers. Some providers require this to a specific \ string matching a hardware SIP device.")) ua.default = appname h = s:taboption("remote_usage", Value, "externhost", translate("Domain/IP Address/Dynamic Domain"), translate("You can enter your domain name, external IP address, or dynamic domain name here. \ The best thing to input is a static IP address. If your IP address is dynamic and it changes, \ your configuration will become invalid. Hence, it's recommended to set up Dynamic DNS in this case. \ and enter your Dynamic DNS hostname here. You can configure Dynamic DNS with the luci-app-ddns package.")) h.datatype = "host(0)" p = s:taboption("remote_usage", Value, "bindport", translate("External SIP Port"), translate("Pick a random port number between 6500 and 9500 for the service to listen on. \ Do not pick the standard 5060, because it is often subject to brute-force attacks. \ When finished, (1) click \"Save and Apply\", and (2) look in the \ \"SIP Device/Softphone Accounts\" section for updated Server and Port settings \ for your SIP Devices/Softphones.")) p.datatype = "port" p = s:taboption("remote_usage", Value, "rtpstart", translate("RTP Port Range Start"), translate("RTP traffic carries actual voice packets. This is the start of the port range \ that will be used for setting up RTP communication. It's usually OK to leave this \ at the default value.")) p.datatype = "port" p.default = defaultrtpstart p = s:taboption("remote_usage", Value, "rtpend", translate("RTP Port Range End")) p.datatype = "port" p.default = defaultrtpend p = s:taboption("qos", ListValue, "qos_enabled", translate("Insert QoS Rules")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
apache-2.0
AdamGagorik/darkstar
scripts/globals/mobskills/Gates_of_Hades.lua
33
1414
--------------------------------------------- -- Gates of Hades -- -- Description: Deals severe Fire damage to enemies within an area of effect. Additional effect: Burn -- Type: Magical -- -- -- Utsusemi/Blink absorb: Wipes shadows -- Range: 20' radial -- Notes: Only used when a cerberus's health is 25% or lower (may not be the case for Orthrus). The burn effect takes off upwards of 20 HP per tick. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1793) then return 0; else return 1; end end local result = 1; local mobhp = mob:getHPP(); if (mobhp <= 25) then result = 0; end; return result; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_BURN; local power = 21; MobStatusEffectMove(mob, target, typeEffect, power, 3, 60); local dmgmod = 1.8; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*6,ELE_FIRE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
nerdclub-tfg/telegram-bot
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
mohammad25253/seed238
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
mahmedhany128/Mr_BOT
plugins/tagall.lua
3
2005
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY faeder ▀▄ ▄▀ ▀▄ ▄▀ BY faeder (@xXxDev_iqxXx) ▀▄ ▄▀ ▀▄ ▄▀ Making the file by faeder ▀▄ ▄▀ ▀▄ ▄▀ tagall : تاك للكل ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function tagall(cb_extra, success, result) local receiver = cb_extra.receiver local text = '' local msgss = 0 for k,v in pairs(result.members) do if v.username then msgss = msgss + 1 text = text..msgss.."- @"..v.username.."\n" end end text = text.."\n"..cb_extra.msg_text send_large_msg(receiver, text) end local function tagall2(cb_extra, success, result) local receiver = cb_extra.receiver local text = '' local msgss = 0 for k,v in pairs(result) do if v.username then msgss = msgss + 1 text = text..msgss.."- @"..v.username.."\n" end end text = text.."\n"..cb_extra.msg_text send_large_msg(receiver, text) end local function Memo(msg, matches) local receiver = get_receiver(msg) if not is_momod(msg) then return "لتبعبص 😒 (me soon( 😌 مو شغلك ابني🚶" end if matches[1] then if msg.to.type == 'chat' then chat_info(receiver, tagall, {receiver = receiver,msg_text = matches[1]}) elseif msg.to.type == 'channel' then channel_get_users(receiver, tagall2, {receiver = receiver,msg_text = matches[1]}) end end return end return { description = "Will tag all ppl with a msg.", usage = { "اشارة للكل [msg]." }, patterns = { "^تاك +(.+)$" }, run = Memo } -- BY Dev - @xXxDev_iqxXx
gpl-2.0
D-m-L/evonara
modules/libs/dkjson.lua
2
25175
-- Module options: local always_try_using_lpeg = true --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.2* This module writes no global values, not even the module table. Import it using json = require ("dkjson") Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.2"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'kolf' at the e-mail provider 'gmx.de'. --------------------------------------------------------------------- *Copyright (C) 2010, 2011, 2012 David Heiko Kolf* 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. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local concat = table.concat local _ENV = nil -- blocking globals in Lua 5.2 --Johnm -- made global instead of local json = { version = "dkjson 2.2" } pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = tostring (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = tonumber (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") local pegmatch = g.match local P, S, R, V = g.P, g.S, g.R, g.V local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/tonumber local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
mit
rigeirani/bbb
plugins/plugins.lua
72
6113
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❎' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✅' end nact = nact+1 end if not only_enabled or status == '✅' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❎' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✅' end nact = nact+1 end if not only_enabled or status == '✅' then -- get the name v = string.match (v, "(.*)%.lua") -- text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == '+' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == '-' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (+) ([%w_%.%-]+)$", "^!plugins? (-) ([%w_%.%-]+)$", "^!plugins? (+) ([%w_%.%-]+) (chat)", "^!plugins? (-) ([%w_%.%-]+) (chat)", "^!plugins? (*)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
shakib01/anonymous01
bot/seedbot.lua
1
10270
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "admin" }, sudo_users = {139349397,,,,,},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Our team! Alphonse (@Iwals) I M /-\ N (@Imandaneshi) Siyanew (@Siyanew) Rondoozle (@Potus) Seyedan (@Seyedan25) Special thanks to: Juan Potato Siyanew Topkecleon Vamptacus Our channels: English: @TeleSeedCH Persian: @IranSeed ]], help_text_realm = [[ Realm Commands: !creategroup [name] Create a group !createrealm [name] Create a realm !setname [name] Set realm name !setabout [group_id] [text] Set a group's about text !setrules [grupo_id] [text] Set a group's rules !lock [grupo_id] [setting] Lock a group's setting !unlock [grupo_id] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [grupo_id] Kick all memebers and delete group !kill realm [realm_id] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Get a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups » Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id Return group id or user id !help Get commands list !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules [text] Set [text] as rules !set about [text] Set [text] as about !settings Returns group settings !newlink Create/revoke your group link !link Returns group link !owner Returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] [text] Save [text] as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] Returns user id !log Will return group logs !banlist Will return group ban list » U can use both "/" and "!" » Only mods, owner and admin can add bots in group » Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands » Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Qufim_Island/npcs/Matica_RK.lua
13
3323
----------------------------------- -- Area: Qufim Island -- NPC: Matica, R.K. -- Type: Border Conquest Guards -- @pos 179.093 -21.575 -15.282 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; 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_SIGIL); player:delStatusEffect(EFFECT_SANCTION); 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
Laeeth/dub
test/function_test.lua
4
2605
--[[------------------------------------------------------ dub.Function ------------ ... --]]------------------------------------------------------ local lub = require 'lub' local lut = require 'lut' local dub = require 'dub' local should = lut.Test 'dub.Function' local ins = dub.Inspector { doc_dir = 'test/tmp', INPUT = 'test/fixtures/simple/include', } local Simple = ins:find 'Simple' local add = Simple:method 'add' function should.autoload() assertType('table', dub.Function) end function should.beAFunction() assertEqual('dub.Function', add.type) end function should.haveParams() local res = {} local i = 0 for param in add:params() do i = i + 1 table.insert(res, {i, param.name}) end assertValueEqual({{1, 'v'}, {2, 'w'}}, res) end function should.haveMinArgSize() assertEqual('(MyFloat v, double w=10)', add.argsstring) assertTrue(add.has_defaults) assertEqual(1, add.min_arg_size) end function should.haveReturnValue() local ret = add.return_value assertEqual('MyFloat', ret.name) end function should.notHaveReturnValueForSetter() local func = Simple:method 'setValue' assertNil(func.return_value) end function should.haveLocation() assertMatch('test/fixtures/simple/include/simple.h:[0-9]+', add.location) end function should.haveDefinition() assertMatch('MyFloat Simple::add', add.definition) end function should.haveArgsString() assertMatch('%(MyFloat v, double w=10%)', add.argsstring) end function should.markConstructorAsStatic() local func = Simple:method 'Simple' assertTrue(func.static) end function should.haveSignature() assertEqual('MyFloat, double', add.sign) end function should.respondToNew() local f = dub.Function { name = 'hop', definition = 'hop', argsstring = '(int i)', db = Simple.db, parent = Simple, params_list = { { type = 'dub.Param', name = 'i', position = 1, ctype = { name = 'int', }, } }, } assertEqual('dub.Function', f.type) assertEqual('hop(int i)', f:nameWithArgs()) end function should.respondToFullname() assertEqual('Simple::add', add:fullname()) end function should.respondToNameWithArgs() assertEqual('MyFloat Simple::add(MyFloat v, double w=10)', add:nameWithArgs()) end function should.respondToFullcname() assertEqual('Simple::add', add:fullcname()) end function should.respondToNeverThrows() local value = Simple:method 'value' assertTrue(value:neverThrows()) assertFalse(add:neverThrows()) end function should.respondToSetName() end should:test()
mit
AdamGagorik/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Qutiba.lua
27
2282
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Qutiba -- Type: Standard NPC -- @pos 92.341 -7.5 -129.980 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vanishProg = player:getVar("vanishingactCS"); if (player:getVar("deliveringTheGoodsCS") == 1) then player:startEvent(0x0028); elseif (player:getQuestStatus(AHT_URHGAN,DELIVERING_THE_GOODS) == QUEST_COMPLETED and vanishProg == 1) then player:startEvent(0x002a); elseif (vanishProg == 2) then player:startEvent(0x0036); elseif (vanishProg == 4 and player:hasKeyItem(RAINBOW_BERRY)) then player:startEvent(0x002d); else player:startEvent(0x0033); 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 == (0x028)) then player:setVar("deliveringTheGoodsCS",2); elseif (csid == 0x002a and option == 0) then player:addQuest(AHT_URHGAN,VANISHING_ACT); player:setVar("vanishingactCS",2); elseif (csid == 0x002d) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2185); else player:setVar("vanishingactCS",0); player:delKeyItem(RAINBOW_BERRY); player:addItem(2185,1); player:messageSpecial(ITEM_OBTAINED,2185); player:completeQuest(AHT_URHGAN,VANISHING_ACT); end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/plate_of_barnacle_paella.lua
18
1633
----------------------------------------- -- ID: 5974 -- Item: Plate of Barnacle Paella -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- HP 40 -- Vitality 5 -- Mind -1 -- Charisma -1 -- Defense % 25 Cap 150 -- Undead Killer 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,10800,5974); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 40); target:addMod(MOD_VIT, 5); target:addMod(MOD_MND, -1); target:addMod(MOD_CHR, -1); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 150); target:addMod(MOD_UNDEAD_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 40); target:delMod(MOD_VIT, 5); target:delMod(MOD_MND, -1); target:delMod(MOD_CHR, -1); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 150); target:delMod(MOD_UNDEAD_KILLER, 5); end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/pot_of_honey.lua
18
1119
----------------------------------------- -- ID: 4370 -- Item: pot_of_honey -- Food Effect: 5Min, All Races ----------------------------------------- -- Magic Regen 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,300,4370); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
TrurlMcByte/docker-prosody
etc/prosody-modules/mod_turncredentials/mod_turncredentials.lua
36
1415
-- XEP-0215 implementation for time-limited turn credentials -- Copyright (C) 2012-2013 Philipp Hancke -- This file is MIT/X11 licensed. local st = require "util.stanza"; local hmac_sha1 = require "util.hashes".hmac_sha1; local base64 = require "util.encodings".base64; local os_time = os.time; local secret = module:get_option_string("turncredentials_secret"); local host = module:get_option_string("turncredentials_host"); -- use ip addresses here to avoid further dns lookup latency local port = module:get_option_number("turncredentials_port", 3478); local ttl = module:get_option_number("turncredentials_ttl", 86400); if not (secret and host) then module:log("error", "turncredentials not configured"); return; end module:add_feature("urn:xmpp:extdisco:1"); module:hook("iq-get/host/urn:xmpp:extdisco:1:services", function(event) local origin, stanza = event.origin, event.stanza; if origin.type ~= "c2s" then return; end local now = os_time() + ttl; local userpart = tostring(now); local nonce = base64.encode(hmac_sha1(secret, tostring(userpart), false)); origin.send(st.reply(stanza):tag("services", {xmlns = "urn:xmpp:extdisco:1"}) :tag("service", { type = "stun", host = host, port = port }):up() :tag("service", { type = "turn", host = host, port = port, username = userpart, password = nonce, ttl = ttl}):up() ); return true; end);
mit
iotcafe/nodemcu-firmware
lua_examples/yet-another-ds18b20.lua
79
1924
------------------------------------------------------------------------------ -- DS18B20 query module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- dofile("ds18b20.lua").read(4, function(r) for k, v in pairs(r) do print(k, v) end end) ------------------------------------------------------------------------------ local M do local bit = bit local format_addr = function(a) return ("%02x-%02x%02x%02x%02x%02x%02x"):format( a:byte(1), a:byte(7), a:byte(6), a:byte(5), a:byte(4), a:byte(3), a:byte(2) ) end local read = function(pin, cb, delay) local ow = require("ow") -- get list of relevant devices local d = { } ow.setup(pin) ow.reset_search(pin) while true do tmr.wdclr() local a = ow.search(pin) if not a then break end if ow.crc8(a) == 0 and (a:byte(1) == 0x10 or a:byte(1) == 0x28) then d[#d + 1] = a end end -- conversion command for all ow.reset(pin) ow.skip(pin) ow.write(pin, 0x44, 1) -- wait a bit tmr.alarm(0, delay or 100, 0, function() -- iterate over devices local r = { } for i = 1, #d do tmr.wdclr() -- read rom command ow.reset(pin) ow.select(pin, d[i]) ow.write(pin, 0xBE, 1) -- read data local x = ow.read_bytes(pin, 9) if ow.crc8(x) == 0 then local t = (x:byte(1) + x:byte(2) * 256) -- negatives? if bit.isset(t, 15) then t = 1 - bit.bxor(t, 0xffff) end -- NB: temperature in Celsius * 10^4 t = t * 625 -- NB: due 850000 means bad pullup. ignore if t ~= 850000 then r[format_addr(d[i])] = t end d[i] = nil end end cb(r) end) end -- expose M = { read = read, } end return M
mit