repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
dtrip/awesome
tests/examples/awful/notification/box_corner.lua
5
1042
--DOC_HIDE --DOC_GEN_IMAGE --DOC_NO_USAGE local naughty = require("naughty") --DOC_HIDE screen[1]._resize {width = 640, height = 480} --DOC_HIDE require("_date") --DOC_HIDE require("_default_look") --DOC_HIDE local function ever_longer_messages(iter) --DOC_HIDE local ret = "content! " --DOC_HIDE for _=1, iter do --DOC_HIDE ret = ret.."more! " --DOC_HIDE end --DOC_HIDE return ret --DOC_HIDE end --DOC_HIDE --DOC_NEWLINE naughty.connect_signal("request::display", function(n) --DOC_HIDE naughty.layout.box {notification = n} --DOC_HIDE end) --DOC_HIDE --DOC_NEWLINE for _, pos in ipairs { "top_left" , "top_middle" , "top_right", "bottom_left", "bottom_middle", "bottom_right", } do for i=1, 3 do naughty.notification { position = pos, title = pos .. " " .. i, message = ever_longer_messages(i) } end end --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
nyczducky/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Ryo.lua
30
1239
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Ryo -- Type: ZNM assistant -- @pos -127.086 0.999 22.693 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/besieged"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0391); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("updateCSID: %u",csid); -- printf("updateRESULT: %u",option); if (option == 300) then player:updateEvent(player:getCurrency("zeni_point"),0); else player:updateEvent(0,0); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("finishCSID: %u",csid); -- printf("finishRESULT: %u",option); end;
gpl-3.0
xamgeis/project_vulcan
models/openface/resnet1.def.lua
14
5514
-- Model: resnet1.def.lua -- Description: ResNet model for face recognition with OpenFace, v1. -- Input size: 3x96x96 -- Number of Parameters from net:getParameters() with embSize=128: TODO -- Components: Mostly `nn` -- Devices: CPU and CUDA -- -- Brandon Amos <http://bamos.github.io> -- 2016-06-19 -- -- Copyright 2016 Carnegie Mellon University -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Modified from: -- https://github.com/facebook/fb.resnet.torch/blob/master/models/resnet.lua -- Portions from here are BSD licensed. imgDim = 96 local nn = require 'nn' local Convolution = nn.SpatialConvolutionMM -- local Avg = nn.SpatialAveragePooling local ReLU = nn.ReLU local Max = nn.SpatialMaxPooling local SBatchNorm = nn.SpatialBatchNormalization function createModel() local depth = 18 local shortcutType = 'B' local iChannels -- The shortcut layer is either identity or 1x1 convolution local function shortcut(nInputPlane, nOutputPlane, stride) local useConv = shortcutType == 'C' or (shortcutType == 'B' and nInputPlane ~= nOutputPlane) if useConv then -- 1x1 convolution return nn.Sequential() :add(Convolution(nInputPlane, nOutputPlane, 1, 1, stride, stride)) :add(SBatchNorm(nOutputPlane)) elseif nInputPlane ~= nOutputPlane then -- Strided, zero-padded identity shortcut return nn.Sequential() :add(nn.SpatialAveragePooling(1, 1, stride, stride)) :add(nn.Concat(2) :add(nn.Identity()) :add(nn.MulConstant(0))) else return nn.Identity() end end -- The basic residual layer block for 18 and 34 layer network, and the -- CIFAR networks local function basicblock(n, stride) local nInputPlane = iChannels iChannels = n local s = nn.Sequential() s:add(Convolution(nInputPlane,n,3,3,stride,stride,1,1)) s:add(SBatchNorm(n)) s:add(ReLU(true)) s:add(Convolution(n,n,3,3,1,1,1,1)) s:add(SBatchNorm(n)) return nn.Sequential() :add(nn.ConcatTable() :add(s) :add(shortcut(nInputPlane, n, stride))) :add(nn.CAddTable(true)) :add(ReLU(true)) end -- The bottleneck residual layer for 50, 101, and 152 layer networks -- local function bottleneck(n, stride) -- local nInputPlane = iChannels -- iChannels = n * 4 -- local s = nn.Sequential() -- s:add(Convolution(nInputPlane,n,1,1,1,1,0,0)) -- s:add(SBatchNorm(n)) -- s:add(ReLU(true)) -- s:add(Convolution(n,n,3,3,stride,stride,1,1)) -- s:add(SBatchNorm(n)) -- s:add(ReLU(true)) -- s:add(Convolution(n,n*4,1,1,1,1,0,0)) -- s:add(SBatchNorm(n * 4)) -- return nn.Sequential() -- :add(nn.ConcatTable() -- :add(s) -- :add(shortcut(nInputPlane, n * 4, stride))) -- :add(nn.CAddTable(true)) -- :add(ReLU(true)) -- end -- Creates count residual blocks with specified number of features local function layer(block, features, count, stride) local s = nn.Sequential() for i=1,count do s:add(block(features, i == 1 and stride or 1)) end return s end -- Configurations for ResNet: -- num. residual blocks, num features, residual block function local cfg = { [18] = {{2, 2, 2, 2}, 4608, basicblock}, -- [34] = {{3, 4, 6, 3}, 512, basicblock}, -- [50] = {{3, 4, 6, 3}, 2048, bottleneck}, -- [101] = {{3, 4, 23, 3}, 2048, bottleneck}, -- [152] = {{3, 8, 36, 3}, 2048, bottleneck}, } assert(cfg[depth], 'Invalid depth: ' .. tostring(depth)) local def, nLinear, block = table.unpack(cfg[depth]) iChannels = 64 -- The ResNet ImageNet model local model = nn.Sequential() model:add(Convolution(3,64,7,7,2,2,3,3)) model:add(SBatchNorm(64)) model:add(ReLU(true)) model:add(Max(3,3,2,2,1,1)) model:add(layer(block, 64, def[1])) model:add(layer(block, 128, def[2], 2)) model:add(layer(block, 256, def[3], 2)) model:add(layer(block, 512, def[4], 2)) -- TODO: Add back? -- model:add(Avg(7, 7, 1, 1)) model:add(nn.View(nLinear)) model:add(nn.Linear(nLinear, opt.embSize)) model:add(nn.Normalize(2)) local function ConvInit(name) for _,v in pairs(model:findModules(name)) do local n = v.kW*v.kH*v.nOutputPlane v.weight:normal(0,math.sqrt(2/n)) if cudnn.version >= 4000 then v.bias = nil v.gradBias = nil else v.bias:zero() end end end local function BNInit(name) for _,v in pairs(model:findModules(name)) do v.weight:fill(1) v.bias:zero() end end ConvInit('nn.SpatialConvolutionMM') BNInit('nn.SpatialBatchNormalization') for _,v in pairs(model:findModules('nn.Linear')) do v.bias:zero() end return model end
apache-2.0
nyczducky/darkstar
scripts/zones/Western_Adoulin/npcs/Theophylacte.lua
14
1284
----------------------------------- -- Area: Western Adoulin -- NPC: Theophylacte -- Type: Shop NPC -- @zone 256 -- @pos 154 4 -33 256 ----------------------------------- package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Western_Adoulin/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Standard shop player:showText(npc, THEOPHYLACTE_SHOP_TEXT); local stock = { 0x1010, 910, -- Potion 0x1014, 4500, -- Hi-Potion 0x1020, 4832, -- Ether 0x1024, 28000, -- Hi-Ether 0x1034, 316, -- Antidote 0x1037, 800, -- Echo Drops 0x103B, 3360, -- Remedy } showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) end;
gpl-3.0
HalosGhost/irc_bot
src/plugins/play.lua
1
6015
-- fun but pointless games local modules = modules local invalid_num = function (n) return not (math.type(n) == 'integer' and n >= 1) end local plugin = {} plugin.commands = {} plugin.commands.test = function (args) local _, _, message = args.message:find('test%s+(.*)') local prob = math.random() local rest = { '3PASS', '5FAIL', '5\x02PANIC\x02' } local res = prob < 0.01 and rest[3] or prob < 0.49 and rest[2] or rest[1] modules.irc.privmsg(args.target, ('%s: Testing %s: [\x03%s\x03]'):format(args.sender, message, res)) end plugin.commands.roll = function (args) local _, _, numdice, numsides = args.message:find('roll%s+(%d+)d(%d+)') local rands = '' numdice = math.tointeger(numdice) numsides = math.tointeger(numsides) if invalid_num(numdice) or invalid_num(numsides) then --modules.irc.privmsg(args.target, ('%s: Please tell me the number of dice and the number of sides, ie: "2d6" for two six sided dice'):format(args.sender)) return end for _ = 1, numdice do rands = ('%d %s'):format(math.random(numsides), rands) if rands:len() > 510 then break end end modules.irc.privmsg(args.target, ('%s: %s'):format(args.sender, rands)) end plugin.commands.coinflip = function (args) local _, _, numflips = args.message:find('coinflip%s+(%d+)') if numflips and numflips:len() > 4 then --modules.irc.privmsg(args.target, 'Please give me a number less than 5 digits long.') return end if not numflips or numflips == ' ' then numflips = 1 else numflips = math.tointeger(numflips) end if invalid_num(numflips) then --modules.irc.privmsg(args.target, ('%s: Tell me how many coinflips you want'):format(args.sender)) return end local heads = 0 local tails = 0 for _ = 1, numflips do local flip = math.random(2) if flip == 1 then heads = heads + 1 else tails = tails + 1 end end modules.irc.privmsg(args.target, ('%s: heads: %d tails: %d'):format(args.sender, heads, tails)) end plugin.commands.magic8ball = function (args) local _, _, message = args.message:find('magic8ball%s+(.*)') local predictions = { positive = { 'It is possible.', 'Yes!', 'Of course.', 'Naturally.', 'Obviously.', 'It shall be.', 'The outlook is good.', 'It is so.', 'One would be wise to think so.', 'The answer is certainly yes.' }, negative = { 'In your dreams.', 'I doubt it very much.', 'No chance.', 'The outlook is poor.', 'Unlikely.', 'Categorically no.', "You're kidding, right?", 'No!', 'No.', 'The answer is a resounding no.' }, unknown = { 'Maybe...', 'No clue.', "_I_ don't know.", 'The outlook is hazy.', 'Not sure, ask again later.', 'What are you asking me for?', 'Come again?', 'The answer is in the stars.', 'You know the answer better than I.', 'The answer is def-- oooh shiny thing!' } } if not message then --modules.irc.privmsg(args.target, ('%s: Ask me a question.'):format(args.sender)) return end local reply if message and message:len() % 3 == 0 then reply = predictions.positive[math.random(10)] elseif message and message:len() % 3 == 1 then reply = predictions.negative[math.random(10)] else reply = predictions.unknown[math.random(10)] end modules.irc.privmsg(args.target, ('%s: %s'):format(args.sender, reply)) end plugin.commands.is = function (args) local prob = { 'certainly', 'possibly', 'categorically', 'negatively' , 'positively', 'without-a-doubt', 'maybe', 'perhaps', 'doubtfully' , 'likely', 'definitely', 'greatfully', 'thankfully', 'undeniably' , 'arguably' } local case = { 'so', 'not', 'true', 'false' } local punct = { '.', '!', '…' } local r1 = math.random(#prob) local r2 = math.random(#case) local r3 = math.random(#punct) modules.irc.privmsg(args.target, ('%s: %s %s%s'):format(args.sender, prob[r1], case[r2], punct[r3])) end plugin.commands.rot13 = function (args) local _, _, text = args.message:find('rot13%s(.*)') if text then local chars = {} for i=1,text:len() do chars[i] = text:byte(i) end local rotted = "" for i=1,#chars do local letter = chars[i] if letter >= 65 and letter < 91 then local offset = letter - 65 letter = string.char(65 + ((offset + 13) % 26)) elseif letter >= 97 and letter < 123 then local offset = letter - 97 letter = string.char(97 + ((offset + 13) % 26)) else letter = string.char(chars[i]) end rotted = rotted .. letter end modules.irc.privmsg(args.target, ('%s: %s'):format(args.sender, rotted)) else return end end plugin.commands.pick = function (args) local _, _, str = args.message:find("pick%s+(.+)") local words = {} if str then for i in str:gmatch("%S+") do words[#words + 1] = i end else modules.irc.privmsg(args.target, ('%s: Please give me some things to choose from.'):format(args.sender)) return end local r = math.random(#words) modules.irc.privmsg(args.target, ('%s: %s'):format(args.sender, words[r])) end local h = '' for k in pairs(plugin.commands) do h = ('%s|%s'):format(h, k) end plugin.help = ('usage: play <%s>'):format(h:sub(2)) plugin.main = function (args) local _, _, action = args.message:find('(%S+)') local f = plugin.commands[action] if f then return f(args) end modules.irc.privmsg(args.target, plugin.help) end return plugin
gpl-2.0
nyczducky/darkstar
scripts/commands/exec.lua
54
1121
--------------------------------------------------------------------------------------------------- -- func: exec -- desc: Allows you to execute a Lua string directly from chat. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 4, parameters = "s" }; function onTrigger(player, str) -- Ensure a command was given.. if (str == nil or string.len(str) == 0) then player:PrintToPlayer("You must enter a string to execute."); return; end -- For safety measures we will nuke the os table.. local old_os = os; os = nil; -- Ensure the command compiles / is valid.. local scriptObj, err = loadstring(str); if (scriptObj == nil) then player:PrintToPlayer("Failed to load the given string."); player:PrintToPlayer(err); os = old_os; return; end -- Execute the string.. local status, err = pcall(scriptObj); if (status == false) then player:PrintToPlayer(err); end -- Restore the os table.. os = old_os; end
gpl-3.0
TheHipster/cwlourp
plugins/books/plugin/items/sh_book_ha.lua
1
2664
--[[ © 2013 CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). --]] ITEM = Clockwork.item:New("book_base"); ITEM.name = "Headcrab Anatomy"; ITEM.cost = 6; ITEM.model = "models/props_lab/binderredlabel.mdl"; ITEM.uniqueID = "book_ha"; ITEM.business = true; ITEM.description = "A book with numerous headcrabs on the front."; ITEM.bookInformation = [[ <font color='red' size='4'>Written by Jamie Ruzicano.</font> A headcrab (or pasasite, according to the Combine) is an alien creature found on earth. Headcrabs are small creatures, consisting of a round, tan body and four legs. They also have a pair of large frontal claws for attacking prey. Under the headcrab's body is a large rounded mouth surrounded by pointed flesh. Headcrabs appear to have no external sensory organs. Because of this, it's assumed they move by touch and vibration. Headcrabs can produce a variety of vocalizations. When they are not hunting, headcrabs usually emit squeaks and quiet, repetitive calls. When attacking, headcrabs emit a sharp, shrill shriek. Headcrabs were found to have originated from a giant creature known as a Gonarch. Headcrabs are known to bury themselves in the ground to hide. Headcrabs appear to be fairly unintelligent creatures, pursuing prey under dangerous conditions. Headcrabs have also been seen cooked and prepared in different dishes. The Combine have been seen utilizing headcrabs as a form of biological weaponry. Headcrab shells, as they are known, are cannisters containing several headcrabs. After impact, headcrabs are released into the open, free to infest or kill nearby victims. If used in large numbers, these shells are highly effective killers. Recent studies have shown that Headcrabs are omnivorous. Headcrabs are small, slow-moving, and relatively weak on their own, however... Its main goal is to attach itself onto an appropriate host's head. Once attached, they take control of the host's nervous system and dreadful mutations occur. These mutations will create a zombie out of the host. Zombies develop elongated claws, increased strength, and a sharp-toothed 'mouth' that bisects the chest from neck to groin. Removal of the headcrab reveals that the host's head is strangely untouched. Zombies emit horrified sounds implying that, while severely injured, the host is aware of its horrific situation. Occasionally, headcrab zombies survive losing both legs and their lower torso, and continue to crawl along using their arms. In most cases, a headcrab remains attached to its host until the zombie is destroyed. ]]; ITEM:Register();
unlicense
ruleless/skynet
service/sharedatad.lua
23
2745
local skynet = require "skynet" local sharedata = require "sharedata.corelib" local table = table local NORET = {} local pool = {} local pool_count = {} local objmap = {} local function newobj(name, tbl) assert(pool[name] == nil) local cobj = sharedata.host.new(tbl) sharedata.host.incref(cobj) local v = { value = tbl , obj = cobj, watch = {} } objmap[cobj] = v pool[name] = v pool_count[name] = { n = 0, threshold = 16 } end local function collectobj() while true do skynet.sleep(600 * 100) -- sleep 10 min collectgarbage() for obj, v in pairs(objmap) do if v == true then if sharedata.host.getref(obj) <= 0 then objmap[obj] = nil sharedata.host.delete(obj) end end end end end local CMD = {} local env_mt = { __index = _ENV } function CMD.new(name, t) local dt = type(t) local value if dt == "table" then value = t elseif dt == "string" then value = setmetatable({}, env_mt) local f = load(t, "=" .. name, "t", value) assert(skynet.pcall(f)) setmetatable(value, nil) elseif dt == "nil" then value = {} else error ("Unknown data type " .. dt) end newobj(name, value) end function CMD.delete(name) local v = assert(pool[name]) pool[name] = nil pool_count[name] = nil assert(objmap[v.obj]) objmap[v.obj] = true sharedata.host.decref(v.obj) for _,response in pairs(v.watch) do response(true) end end function CMD.query(name) local v = assert(pool[name]) local obj = v.obj sharedata.host.incref(obj) return v.obj end function CMD.confirm(cobj) if objmap[cobj] then sharedata.host.decref(cobj) end return NORET end function CMD.update(name, t) local v = pool[name] local watch, oldcobj if v then watch = v.watch oldcobj = v.obj objmap[oldcobj] = true sharedata.host.decref(oldcobj) pool[name] = nil pool_count[name] = nil end CMD.new(name, t) local newobj = pool[name].obj if watch then sharedata.host.markdirty(oldcobj) for _,response in pairs(watch) do response(true, newobj) end end end local function check_watch(queue) local n = 0 for k,response in pairs(queue) do if not response "TEST" then queue[k] = nil n = n + 1 end end return n end function CMD.monitor(name, obj) local v = assert(pool[name]) if obj ~= v.obj then return v.obj end local n = pool_count[name].n pool_count[name].n = n + 1 if n > pool_count[name].threshold then n = n - check_watch(v.watch) pool_count[name].threshold = n * 2 end table.insert(v.watch, skynet.response()) return NORET end skynet.start(function() skynet.fork(collectobj) skynet.dispatch("lua", function (session, source ,cmd, ...) local f = assert(CMD[cmd]) local r = f(...) if r ~= NORET then skynet.ret(skynet.pack(r)) end end) end)
mit
jbeich/Aquaria
files/scripts/entities/roundvirus-bg.lua
6
2965
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 v.fireDelayTime = 3 v.fireDelay = 0 function init(me) setupBasicEntity( me, "roundvirus-bg", -- texture 6, -- health 2, -- manaballamount 2, -- exp 10, -- money 0, -- collideRadius (for hitting entities + spells) STATE_IDLE, -- initState 256, -- sprite width 256, -- sprite height 1, -- particle "explosion" type, 0 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) 4000, -- updateCull -1: disabled, default: 4000 1 ) entity_setEntityLayer(me, -4) entity_addVel(me, randVector(500)) entity_setMaxSpeed(me, 100) entity_setUpdateCull(me, 2000) entity_setCullRadius(me, 512) entity_setDeathScene(me, true) entity_setDamageTarget(me, DT_ENEMY_POISON, false) entity_setEntityType(me, ET_NEUTRAL) --entity_setDropChance(me, 100) end function postInit(me) v.n = getNaija() entity_setTarget(me, v.n) end function update(me, dt) entity_updateMovement(me, dt) --entity_handleShotCollisions(me) --entity_touchAvatarDamage(me, entity_getCollideRadius(me), 0.5, 400) --entity_doCollisionAvoidance(me, dt, 8, 0.1) --entity_doEntityAvoidance(me, dt, 64, 1) v.fireDelay = v.fireDelay - dt if v.fireDelay < 0 then entity_addVel(me, randVector(500)) v.fireDelay = v.fireDelayTime entity_rotate(me, entity_getRotation(me)+90, 1, 0, 0, 1) end end function enterState(me) if entity_isState(me, STATE_IDLE) then entity_animate(me, "idle", -1) elseif entity_isState(me, STATE_DEATHSCENE) then entity_scale(me, 1.1, 1.1) entity_scale(me, 0, 0, 0.5) entity_setStateTime(me, 0.5) end end function exitState(me) end function damage(me, attacker, bone, damageType, dmg) if damageType == DT_ENEMY_POISON then return false end return true end function animationKey(me, key) end function hitSurface(me) end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end function dieNormal(me) spawnParticleEffect("TinyGreenExplode", entity_x(me),entity_y(me)) end
gpl-2.0
nyczducky/darkstar
scripts/globals/items/crab_stewpot.lua
12
1753
----------------------------------------- -- ID: 5544 -- Item: Crab Stewpot -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 50 -- MP +10 -- HP Recoverd while healing 5 -- MP Recovered while healing 1 -- Defense +20% Cap 50 -- Evasion +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,5544); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 50); target:addMod(MOD_MP, 10); target:addMod(MOD_HPHEAL, 5); target:addMod(MOD_MPHEAL, 1); target:addMod(MOD_FOOD_DEFP, 20); target:addMod(MOD_FOOD_DEF_CAP, 50); target:addMod(MOD_EVA, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 50); target:delMod(MOD_MP, 10); target:delMod(MOD_HPHEAL, 5); target:delMod(MOD_MPHEAL, 1); target:delMod(MOD_FOOD_DEFP, 20); target:delMod(MOD_FOOD_DEF_CAP, 50); target:delMod(MOD_EVA, 5); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Eastern_Altepa_Desert/npcs/Telepoint.lua
17
1706
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: Telepoint ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) item = trade:getItemId(); if (trade:getItemCount() == 1 and item > 4095 and item < 4104) then if (player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then player:tradeComplete(); player:addItem(613); player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(ALTEPA_GATE_CRYSTAL) == false) then player:addKeyItem(ALTEPA_GATE_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,ALTEPA_GATE_CRYSTAL); else player:messageSpecial(ALREADY_OBTAINED_TELE); 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
nyczducky/darkstar
scripts/zones/Nashmau/npcs/Yoyoroon.lua
17
1709
----------------------------------- -- Area: Nashmau -- NPC: Yoyoroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,YOYOROON_SHOP_DIALOG); stock = {0x08BF,4940, -- Tension Spring 0x08C0,9925, -- Inhibitor 0x08C2,9925, -- Mana Booster 0x08C3,4940, -- Loudspeaker 0x08C6,4940, -- Accelerator 0x08C7,9925, -- Scope 0x08CA,9925, -- Shock Absorber 0x08CB,4940, -- Armor Plate 0x08CE,4940, -- Stabilizer 0x08CF,9925, -- Volt Gun 0x08D2,4940, -- Mana Jammer 0x08D4,9925, -- Stealth Screen 0x08D6,4940, -- Auto-Repair Kit 0x08D8,9925, -- Damage Gauge 0x08DA,4940, -- Mana Tank 0x08DC,9925} -- Mana Conserver showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Al_Zahbi/npcs/Macici.lua
53
2304
----------------------------------- -- Area: Al Zahbi -- NPC: Macici -- Type: Smithing Normal/Adv. Image Support -- @pos -35.163 -1 -31.351 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local guildMember = isGuildMember(player,8); if (guildMember == 1) then if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then if (player:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == false) then player:tradeComplete(); player:startEvent(0x00E9,8,0,0,0,188,0,2,0); else npc:showText(npc, IMAGE_SUPPORT_ACTIVE); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,8); local SkillLevel = player:getSkillLevel(SKILL_SMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == false) then player:startEvent(0x00E8,8,SkillLevel,0,511,188,0,2,2184); else player:startEvent(0x00E8,8,SkillLevel,0,511,188,6566,2,2184); end else player:startEvent(0x00E8,0,0,0,0,0,0,2,0); -- Standard 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 == 0x00E8 and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,2,1); player:addStatusEffect(EFFECT_SMITHING_IMAGERY,1,0,120); elseif (csid == 0x00E9) then player:messageSpecial(IMAGE_SUPPORT,0,2,0); player:addStatusEffect(EFFECT_SMITHING_IMAGERY,3,0,480); end end;
gpl-3.0
ScottHamper/ChatSuey
ChatSuey-WebLinks/Main.lua
1
2482
local _G = getfenv(); local ChatSuey = _G.ChatSuey; local hooks = ChatSuey.HookTable:new(); local LS = ChatSuey.Locales[_G.GetLocale()].Strings; local DIALOG_NAME = "ChatSuey_WebLinkDialog"; local URL_PATTERN = "(|?%a[%w+.%-]-://[%w%-._~:/?#%[%]@!$&'()*+,;=%%]+)"; local LINK_COLOR = ChatSuey.Colors.TOKEN; local parseHyperlink = function (link) -- We don't want to replace the text of an existing chat hyperlink -- This is admittedly a rare edge case. if string.sub(link, 1, 1) == "|" then return link; end return ChatSuey.Hyperlink(link, link, LINK_COLOR); end; local addMessage = function (self, text, red, green, blue, messageId, holdTime) text = string.gsub(text, URL_PATTERN, parseHyperlink); hooks[self].AddMessage(self, text, red, green, blue, messageId, holdTime); end; local clickedUrl = ""; local onHyperlinkClick = function () local uri = _G.arg1; local link = _G.arg2; if not string.find(uri, URL_PATTERN) then hooks[this].OnHyperlinkClick(); return; end if _G.IsShiftKeyDown() and _G.ChatFrameEditBox:IsVisible() then _G.ChatFrameEditBox:Insert(link); return; end clickedUrl = uri; StaticPopup_Show(DIALOG_NAME); end; for i = 1, _G.NUM_CHAT_WINDOWS do local chatFrame = _G["ChatFrame" .. i]; hooks:RegisterFunc(chatFrame, "AddMessage", addMessage); hooks:RegisterScript(chatFrame, "OnHyperlinkClick", onHyperlinkClick); end _G.StaticPopupDialogs[DIALOG_NAME] = { text = LS["Copy the URL into your clipboard (Ctrl-C):"], button1 = _G.CLOSE, timeout = 0, whileDead = true, hasEditBox = true, hasWideEditBox = true, maxLetters = 500, OnShow = function () local editBox = _G[this:GetName() .. "WideEditBox"]; editBox:SetText(clickedUrl); editBox:HighlightText(); -- Fixes editBox bleeding out of the dialog boundaries this:SetWidth(editBox:GetWidth() + 80); -- Fixes close button overlapping the edit box local closeButton = _G[this:GetName() .. "Button1"]; closeButton:ClearAllPoints(); closeButton:SetPoint("CENTER", editBox, "CENTER", 0, -30); end, OnHide = function () _G[this:GetName() .. "WideEditBox"]:SetText(""); clickedUrl = ""; end, EditBoxOnEscapePressed = function () this:GetParent():Hide(); end, EditBoxOnEnterPressed = function () this:GetParent():Hide(); end, };
unlicense
ahmedjabbar/uor
plugins/supergroup.lua
7
104172
--[[ # #ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ #:(( # For More Information ....! # Developer : Aziz < @TH3_GHOST > # our channel: @DevPointTeam # Version: 1.1 #:)) #ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ # ]] --Begin supergrpup.lua --Check members #Add supergroup --channel : @DevPointTeam local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "Promote me to admin first!") end for k,v in pairs(result) do local member_id = v.peer_id if member_id ~= our_id then -- SuperGroup configuration data[tostring(msg.to.id)] = { group_type = 'SuperGroup', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.title, '_', ' '), lock_arabic = 'no', lock_link = "no", flood = 'yes', lock_spam = 'yes', lock_sticker = 'no', member = 'no', public = 'no', lock_rtl = 'no', lock_tgservice = 'yes', lock_contacts = 'no', strict = 'no' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) local text = 'bot has been added ✅ in Group🔹'..msg.to.title return reply_msg(msg.id, text, ok_cb, false) end end end --Check Members #rem supergroup local function check_member_superrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'bot has been removed ❎ in Group🔹'..msg.to.title return reply_msg(msg.id, text, ok_cb, false) end end end --Function to Add supergroup local function superadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg}) end --Function to remove supergroup local function superrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg}) end --Get and output admins and bots in supergroup local function callback(cb_extra, success, result) local i = 1 local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ") local member_type = cb_extra.member_type local text = member_type.." for "..chat_name..":\n" for k,v in pairsByKeys(result) do if not v.first_name then name = " " else vname = v.first_name:gsub("‮", "") name = vname:gsub("_", " ") end text = text.."\n"..i.." - "..name.."["..v.peer_id.."]" i = i + 1 end send_large_msg(cb_extra.receiver, text) end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="Info for SuperGroup: ["..result.title.."]\n\n" local admin_num = "Admin count: "..result.admins_count.."\n" local user_num = "User count: "..result.participants_count.."\n" local kicked_num = "Kicked user count: "..result.kicked_count.."\n" local channel_id = "ID: "..result.peer_id.."\n" if result.username then channel_username = "Username: @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "Members for "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username Channel : @DevPointTeam i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n" local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then name = name.." @"..v.username end text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n" i = i + 1 end local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false) --send_large_msg(cb_extra.receiver, text) end --Begin supergroup locks local function lock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Links is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Links has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Links is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Links has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_all(msg, data, target) if not is_momod(msg) then return end local group_all_lock = data[tostring(target)]['settings']['all'] if group_all_lock == 'yes' then return 'all settings is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['all'] = 'yes' save_data(_config.moderation.data, data) return 'all settings has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_all(msg, data, target) if not is_momod(msg) then return end local group_all_lock = data[tostring(target)]['settings']['all'] if group_all_lock == 'no' then return 'all settings is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['all'] = 'no' save_data(_config.moderation.data, data) return 'all settings has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_etehad(msg, data, target) if not is_momod(msg) then return end local group_etehad_lock = data[tostring(target)]['settings']['etehad'] if group_etehad_lock == 'yes' then return 'etehad setting is already locked' else data[tostring(target)]['settings']['etehad'] = 'yes' save_data(_config.moderation.data, data) return 'etehad setting has been locked' end end local function unlock_group_etehad(msg, data, target) if not is_momod(msg) then return end local group_etehad_lock = data[tostring(target)]['settings']['etehad'] if group_etehad_lock == 'no' then return 'etehad setting is not locked' else data[tostring(target)]['settings']['etehad'] = 'no' save_data(_config.moderation.data, data) return 'etehad setting has been unlocked' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return end local group_leave_lock = data[tostring(target)]['settings']['leave'] if group_leave_lock == 'yes' then return 'leave is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['leave'] = 'yes' save_data(_config.moderation.data, data) return 'leave has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return end local group_leave_lock = data[tostring(target)]['settings']['leave'] if group_leave_lock == 'no' then return 'leave is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['leave'] = 'no' save_data(_config.moderation.data, data) return 'leave has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_operator(msg, data, target) if not is_momod(msg) then return end local group_operator_lock = data[tostring(target)]['settings']['operator'] if group_operator_lock == 'yes' then return 'operator is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['operator'] = 'yes' save_data(_config.moderation.data, data) return 'operator has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_operator(msg, data, target) if not is_momod(msg) then return end local group_operator_lock = data[tostring(target)]['settings']['operator'] if group_operator_lock == 'no' then return 'operator is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['operator'] = 'no' save_data(_config.moderation.data, data) return 'operator has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_reply(msg, data, target) if not is_momod(msg) then return end local group_reply_lock = data[tostring(target)]['settings']['reply'] if group_reply_lock == 'yes' then return 'Reply is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['reply'] = 'yes' save_data(_config.moderation.data, data) return 'Reply has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_reply(msg, data, target) if not is_momod(msg) then return end local group_reply_lock = data[tostring(target)]['settings']['reply'] if group_reply_lock == 'no' then return 'Reply is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['reply'] = 'no' save_data(_config.moderation.data, data) return 'Reply has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_username(msg, data, target) if not is_momod(msg) then return end local group_username_lock = data[tostring(target)]['settings']['username'] if group_username_lock == 'yes' then return 'Username is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['username'] = 'yes' save_data(_config.moderation.data, data) return 'Username has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_username(msg, data, target) if not is_momod(msg) then return end local group_username_lock = data[tostring(target)]['settings']['username'] if group_username_lock == 'no' then return 'Username is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['username'] = 'no' save_data(_config.moderation.data, data) return 'Username has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_media(msg, data, target) if not is_momod(msg) then return end local group_media_lock = data[tostring(target)]['settings']['media'] if group_media_lock == 'yes' then return 'Media is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['media'] = 'yes' save_data(_config.moderation.data, data) return 'Media has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_media(msg, data, target) if not is_momod(msg) then return end local group_media_lock = data[tostring(target)]['settings']['media'] if group_media_lock == 'no' then return 'Media is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['media'] = 'no' save_data(_config.moderation.data, data) return 'Media has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_fosh(msg, data, target) if not is_momod(msg) then return end local group_fosh_lock = data[tostring(target)]['settings']['fosh'] if group_fosh_lock == 'yes' then return 'badword is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['fosh'] = 'yes' save_data(_config.moderation.data, data) return 'badword has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_fosh(msg, data, target) if not is_momod(msg) then return end local group_fosh_lock = data[tostring(target)]['settings']['fosh'] if group_fosh_lock == 'no' then return 'badword is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['fosh'] = 'no' save_data(_config.moderation.data, data) return 'badword has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_join(msg, data, target) if not is_momod(msg) then return end local group_join_lock = data[tostring(target)]['settings']['join'] if group_join_lock == 'yes' then return 'join is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['join'] = 'yes' save_data(_config.moderation.data, data) return 'join has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_join(msg, data, target) if not is_momod(msg) then return end local group_join_lock = data[tostring(target)]['settings']['join'] if group_join_lock == 'no' then return 'join is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['join'] = 'no' save_data(_config.moderation.data, data) return 'join has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_fwd(msg, data, target) if not is_momod(msg) then return end local group_fwd_lock = data[tostring(target)]['settings']['fwd'] if group_fwd_lock == 'yes' then return 'fwd is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['fwd'] = 'yes' save_data(_config.moderation.data, data) return 'fwd has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_fwd(msg, data, target) if not is_momod(msg) then return end local group_fwd_lock = data[tostring(target)]['settings']['fwd'] if group_fwd_lock == 'no' then return 'fwd is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['fwd'] = 'no' save_data(_config.moderation.data, data) return 'fwd has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_english(msg, data, target) if not is_momod(msg) then return end local group_english_lock = data[tostring(target)]['settings']['english'] if group_english_lock == 'yes' then return 'English is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['english'] = 'yes' save_data(_config.moderation.data, data) return 'English has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_english(msg, data, target) if not is_momod(msg) then return end local group_english_lock = data[tostring(target)]['settings']['english'] if group_english_lock == 'no' then return 'English is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['english'] = 'no' save_data(_config.moderation.data, data) return 'English has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_emoji(msg, data, target) if not is_momod(msg) then return end local group_emoji_lock = data[tostring(target)]['settings']['emoji'] if group_emoji_lock == 'yes' then return 'Emoji is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['emoji'] = 'yes' save_data(_config.moderation.data, data) return 'Emoji has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_emoji(msg, data, target) if not is_momod(msg) then return end local group_emoji_lock = data[tostring(target)]['settings']['emoji'] if group_emoji_lock == 'no' then return 'Emoji is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['emoji'] = 'no' save_data(_config.moderation.data, data) return 'Emoji has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'yes' then return 'tag is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['tag'] = 'yes' save_data(_config.moderation.data, data) return 'tag has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'no' then return 'tag is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['tag'] = 'no' save_data(_config.moderation.data, data) return 'tag has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_all(msg, data, target) if not is_momod(msg) then return end local group_all_lock = data[tostring(target)]['settings']['all'] if group_all_lock == 'no' then return 'all settings is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['all'] = 'no' save_data(_config.moderation.data, data) return 'all settings has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_spam(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "Owners only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'Spam is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'Spam has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_spam(msg, data, target) if not is_momod(msg) then return end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'Spam is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'Spam has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Flood is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Flood has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Flood is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Flood has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Members are already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Members has been locked 🔐\n👮 Order by :️ @'..msg.from.username end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Members are not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Members has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'yes' then return 'Tgservice is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_tgservice'] = 'yes' save_data(_config.moderation.data, data) return 'Tgservice has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'no' then return 'Tgservice is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_tgservice'] = 'no' save_data(_config.moderation.data, data) return 'Tgservice has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return 'Contact is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return 'Contact is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'yes' then return 'Settings are already strictly enforced 🛡\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced 🛡\n👮 Order by :️ @'..msg.from.username end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'no' then return 'Settings are not strictly enforced 🛡\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings will not be strictly enforced 🛡\n👮 Order by :️ @'..msg.from.username end end --End supergroup locks --'Set supergroup rules' function local function set_rulesmod(msg, data, target) if not is_momod(msg) then return end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'SuperGroup rules set' end --'Get supergroup rules' function local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local group_name = data[tostring(msg.to.id)]['settings']['set_name'] local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ") return rules end --Set supergroup to public or not public function local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(target)]['settings']['lock_bots'] then bots_protection = data[tostring(target)]['settings']['lock_bots'] end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_tgservice'] then data[tostring(target)]['settings']['lock_tgservice'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['tag'] then data[tostring(target)]['settings']['tag'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['emoji'] then data[tostring(target)]['settings']['emoji'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['english'] then data[tostring(target)]['settings']['english'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['fwd'] then data[tostring(target)]['settings']['fwd'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['reply'] then data[tostring(target)]['settings']['reply'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['join'] then data[tostring(target)]['settings']['join'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['fosh'] then data[tostring(target)]['settings']['fosh'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['username'] then data[tostring(target)]['settings']['username'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['media'] then data[tostring(target)]['settings']['media'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['leave'] then data[tostring(target)]['settings']['leave'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['all'] then data[tostring(target)]['settings']['all'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['operator'] then data[tostring(target)]['settings']['operator'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['etehad'] then data[tostring(target)]['settings']['etehad'] = 'no' end end local gp_type = data[tostring(msg.to.id)]['group_type'] local settings = data[tostring(target)]['settings'] local text = "🎗➖➖➖🎗➖➖➖🎗\nℹ️SuperGroups Settings: ⬇️\n💟Group name : "..msg.to.title.."\n🎗➖➖➖🎗➖➖➖🎗\n🔗lock links : "..settings.lock_link.."\n📵Lock contacts: "..settings.lock_contacts.."\n🔐Lock flood: "..settings.flood.."\n👾Flood sensitivity : "..NUM_MSG_MAX.."\n📊Lock spam: "..settings.lock_spam.."\n🆎Lock Arabic: "..settings.lock_arabic.."\n🔠Lock english: "..settings.english.."\n👤Lock Member: "..settings.lock_member.."\n📌Lock RTL: "..settings.lock_rtl.."\n🔯Lock Tgservice: "..settings.lock_tgservice.."\n🎡Lock sticker: "..settings.lock_sticker.."\n➕Lock tag(#): "..settings.tag.."\n😃Lock emoji: "..settings.emoji.."\n🤖Lock bots: "..bots_protection.."\n↩️Lock fwd(forward): "..settings.fwd.."\n🔃lock reply: "..settings.reply.."\n🚷Lock join: "..settings.join.."\n♏️Lock username(@): "..settings.username.."\n🆘Lock media: "..settings.media.."\n🏧Lock badword: "..settings.fosh.."\n🚶Lock leave: "..settings.leave.."\n🔕Lock all: "..settings.all.."\n🎗➖➖➖🎗➖➖➖🎗\nℹ️About Group: ⬇️\n🎗➖➖➖🎗➖➖➖🎗\n⚠️Group type: "..gp_type.."\n✳️Public: "..settings.public.."\n⛔️Strict settings: "..settings.strict.."\n🎗➖➖➖🎗➖➖➖🎗\nℹ️bot version : v1.1\n\n🌐 DEV🎗POINT🎗TEAM 🌐" return text end local function promote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) end local function demote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) end local function promote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return send_large_msg(receiver, 'SuperGroup is not added.') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been promoted.') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been demoted.') end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'SuperGroup is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end -- Start by reply actions function get_message_callback(extra, success, result) local get_cmd = extra.get_cmd local msg = extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if get_cmd == "id" and not result.action then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]") id1 = send_large_msg(channel, result.from.peer_id) elseif get_cmd == 'id' and result.action then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id else user_id = result.peer_id end local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]") id1 = send_large_msg(channel, user_id) end elseif get_cmd == "idfrom" then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]") id2 = send_large_msg(channel, result.fwd_from.peer_id) elseif get_cmd == 'channel_block' and not result.action then local member_id = result.from.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end --savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply") kick_user(member_id, channel_id) elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then local user_id = result.action.user.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.") kick_user(user_id, channel_id) elseif get_cmd == "del" then delete_msg(result.id, ok_cb, false) savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply") elseif get_cmd == "setadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." set as an admin" else text = "[ "..user_id.." ]set as an admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "demoteadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id if is_admin2(result.from.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." has been demoted from admin" else text = "[ "..user_id.." ] has been demoted from admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "setowner" then local group_owner = data[tostring(result.to.peer_id)]['set_owner'] if group_owner then local channel_id = 'channel#id'..result.to.peer_id if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(channel_id, user, ok_cb, false) end local user_id = "user#id"..result.from.peer_id channel_set_admin(channel_id, user_id, ok_cb, false) data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply") if result.from.username then text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as owner" else text = "[ "..result.from.peer_id.." ] added as owner" end send_large_msg(channel_id, text) end elseif get_cmd == "promote" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") promote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == "demote" then local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id --local user = "user#id"..result.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_demote(channel_id, user, ok_cb, false) elseif get_cmd == 'mute_user' then if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end if action == 'chat_add_user_link' then if result.from then user_id = result.from.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = msg.to.id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] removed from the muted user list") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") end end end -- End by reply actions --By ID actions local function cb_user_info(extra, success, result) local receiver = extra.receiver local user_id = result.peer_id local get_cmd = extra.get_cmd local data = load_data(_config.moderation.data) --[[if get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" else text = "[ "..result.peer_id.." ] has been set as an admin" end send_large_msg(receiver, text)]] if get_cmd == "demoteadmin" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "You can't demote global admins!") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] has been demoted from admin" send_large_msg(receiver, text) end elseif get_cmd == "promote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "demote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "res" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "id" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif Dev = Point elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "promote" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "demote" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "demoteadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel if is_admin2(result.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been demoted from admin" send_large_msg(channel_id, text) end local receiver = extra.channel local user_id = result.peer_id demote_admin(receiver, member_username, user_id) elseif get_cmd == 'mute_user' then local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end end --End resolve username actions --Begin non-channel_invite username actions local function in_channel_cb(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local msg = cb_extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(cb_extra.msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local member = cb_extra.username local memberid = cb_extra.user_id if member then text = 'No user @'..member..' in this SuperGroup.' else text = 'No user ['..memberid..'] in this SuperGroup.' end if get_cmd == "channel_block" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = v.peer_id local channel_id = cb_extra.msg.to.id local sender = cb_extra.msg.from.id if user_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(user_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end if v.username then text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") else text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") end kick_user(user_id, channel_id) return end end elseif get_cmd == "setadmin" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = "user#id"..v.peer_id local channel_id = "channel#id"..cb_extra.msg.to.id channel_set_admin(channel_id, user_id, ok_cb, false) if v.username then text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) return end elseif get_cmd == 'setowner' then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..v.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(v.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username") if result.username then text = member_username.." ["..v.peer_id.."] added as owner" else text = "["..v.peer_id.."] added as owner" end end elseif memberid and vusername ~= member and vpeer_id ~= memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end data[tostring(channel)]['set_owner'] = tostring(memberid) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username") text = "["..memberid.."] added as owner" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return end local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Run function local function DevPointTeam(msg, matches) if msg.to.type == 'chat' then if matches[1] == 'tosuper' then if not is_admin1(msg) then return end local receiver = get_receiver(msg) chat_upgrade(receiver, ok_cb, false) end elseif msg.to.type == 'channel'then if matches[1] == 'tosuper' then if not is_admin1(msg) then return end return "Already a SuperGroup" end end if msg.to.type == 'channel' then local support_id = msg.from.id local receiver = get_receiver(msg) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local data = load_data(_config.moderation.data) if matches[1] == 'addbot' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then local iDev1 = "is already added !" return send_large_msg(receiver, iDev1) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1] == 'addbot' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then local iDev1 = "This Group not added 🤖 OK I will add this Group" return send_large_msg(receiver, iDev1) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if matches[1] == 'rembot' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if not data[tostring(msg.to.id)] then return end--@DevPointTeam = Dont Remove if matches[1] == "gpinfo" then if not is_owner(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info") channel_info(receiver, callback_info, {receiver = receiver, msg = msg}) end if matches[1] == "admins" then if not is_owner(msg) and not is_support(msg.from.id) then return end member_type = 'Admins' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list") admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "owner" then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your SuperGroup" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "SuperGroup owner is ["..group_owner..']' end if matches[1] == "modlist" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) -- channel_get_admins(receiver,callback, {receiver = receiver}) end if matches[1] == "bots" and is_momod(msg) then member_type = 'Bots' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list") channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "who" and not matches[2] and is_momod(msg) then local user_id = msg.from.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list") channel_get_users(receiver, callback_who, {receiver = receiver}) end if matches[1] == "kicked" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list") channel_get_kicked(receiver, callback_kicked, {receiver = receiver}) end if matches[1] == 'del' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'del', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1] == 'bb' or matches[1] == 'kick' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'channel_block', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'bb' or matches[1] == 'kick' and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id Dev = Point if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end @DevPointTeam savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif msg.text:match("@[%a%d]") then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id Dev = Point } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'id' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'id' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") local text = "♍️- Name: " ..string.gsub(msg.from.print_name, "_", " ").. "\n♑️- Username: @"..(msg.from.username or '----').."\n🆔- ID: "..msg.from.id.."\n💟- Group Name: " ..string.gsub(msg.to.print_name, "_", " ").. "\nℹ️- Group ID: "..msg.to.id return reply_msg(msg.id, text, ok_cb, false) end end if matches[1] == 'kickme' then if msg.to.type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme") channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if matches[1] == 'newlink' and is_momod(msg)then local function callback_link (extra , success, result) local receiver = get_receiver(msg) if success == 0 then send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_link, false) end if matches[1] == 'setlink' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send the new group link now' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "New link set" end end if matches[1] == 'link' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first!\n\nOr if I am not creator use /setlink to set your link" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "link Group ["..msg.to.title.."] :\n"..group_link end if matches[1] == "invite" and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1] == 'res' and is_owner(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'res' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username) resolve_username(username, callbackres, cbres_extra) end --[[if matches[1] == 'kick' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) @DevPointTeam end]] if matches[1] == 'setadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setadmin', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setadmin' and string.match(matches[2], '^%d+$') then --[[] local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'setadmin' Dev = Point user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]] local get_cmd = 'setadmin' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setadmin' and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channel = get_receiver(msg), get_cmd = 'setadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'setadmin' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'demoteadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demoteadmin', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demoteadmin' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demoteadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'demoteadmin' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demoteadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username) resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'setowner' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setowner', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setowner' and string.match(matches[2], '^%d+$') then --[[ local group_owner = data[tostring(msg.to.id)]['set_owner'] if group_owner then local receiver = get_receiver(msg) local user_id = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user_id, ok_cb, false) end local user = "user#id"..matches[2] channel_set_admin(receiver, user, ok_cb, false) data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2]) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = "[ "..matches[2].." ] added as owner" return text Dev = Point end]] local get_cmd = 'setowner' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setowner' and not string.match(matches[2], '^%d+$') then local get_cmd = 'setowner' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'promote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'promote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'promote' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'mp' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_set_mod(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'md' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'demote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/support/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demote' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == "setname" and is_momod(msg) then local receiver = get_receiver(msg) local set_name = string.gsub(matches[2], '_', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2]) rename_channel(receiver, set_name, ok_cb, false) end if msg.service and msg.action.type == 'chat_rename' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title) data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title save_data(_config.moderation.data, data) end if matches[1] == "setabout" and is_momod(msg) then local receiver = get_receiver(msg) local about_text = matches[2] local data_cat = 'description' local target = msg.to.id data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text) channel_set_about(receiver, about_text, ok_cb, false) return "Description has been set.\n\nSelect the chat again to see the changes." end if matches[1] == "setusername" and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.") elseif success == 0 then send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.") end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1] == 'setrules' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]") return set_rulesmod(msg, data, target) end if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo") load_photo(msg.id, set_supergroup_photo, msg) return end end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo") return 'Please send the new group photo now' end if matches[1] == 'clean' then if not is_momod(msg) then return end if not is_momod(msg) then return "Only owner can clean" end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator(s) in this SuperGroup.' end for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") return 'Modlist has been cleaned' end if matches[2] == 'rules' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "Rules have not been set" end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") return 'Rules have been cleaned' end if matches[2] == 'about' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'About is not set' end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") channel_set_about(receiver, about_text, ok_cb, false) return "About has been cleaned" end if matches[2] == 'silentlist' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "silentlist Cleaned" end if matches[2] == 'username' and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username cleaned.") elseif success == 0 then send_large_msg(receiver, "Failed to clean SuperGroup username.") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end end if matches[1] == 'lock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'all' then local safemode ={ lock_group_links(msg, data, target), lock_group_tag(msg, data, target), lock_group_spam(msg, data, target), lock_group_flood(msg, data, target), lock_group_arabic(msg, data, target), lock_group_membermod(msg, data, target), lock_group_rtl(msg, data, target), lock_group_tgservice(msg, data, target), lock_group_sticker(msg, data, target), lock_group_contacts(msg, data, target), lock_group_english(msg, data, target), lock_group_fwd(msg, data, target), lock_group_reply(msg, data, target), lock_group_join(msg, data, target), lock_group_emoji(msg, data, target), lock_group_username(msg, data, target), lock_group_fosh(msg, data, target), lock_group_media(msg, data, target), lock_group_leave(msg, data, target), lock_group_bots(msg, data, target), lock_group_operator(msg, data, target), } return lock_group_all(msg, data, target), safemode end if matches[2] == 'etehad' then local etehad ={ unlock_group_links(msg, data, target), lock_group_tag(msg, data, target), lock_group_spam(msg, data, target), lock_group_flood(msg, data, target), unlock_group_arabic(msg, data, target), lock_group_membermod(msg, data, target), unlock_group_rtl(msg, data, target), lock_group_tgservice(msg, data, target), lock_group_sticker(msg, data, target), unlock_group_contacts(msg, data, target), unlock_group_english(msg, data, target), unlock_group_fwd(msg, data, target), unlock_group_reply(msg, data, target), lock_group_join(msg, data, target), unlock_group_emoji(msg, data, target), unlock_group_username(msg, data, target), lock_group_fosh(msg, data, target), unlock_group_media(msg, data, target), lock_group_leave(msg, data, target), lock_group_bots(msg, data, target), unlock_group_operator(msg, data, target), } return lock_group_etehad(msg, data, target), etehad end if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked join ") return lock_group_join(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ") return lock_group_tag(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions") return lock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end if matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english") return lock_group_english(msg, data, target) end if matches[2] == 'fwd' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fwd") return lock_group_fwd(msg, data, target) end if matches[2] == 'reply' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked reply") return lock_group_reply(msg, data, target) end if matches[2] == 'emoji' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked emoji") return lock_group_emoji(msg, data, target) end if matches[2] == 'badword' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fosh") return lock_group_fosh(msg, data, target) end if matches[2] == 'media' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked media") return lock_group_media(msg, data, target) end if matches[2] == 'username' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked username") return lock_group_username(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leave") return lock_group_leave(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots") return lock_group_bots(msg, data, target) end if matches[2] == 'operator' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked operator") return lock_group_operator(msg, data, target) end end if matches[1] == 'unlock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'all' then local dsafemode ={ unlock_group_links(msg, data, target), unlock_group_tag(msg, data, target), unlock_group_spam(msg, data, target), unlock_group_flood(msg, data, target), unlock_group_arabic(msg, data, target), unlock_group_membermod(msg, data, target), unlock_group_rtl(msg, data, target), unlock_group_tgservice(msg, data, target), unlock_group_sticker(msg, data, target), unlock_group_contacts(msg, data, target), unlock_group_english(msg, data, target), unlock_group_fwd(msg, data, target), unlock_group_reply(msg, data, target), unlock_group_join(msg, data, target), unlock_group_emoji(msg, data, target), unlock_group_username(msg, data, target), unlock_group_fosh(msg, data, target), unlock_group_media(msg, data, target), unlock_group_leave(msg, data, target), unlock_group_bots(msg, data, target), unlock_group_operator(msg, data, target), } return unlock_group_all(msg, data, target), dsafemode end if matches[2] == 'etehad' then local detehad ={ lock_group_links(msg, data, target), unlock_group_tag(msg, data, target), lock_group_spam(msg, data, target), lock_group_flood(msg, data, target), unlock_group_arabic(msg, data, target), unlock_group_membermod(msg, data, target), unlock_group_rtl(msg, data, target), unlock_group_tgservice(msg, data, target), unlock_group_sticker(msg, data, target), unlock_group_contacts(msg, data, target), unlock_group_english(msg, data, target), unlock_group_fwd(msg, data, target), unlock_group_reply(msg, data, target), unlock_group_join(msg, data, target), unlock_group_emoji(msg, data, target), unlock_group_username(msg, data, target), unlock_group_fosh(msg, data, target), unlock_group_media(msg, data, target), unlock_group_leave(msg, data, target), unlock_group_bots(msg, data, target), unlock_group_operator(msg, data, target), } return unlock_group_etehad(msg, data, target), detehad end if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked join") return unlock_group_join(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag") return unlock_group_tag(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic") return unlock_group_arabic(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions") return unlock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end if matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english") return unlock_group_english(msg, data, target) end if matches[2] == 'fwd' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fwd") return unlock_group_fwd(msg, data, target) end if matches[2] == 'reply' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked reply") return unlock_group_reply(msg, data, target) end if matches[2] == 'emoji' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled emoji") return unlock_group_emoji(msg, data, target) end if matches[2] == 'badword' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fosh") return unlock_group_fosh(msg, data, target) end if matches[2] == 'media' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked media") return unlock_group_media(msg, data, target) end if matches[2] == 'username' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled username") return unlock_group_username(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leave") return unlock_group_leave(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots") return unlock_group_bots(msg, data, target) end if matches[2] == 'operator' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked operator") return unlock_group_operator(msg, data, target) end end if matches[1] == 'setflood' then if not is_momod(msg) then return end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Flood has been set to: '..matches[2] end if matches[1] == 'public' and is_momod(msg) then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public") return unset_public_membermod(msg, data, target) end end if matches[1] == 'mute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Audio has been muted 🎵🔐\n👮 Order by :️ @'..msg.from.username else return 'Audio is already muted 🎵🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'photo' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Photo has been muted 🎡🔐\n👮 Order by :️ @'..msg.from.username else return 'Photo is already muted 🎡🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'video' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Video has been muted 🎥🔐\n👮 Order by :️ @'..msg.from.username else return 'Video is already muted 🎥🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Gifs has been muted 🎆🔐\n👮 Order by :️ @'..msg.from.username else return 'Gifs is already muted 🎆🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'doc' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'documents has been muted 📂🔐\n👮 Order by :️ @'..msg.from.username else return 'documents is already muted 📂🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'text' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Text has been muted 📝🔐\n👮 Order by :️ @'..msg.from.username else return 'Text is already muted 📝🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'all' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Mute all has been enabled 🔕\n👮 Order by :️ @'..msg.from.username else return 'Mute all is already enabled 🔕\n👮 Order by :️ @'..msg.from.username end end end if matches[1] == 'unmute' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Audio has been unmuted 🎵🔓\n👮 Order by :️ @'..msg.from.username else return 'Audio is already unmuted 🎵🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'photo' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Photo has been unmuted 🎡🔓\n👮 Order by :️ @'..msg.from.username else return 'Photo is already unmuted 🎡🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'video' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Video has been unmuted 🎥🔓\n👮 Order by :️ @'..msg.from.username else return 'Video is already unmuted 🎥🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Gifs has been unmuted 🎆🔓\n👮 Order by :️ @'..msg.from.username else return 'Gifs is already unmuted 🎆🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'doc' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'documents has been unmuted 📂🔓\n👮 Order by :️ @'..msg.from.username else return 'documents is already unmuted 📂🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'text' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message") unmute(chat_id, msg_type) return 'Text has been unmuted 📝🔓\n👮 Order by :️ @'..msg.from.username else return 'Text is already unmuted 📝🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'all' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Mute all has been disabled 🔔\n👮 Order by :️ @'..msg.from.username else return 'Mute all is already disabled 🔔\n👮 Order by :️ @'..msg.from.username end end end if matches[1] == "silent" or matches[1] == "unsilent" and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg}) elseif matches[1] == "silent" or matches[1] == "unsilent" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list") return "["..user_id.."] removed from the muted users list" elseif is_momod(msg) then mute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list") return "["..user_id.."] added to the muted user list" end elseif matches[1] == "silent" or matches[1] == "unsilent" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg}) end end if matches[1] == "muteslist" and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "silentlist" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'settings' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ") return show_supergroup_settingsmod(msg, target) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'help' and not is_owner(msg) then text = "Only managers 😐⛔️" reply_msg(msg.id, text, ok_cb, false) elseif matches[1] == 'help' and is_owner(msg) then local name_log = user_print_name(msg.from) savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end if matches[1] == 'peer_id' and is_admin1(msg)then text = msg.to.peer_id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end if matches[1] == 'msg.to.id' and is_admin1(msg) then text = msg.to.id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end --Admin Join Service Message if msg.service then local action = msg.action.type if action == 'chat_add_user_link' then if is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.from.id) and not is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup") channel_set_mod(receiver, user, ok_cb, false) end end if action == 'chat_add_user' then if is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_mod(receiver, user, ok_cb, false) end end end if matches[1] == 'msg.to.peer_id' then post_large_msg(receiver, msg.to.peer_id) end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/]([Aa]ddbot)$", "^[#!/]([Rr]embot)$", "^[#!/]([Mm]ove) (.*)$", "^[#!/]([Gg]pinfo)$", "^[#!/]([Aa]dmins)$", "^[#!/]([Oo]wner)$", "^[#!/]([Mm]odlist)$", "^[#!/]([Bb]ots)$", "^[#!/]([Ww]ho)$", "^[#!/]([Kk]icked)$", "^[#!/]([Bb]b) (.*)", "^[#!/]([Bb]b)", "^[#!/]([Kk]ick) (.*)", "^[#!/]([Kk]ick)", "^[#!/]([Tt]osuper)$", "^[#!/]([Ii][Dd])$", "^[#!/]([Ii][Dd]) (.*)$", "^[#!/]([Kk]ickme)$", "^[#!/]([Nn]ewlink)$", "^[#!/]([Ss]etlink)$", "^[#!/]([Ll]ink)$", "^[#!/]([Rr]es) (.*)$", "^[#!/]([Ss]etadmin) (.*)$", "^[#!/]([Ss]etadmin)", "^[#!/]([Dd]emoteadmin) (.*)$", "^[#!/]([Dd]emoteadmin)", "^[#!/]([Ss]etowner) (.*)$", "^[#!/]([Ss]etowner)$", "^[#!/]([Pp]romote) (.*)$", "^[#!/]([Pp]romote)", "^[#!/]([Dd]emote) (.*)$", "^[#!/]([Dd]emote)", "^[#!/]([Ss]etname) (.*)$", "^[#!/]([Ss]etabout) (.*)$", "^[#!/]([Ss]etrules) (.*)$", "^[#!/]([Ss]etphoto)$", "^[#!/]([Ss]etusername) (.*)$", "^[#!/]([Dd]el)$", "^[#!/]([Ll]ock) (.*)$", "^[#!/]([Uu]nlock) (.*)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^[#!/]([Ss]ilent)$", "^[#!/]([Ss]ilent) (.*)$", "^[#!/]([Uu]nsilent)$", "^[#!/]([Uu]nsilent) (.*)$", "^[#!/]([Pp]ublic) (.*)$", "^[#!/]([Ss]ettings)$", "^[#!/]([Rr]ules)$", "^[#!/]([Ss]etflood) (%d+)$", "^[#!/]([Cc]lean) (.*)$", "^[#!/]([Hh]elp)$", "^[#!/]([Mm]uteslist)$", "^[#!/]([Ss]ilentlist)$", "[#!/](mp) (.*)", "[#!/](md) (.*)", "^(https://telegram.me/joinchat/%S+)$", "msg.to.peer_id", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = DevPointTeam, pre_process = pre_process } --@DevPointTeam --@TH3_GHOST
gpl-2.0
nyczducky/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm8.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm8 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED2); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED2); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); 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); end;
gpl-3.0
mynameiscraziu/mycaty
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
Shayan123456/bottttttt
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
nyczducky/darkstar
scripts/zones/Bastok_Mines/npcs/Proud_Beard.lua
17
1688
----------------------------------- -- Area: Bastok Mines -- NPC: Proud Beard -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); require("scripts/globals/events/harvest_festivals"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,PROUDBEARD_SHOP_DIALOG); stock = { 0x3157, 276, --Hume Tunic 0x3158, 276, --Hume Vest 0x31D2, 165, --Hume M Gloves 0x31D8, 165, --Hume F Gloves 0x3253, 239, --Hume Slacks 0x3254, 239, --Hume Pants 0x32CD, 165, --Hume M Boots 0x32D2, 165, --Hume F Boots 0x315D, 276, --Galkan Surcoat 0x31D6, 165, --Galkan Bracers 0x3258, 239, --Galkan Braguette 0x32D1, 165 --Galkan Sandals } 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
nyczducky/darkstar
scripts/zones/Temple_of_Uggalepih/npcs/Old_Casket.lua
14
1557
----------------------------------- -- Area: Temple of Uggalepih -- NPC: Old casket -- Obtaining 'Paintbrush of Souls' -- @pos 61 0 17 159 ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Temple_of_Uggalepih/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(OLD_RUSTY_KEY)) then player:startEvent(0x0040,OLD_RUSTY_KEY); elseif (player:hasKeyItem(PAINTBRUSH_OF_SOULS)) then player:messageSpecial(NO_REASON_TO_INVESTIGATE); else player:messageSpecial(THE_BOX_IS_LOCKED); 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 == 0x0040 and option == 1) then player:delKeyItem(OLD_RUSTY_KEY); player:addKeyItem(PAINTBRUSH_OF_SOULS); player:messageSpecial(KEYITEM_OBTAINED,PAINTBRUSH_OF_SOULS); end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Lower_Jeuno/npcs/Chetak.lua
17
1423
----------------------------------- -- Area: Lower Jeuno -- NPC: Chetak -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CHETAK_SHOP_DIALOG); stock = {0x30B2,20000, -- Red Cap 0x30B3,45760, -- Wool Cap 0x30BA,11166, -- Wool Hat 0x3132,32500, -- Gambison 0x3142,33212, -- Cloak 0x3133,68640, -- Wool Gambison 0x313A,18088, -- Wool Robe 0x3141,9527, -- Black Tunic 0x31B2,16900, -- Bracers 0x31C2,15732, -- Linen Mitts 0x31BA,10234, -- Wool Cuffs 0x31C1,4443} -- White Mitts 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
nyczducky/darkstar
scripts/zones/Ranguemont_Pass/npcs/Perchond.lua
14
1698
----------------------------------- -- Area: Ranguemont Pass -- NPC: Perchond -- @pos -182.844 4 -164.948 166 ----------------------------------- package.loaded["scripts/zones/Ranguemont_Pass/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1107,1) and trade:getItemCount() == 1) then -- glitter sand local SinHunting = player:getVar("sinHunting"); -- RNG AF1 if (SinHunting == 2) then player:startEvent(0x0005); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SinHunting = player:getVar("sinHunting"); -- RNG AF1 if (SinHunting == 1) then player:startEvent(0x0003, 0, 1107); else player:startEvent(0x0002); 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 == 3) then player:setVar("sinHunting",2); elseif (csid == 5) then player:tradeComplete(); player:addKeyItem(PERCHONDS_ENVELOPE); player:messageSpecial(KEYITEM_OBTAINED,PERCHONDS_ENVELOPE); player:setVar("sinHunting",3); end end;
gpl-3.0
oldstylejoe/vlc-timed
share/lua/playlist/koreus.lua
57
4037
--[[ Copyright © 2009 the VideoLAN team 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() if vlc.access ~= "http" and vlc.access ~= "https" then return false end koreus_site = string.match( vlc.path, "koreus" ) if not koreus_site then return false end return ( string.match( vlc.path, "video" ) ) -- http://www.koreus.com/video/pouet.html end -- Parse function. function parse() while true do line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.-)\"" ) name = vlc.strings.resolve_xml_special_chars( name ) end if string.match( line, "<meta property=\"og:description\"" ) then _,_,description = string.find( line, "content=\"(.-)\"" ) if (description ~= nil) then description = vlc.strings.resolve_xml_special_chars( description ) end end if string.match( line, "<span id=\"spoil\" style=\"display:none\">" ) then _,_,desc_spoil = string.find( line, "<span id=\"spoil\" style=\"display:none\">(.-)</span>" ) desc_spoil = vlc.strings.resolve_xml_special_chars( desc_spoil ) description = description .. "\n\r" .. desc_spoil end if string.match( line, "<meta name=\"author\"" ) then _,_,artist = string.find( line, "content=\"(.-)\"" ) artist = vlc.strings.resolve_xml_special_chars( artist ) end if string.match( line, "link rel=\"image_src\"" ) then _,_,arturl = string.find( line, "href=\"(.-)\"" ) end vid_url = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.mp4)' ) if vid_url then path_url = vid_url end vid_url_hd = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%-hd%.mp4)' ) if vid_url_hd then path_url_hd = vid_url_hd end vid_url_webm = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.webm)' ) if vid_url_webm then path_url_webm = vid_url_webm end vid_url_flv = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.flv)' ) if vid_ulr_flv then path_url_flv = vid_url_flv end end if path_url_hd then if vlc.access == 'https' then path_url_hd = path_url_hd:gsub('http','https') end return { { path = path_url_hd; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url then if vlc.access == 'https' then path_url = path_url:gsub('http','https') end return { { path = path_url; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url_webm then if vlc.access == 'https' then path_url_webm = path_url_webm:gsub('http','https') end return { { path = path_url_webm; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url_flv then if vlc.access == 'https' then path_url_flv = path_url_flv:gsub('http','https') end return { { path = path_url_flv; name = name; description = description; artist = artist; arturl = arturl } } else return {} end end
gpl-2.0
nyczducky/darkstar
scripts/globals/weaponskills/stardiver.lua
22
1598
----------------------------------- -- Stardiver -- Polearm weapon skill -- Skill Level: MERIT -- Delivers a fourfold attack. Damage varies with TP. -- Will stack with Sneak Attack. reduces params.crit hit evasion by 5% -- Element: None -- Modifiers: STR:73~85% -- 100%TP 200%TP 300%TP -- 0.75 1.25 1.75 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 4; params.ftp100 = 0.75; params.ftp200 = 1.25; params.ftp300 = 1.75; params.str_wsc = 0.85 + (player:getMerit(MERIT_STARDIVER) / 100); params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.7 + (player:getMerit(MERIT_STARDIVER) / 100); end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0 and target:hasStatusEffect(EFFECT_CRIT_HIT_EVASION_DOWN) == false) then target:addStatusEffect(EFFECT_CRIT_HIT_EVASION_DOWN, 5, 0, 60); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nyczducky/darkstar
scripts/zones/Zeruhn_Mines/npcs/Zelman.lua
17
1793
----------------------------------- -- Area: Zeruhn Mines -- NPC: Zelman -- Involved In Quest: Groceries ----------------------------------- package.loaded["scripts/zones/Zeruhn_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Zeruhn_Mines/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local GroceriesVar = player:getVar("Groceries"); local GroceriesViewedNote = player:getVar("GroceriesViewedNote"); if (GroceriesVar == 2) then player:showText(npc,7279); elseif (GroceriesVar == 1) then ViewedNote = player:seenKeyItem(TAMIS_NOTE); if (ViewedNote == true) then player:startEvent(0x00a2); else player:startEvent(0x00a1); end else player:startEvent(0x00a0); 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 == 0x00a1) then player:setVar("Groceries",2); player:delKeyItem(TAMIS_NOTE); elseif (csid == 0x00a2) then player:setVar("GroceriesViewedNote",1); player:delKeyItem(TAMIS_NOTE); end end;
gpl-3.0
hadess/libquvi-scripts-iplayer
share/lua/website/redtube.lua
4
2325
-- libquvi-scripts -- Copyright (C) 2012 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library 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 -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local Redtube = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "redtube%.com" r.formats = "default" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/%d+", "/player/"}) return r end -- Query available formats. function query_formats(self) self.formats = 'default' return self end -- Parse media URL. function parse(self) self.host_id = "redtube" Redtube.normalize(self) self.id = self.page_url:match('/(%d+)') or error("no match: media ID") local p = quvi.fetch(self.page_url) self.title = p:match('<title>(.-) |') or error("no match: media title") self.thumbnail_url = p:match('<img src=%"(.-)%" .- id=%"vidImgPoster%"') or '' self.url = {p:match('(http://videos.mp4.redtubefiles.com/.-)\'') or error("no match: media stream URL")} return self end -- -- Utility functions -- function Redtube.normalize(self) -- "Normalize" an embedded URL local p = 'http://embed%.redtube%.com/player/%?id=(%d+).?' local id = self.page_url:match(p) if not id then return end self.page_url = 'http://www.redtube.com/' .. id end -- vim: set ts=4 sw=4 tw=72 expandtab:
lgpl-2.1
jbeich/Aquaria
files/scripts/maps/node_naija_openwaters.lua
6
1105
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) end function update(me, dt) if isFlag(FLAG_NAIJA_OPENWATERS,0) then if node_isEntityIn(me, getNaija()) then voice("naija_openwaters") setFlag(FLAG_NAIJA_OPENWATERS, 1) end end end
gpl-2.0
oldstylejoe/vlc-timed
share/lua/modules/dkjson.lua
95
25741
--[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.1* 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) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This is mainly useful for tables that can be empty. (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.1"`. `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 functions `quotestring` and `decode`. 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 this option: --]==] local always_try_using_lpeg = true --[==[ 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. You can contact the author by sending an e-mail to 'kolf' at the e-mail provider 'gmx.de'. --------------------------------------------------------------------- *Copyright (C) 2010, 2011 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 = error, require, pcall 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 common = require ("common") local us_tostring = common.us_tostring if _VERSION == 'Lua 5.1' then local function noglobals (s,k,v) error ("global access: " .. k, 2) end setfenv (1, setmetatable ({}, { __index = noglobals, __newindex = noglobals })) end local _ENV = nil -- blocking globals in Lua 5.2 local json = { version = "dkjson 2.1" } 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 = us_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 metatype = valmeta and valmeta.__jsontype local isa, n if metatype == 'array' then isa = true n = value.n or #value elseif metatype == 'object' then isa = false else isa, n = isarray (value) 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, 1 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 function json.decode (str, pos, nullval, objectmeta, arraymeta) objectmeta = objectmeta or {__jsontype = 'object'} arraymeta = arraymeta or {__jsontype = 'array'} 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 SpecialChars = (R"\0\31" + S"\"\\\127" + P"\194" * (R"\128\159" + P"\173") + P"\216" * R"\128\132" + P"\220\132" + P"\225\158" * S"\180\181" + P"\226\128" * (R"\140\143" + S"\168\175") + P"\226\129" * R"\160\175" + P"\239\187\191" + P"\229\191" + R"\176\191") / escapeutf8 local QuoteStr = g.Cs (g.Cc "\"" * (SpecialChars + 1)^0 * g.Cc "\"") quotestring = function (str) return pegmatch (QuoteStr, str) end json.quotestring = quotestring 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, objectmeta, arraymeta) local state = { objectmeta = objectmeta or {__jsontype = 'object'}, arraymeta = arraymeta or {__jsontype = 'array'} } 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 -->
gpl-2.0
nyczducky/darkstar
scripts/zones/Arrapago_Remnants/instances/arrapago_remnants.lua
29
3716
----------------------------------- -- -- Salvage: Arrapago Remnants -- ----------------------------------- require("scripts/globals/instance") package.loaded["scripts/zones/Arrapago_Remnants/IDs"] = nil; local Arrapago = require("scripts/zones/Arrapago_Remnants/IDs"); ----------------------------------- -- afterInstanceRegister ----------------------------------- function afterInstanceRegister(player) local instance = player:getInstance(); player:messageSpecial(Arrapago.text.TIME_TO_COMPLETE, instance:getTimeLimit()); player:messageSpecial(Arrapago.text.SALVAGE_START, 1); player:addStatusEffectEx(EFFECT_ENCUMBRANCE_I, EFFECT_ENCUMBRANCE_I, 0xFFFF, 0, 0) player:addStatusEffectEx(EFFECT_OBLIVISCENCE, EFFECT_OBLIVISCENCE, 0, 0, 0) player:addStatusEffectEx(EFFECT_OMERTA, EFFECT_OMERTA, 0, 0, 0) player:addStatusEffectEx(EFFECT_IMPAIRMENT, EFFECT_IMPAIRMENT, 0, 0, 0) player:addStatusEffectEx(EFFECT_DEBILITATION, EFFECT_DEBILITATION, 0x1FF, 0, 0) for i = 0,15 do player:unequipItem(i) end end; ----------------------------------- -- onInstanceCreated ----------------------------------- function onInstanceCreated(instance) for i,v in pairs(Arrapago.npcs[1][1]) do local npc = instance:getEntity(bit.band(v, 0xFFF), TYPE_NPC); npc:setStatus(STATUS_NORMAL) end instance:setStage(1) end; ----------------------------------- -- onInstanceTimeUpdate ----------------------------------- function onInstanceTimeUpdate(instance, elapsed) updateInstanceTime(instance, elapsed, Arrapago.text) end; ----------------------------------- -- onInstanceFailure ----------------------------------- function onInstanceFailure(instance) local chars = instance:getChars(); for i,v in pairs(chars) do v:messageSpecial(Arrapago.text.MISSION_FAILED,10,10); v:startEvent(0x66); end end; ----------------------------------- -- onInstanceProgressUpdate ----------------------------------- function onInstanceProgressUpdate(instance, progress) if instance:getStage() == 1 and progress == 10 then SpawnMob(Arrapago.mobs[1][2].rampart, instance) elseif instance:getStage() == 3 and progress == 0 then SpawnMob(Arrapago.mobs[2].astrologer, instance) end end; ----------------------------------- -- onInstanceComplete ----------------------------------- function onInstanceComplete(instance) end; function onRegionEnter(player,region) if region:GetRegionID() <= 10 then player:startEvent(199 + region:GetRegionID()) end end function onEventUpdate(entity, eventid, result) if (eventid >= 200 and eventid <= 203) then local instance = entity:getInstance() if instance:getProgress() == 0 then for id = Arrapago.mobs[2][eventid-199].mobs_start, Arrapago.mobs[2][eventid-199].mobs_end do SpawnMob(id, instance) end instance:setProgress(eventid-199) end elseif eventid == 204 then -- spawn floor 3 end end function onEventFinish(entity, eventid, result) local instance = entity:getInstance() if (eventid >= 200 and eventid <= 203) then for id = Arrapago.mobs[1][2].mobs_start, Arrapago.mobs[1][2].mobs_end do DespawnMob(id, instance) end DespawnMob(Arrapago.mobs[1][2].rampart, instance) DespawnMob(Arrapago.mobs[1][2].sabotender, instance) elseif eventid == 204 then for _,v in ipairs(Arrapago.mobs[2]) do for id = v.mobs_start, v.mobs_end do DespawnMob(id, instance) end end DespawnMob(Arrapago.mobs[2].astrologer, instance) end end
gpl-3.0
JohnWich/MEGA-john-wich
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
moltafet35/senatorv2
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
forivall/dotfiles
wezterm.lua
1
1549
local wezterm = require 'wezterm'; return { default_prog = {"/usr/local/bin/zsh"}, freetype_load_target = "Light", freetype_load_flags = "NO_HINTING", font = wezterm.font("FantasqueSansMono Nerd Font", {}), font_size=12.24, line_height=1.1, font_antialias="Subpixel", color_scheme = "Tomorrow Night", -- colors = { -- -- The default text color -- foreground = "silver", -- -- The default background color -- background = "black", -- -- Overrides the cell background color when the current cell is occupied by the -- -- cursor and the cursor style is set to Block -- cursor_bg = "#52ad70", -- -- Overrides the text color when the current cell is occupied by the cursor -- cursor_fg = "black", -- -- Specifies the border color of the cursor when the cursor style is set to Block, -- -- of the color of the vertical or horizontal bar when the cursor style is set to -- -- Bar or Underline. -- cursor_border = "#52ad70", -- -- the foreground color of selected text -- selection_fg = "black", -- -- the background color of selected text -- selection_bg = "#fffacd", -- -- The color of the scrollbar "thumb"; the portion that represents the current viewport -- scrollbar_thumb = "#222222", -- -- The color of the split lines between panes -- split = "#444444", -- ansi = {"black", "maroon", "green", "olive", "navy", "purple", "teal", "silver"}, -- brights = {"grey", "red", "lime", "yellow", "blue", "fuchsia", "aqua", "white"}, -- }, }
isc
hanikk/tele-you
plugins/weather.lua
274
1531
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) location = string.gsub(location," ","+") local url = BASE_URL url = url..'?q='..location url = url..'&units=metric' url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Madrid,ES' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Madrid is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
gpl-2.0
vorbi123/x
plugins/add.lua
527
44020
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(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 = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
naxiwer/Atlas
lib/admin-sql.lua
40
8858
--[[ $%BEGINLICENSE%$ Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --- -- map SQL commands to the hidden MySQL Protocol commands -- -- some protocol commands are only available through the mysqladmin tool like -- * ping -- * shutdown -- * debug -- * statistics -- -- ... while others are avaible -- * process info (SHOW PROCESS LIST) -- * process kill (KILL <id>) -- -- ... and others are ignored -- * time -- -- that way we can test MySQL Servers more easily with "mysqltest" -- --- -- recognize special SQL commands and turn them into COM_* sequences -- function read_query(packet) if packet:byte() ~= proxy.COM_QUERY then return end if packet:sub(2) == "COMMIT SUICIDE" then proxy.queries:append(proxy.COM_SHUTDOWN, string.char(proxy.COM_SHUTDOWN), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PING" then proxy.queries:append(proxy.COM_PING, string.char(proxy.COM_PING), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "STATISTICS" then proxy.queries:append(proxy.COM_STATISTICS, string.char(proxy.COM_STATISTICS), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PROCINFO" then proxy.queries:append(proxy.COM_PROCESS_INFO, string.char(proxy.COM_PROCESS_INFO), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "TIME" then proxy.queries:append(proxy.COM_TIME, string.char(proxy.COM_TIME), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "DEBUG" then proxy.queries:append(proxy.COM_DEBUG, string.char(proxy.COM_DEBUG), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PROCKILL" then proxy.queries:append(proxy.COM_PROCESS_KILL, string.char(proxy.COM_PROCESS_KILL), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "SETOPT" then proxy.queries:append(proxy.COM_SET_OPTION, string.char(proxy.COM_SET_OPTION), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "BINLOGDUMP" then proxy.queries:append(proxy.COM_BINLOG_DUMP, string.char(proxy.COM_BINLOG_DUMP), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "BINLOGDUMP1" then proxy.queries:append(proxy.COM_BINLOG_DUMP, string.char(proxy.COM_BINLOG_DUMP) .. "\004\000\000\000" .. "\000\000" .. "\002\000\000\000" .. "\000" .. "" , { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "REGSLAVE" then proxy.queries:append(proxy.COM_REGISTER_SLAVE, string.char(proxy.COM_REGISTER_SLAVE), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "REGSLAVE1" then proxy.queries:append(proxy.COM_REGISTER_SLAVE, string.char(proxy.COM_REGISTER_SLAVE) .. "\001\000\000\000" .. -- server-id "\000" .. -- report-host "\000" .. -- report-user "\000" .. -- report-password ? "\001\000" .. -- our port "\000\000\000\000" .. -- recovery rank "\001\000\000\000" .. -- master id ... what ever that is "" , { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PREP" then proxy.queries:append(proxy.COM_STMT_PREPARE, string.char(proxy.COM_STMT_PREPARE), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PREP1" then proxy.queries:append(proxy.COM_STMT_PREPARE, string.char(proxy.COM_STMT_PREPARE) .. "SELECT ?", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "EXEC" then proxy.queries:append(proxy.COM_STMT_EXECUTE, string.char(proxy.COM_STMT_EXECUTE), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "EXEC1" then proxy.queries:append(proxy.COM_STMT_EXECUTE, string.char(proxy.COM_STMT_EXECUTE) .. "\001\000\000\000" .. -- stmt-id "\000" .. -- flags "\001\000\000\000" .. -- iteration count "\000" .. -- null-bits "\001" .. -- new-parameters "\000\254" .. "\004" .. "1234" .. "", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "DEAL" then proxy.queries:append(proxy.COM_STMT_CLOSE, string.char(proxy.COM_STMT_CLOSE), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "DEAL1" then proxy.queries:append(proxy.COM_STMT_CLOSE, string.char(proxy.COM_STMT_CLOSE) .. "\001\000\000\000", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "RESET" then proxy.queries:append(proxy.COM_STMT_RESET, string.char(proxy.COM_STMT_RESET), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "RESET1" then proxy.queries:append(proxy.COM_STMT_RESET, string.char(proxy.COM_STMT_RESET) .. "\001\000\000\000", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "FETCH" then proxy.queries:append(proxy.COM_STMT_FETCH, string.char(proxy.COM_STMT_FETCH), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "FETCH1" then proxy.queries:append(proxy.COM_STMT_FETCH, string.char(proxy.COM_STMT_FETCH) .. "\001\000\000\000" .. "\128\000\000\000", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "FLIST" then proxy.queries:append(proxy.COM_FIELD_LIST, string.char(proxy.COM_FIELD_LIST), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "FLIST1" then proxy.queries:append(proxy.COM_FIELD_LIST, string.char(proxy.COM_FIELD_LIST) .. "t1\000id\000\000\000", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "TDUMP" then proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "TDUMP1" then proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP) .. "\004test\002t1", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "TDUMP2" then proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP) .. "\004test\002t2", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY end end --- -- adjust the response to match the needs of COM_QUERY -- where neccesary -- -- * some commands return EOF (COM_SHUTDOWN), -- * some are plain-text (COM_STATISTICS) -- -- in the end the client sent us a COM_QUERY and we have to hide -- all those specifics function read_query_result(inj) if inj.id == proxy.COM_SHUTDOWN or inj.id == proxy.COM_SET_OPTION or inj.id == proxy.COM_BINLOG_DUMP or inj.id == proxy.COM_STMT_PREPARE or inj.id == proxy.COM_STMT_FETCH or inj.id == proxy.COM_FIELD_LIST or inj.id == proxy.COM_TABLE_DUMP or inj.id == proxy.COM_DEBUG then -- translate the EOF packet from the COM_SHUTDOWN into a OK packet -- to match the needs of the COM_QUERY we got if inj.resultset.raw:byte() ~= 255 then proxy.response = { type = proxy.MYSQLD_PACKET_OK, } return proxy.PROXY_SEND_RESULT end elseif inj.id == proxy.COM_PING or inj.id == proxy.COM_TIME or inj.id == proxy.COM_PROCESS_KILL or inj.id == proxy.COM_REGISTER_SLAVE or inj.id == proxy.COM_STMT_EXECUTE or inj.id == proxy.COM_STMT_RESET or inj.id == proxy.COM_PROCESS_INFO then -- no change needed elseif inj.id == proxy.COM_STATISTICS then -- the response a human readable plain-text -- -- just turn it into a proper result-set proxy.response = { type = proxy.MYSQLD_PACKET_OK, resultset = { fields = { { name = "statisitics" } }, rows = { { inj.resultset.raw } } } } return proxy.PROXY_SEND_RESULT else -- we don't know them yet, just return ERR to the client to -- match the needs of COM_QUERY print(("got: %q"):format(inj.resultset.raw)) proxy.response = { type = proxy.MYSQLD_PACKET_ERR, } return proxy.PROXY_SEND_RESULT end end
gpl-2.0
MasterKia/xyself
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
hanikk/tele-you
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
skaasj/MemNN
MemN2N-lang-model/main.lua
18
5587
-- Copyright (c) 2015-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. require('xlua') require('paths') local tds = require('tds') paths.dofile('data.lua') paths.dofile('model.lua') local function train(words) local N = math.ceil(words:size(1) / g_params.batchsize) local cost = 0 local y = torch.ones(1) local input = torch.CudaTensor(g_params.batchsize, g_params.edim) local target = torch.CudaTensor(g_params.batchsize) local context = torch.CudaTensor(g_params.batchsize, g_params.memsize) local time = torch.CudaTensor(g_params.batchsize, g_params.memsize) input:fill(g_params.init_hid) for t = 1, g_params.memsize do time:select(2, t):fill(t) end for n = 1, N do if g_params.show then xlua.progress(n, N) end for b = 1, g_params.batchsize do local m = math.random(g_params.memsize + 1, words:size(1)-1) target[b] = words[m+1] context[b]:copy( words:narrow(1, m - g_params.memsize + 1, g_params.memsize)) end local x = {input, target, context, time} local out = g_model:forward(x) cost = cost + out[1] g_paramdx:zero() g_model:backward(x, y) local gn = g_paramdx:norm() if gn > g_params.maxgradnorm then g_paramdx:mul(g_params.maxgradnorm / gn) end g_paramx:add(g_paramdx:mul(-g_params.dt)) end return cost/N/g_params.batchsize end local function test(words) local N = math.ceil(words:size(1) / g_params.batchsize) local cost = 0 local input = torch.CudaTensor(g_params.batchsize, g_params.edim) local target = torch.CudaTensor(g_params.batchsize) local context = torch.CudaTensor(g_params.batchsize, g_params.memsize) local time = torch.CudaTensor(g_params.batchsize, g_params.memsize) input:fill(g_params.init_hid) for t = 1, g_params.memsize do time:select(2, t):fill(t) end local m = g_params.memsize + 1 for n = 1, N do if g_params.show then xlua.progress(n, N) end for b = 1, g_params.batchsize do target[b] = words[m+1] context[b]:copy( words:narrow(1, m - g_params.memsize + 1, g_params.memsize)) m = m + 1 if m > words:size(1)-1 then m = g_params.memsize + 1 end end local x = {input, target, context, time} local out = g_model:forward(x) cost = cost + out[1] end return cost/N/g_params.batchsize end local function run(epochs) for i = 1, epochs do local c, ct c = train(g_words_train) ct = test(g_words_valid) -- Logging local m = #g_log_cost+1 g_log_cost[m] = {m, c, ct} g_log_perp[m] = {m, math.exp(c), math.exp(ct)} local stat = {perplexity = math.exp(c) , epoch = m, valid_perplexity = math.exp(ct), LR = g_params.dt} if g_params.test then local ctt = test(g_words_test) table.insert(g_log_cost[m], ctt) table.insert(g_log_perp[m], math.exp(ctt)) stat['test_perplexity'] = math.exp(ctt) end print(stat) -- Learning rate annealing if m > 1 and g_log_cost[m][3] > g_log_cost[m-1][3] * 0.9999 then g_params.dt = g_params.dt / 1.5 if g_params.dt < 1e-5 then break end end end end local function save(path) local d = {} d.params = g_params d.paramx = g_paramx:float() d.log_cost = g_log_cost d.log_perp = g_log_perp torch.save(path, d) end -------------------------------------------------------------------- -------------------------------------------------------------------- -- model params: local cmd = torch.CmdLine() cmd:option('--gpu', 1, 'GPU id to use') cmd:option('--edim', 150, 'internal state dimension') cmd:option('--lindim', 75, 'linear part of the state') cmd:option('--init_std', 0.05, 'weight initialization std') cmd:option('--init_hid', 0.1, 'initial internal state value') cmd:option('--sdt', 0.01, 'initial learning rate') cmd:option('--maxgradnorm', 50, 'maximum gradient norm') cmd:option('--memsize', 100, 'memory size') cmd:option('--nhop', 6, 'number of hops') cmd:option('--batchsize', 128) cmd:option('--show', false, 'print progress') cmd:option('--load', '', 'model file to load') cmd:option('--save', '', 'path to save model') cmd:option('--epochs', 100) cmd:option('--test', false, 'enable testing') g_params = cmd:parse(arg or {}) print(g_params) cutorch.setDevice(g_params.gpu) g_vocab = tds.hash() g_ivocab = tds.hash() g_ivocab[#g_vocab+1] = '<eos>' g_vocab['<eos>'] = #g_vocab+1 g_words_train = g_read_words('data/ptb.train.txt', g_vocab, g_ivocab) g_words_valid = g_read_words('data/ptb.valid.txt', g_vocab, g_ivocab) g_words_test = g_read_words('data/ptb.test.txt', g_vocab, g_ivocab) g_params.nwords = #g_vocab print('vocabulary size ' .. #g_vocab) g_model = g_build_model(g_params) g_paramx, g_paramdx = g_model:getParameters() g_paramx:normal(0, g_params.init_std) if g_params.load ~= '' then local f = torch.load(g_params.load) g_paramx:copy(f.paramx) end g_log_cost = {} g_log_perp = {} g_params.dt = g_params.sdt print('starting to run....') run(g_params.epochs) if g_params.save ~= '' then save(g_params.save) end
bsd-3-clause
nyczducky/darkstar
scripts/globals/spells/kurayami_ni.lua
27
1143
----------------------------------------- -- Spell: Kurayami:Ni ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local duration = 300 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Kurayami base power is 30 and is not affected by resistaces. local power = 30; --Calculates resist chanve from Reist Blind if (math.random(0,100) >= target:getMod(MOD_BLINDRES)) then if (duration >= 150) then if (target:addStatusEffect(EFFECT_BLINDNESS,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end else spell:setMsg(284); end return EFFECT_BLINDNESS; end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Waughroon_Shrine/bcnms/rank_2_mission.lua
26
2002
----------------------------------- -- Area: Waughroon Shrine -- Name: Mission Rank 2 -- @pos -345 104 -260 144 ----------------------------------- package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Waughroon_Shrine/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompletedMission(player:getNation(),5)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if ((player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) and player:getVar("MissionStatus") == 10) then player:addKeyItem(KINDRED_CREST); player:messageSpecial(KEYITEM_OBTAINED,KINDRED_CREST); player:setVar("MissionStatus",11); end end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Promyvion-Holla/mobs/Memory_Receptacle.lua
15
7516
----------------------------------- -- Area: Promyvion-Holla -- MOB: Memory Receptacle -- Todo: clean up disgustingly bad formatting ----------------------------------- package.loaded["scripts/zones/Promyvion-Holla/TextIDs"] = nil; ----------------------------------- require( "scripts/zones/Promyvion-Holla/TextIDs" ); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 100); -- 10% Regain for now mob:SetAutoAttackEnabled(false); -- Recepticles only use TP moves. end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local Mem_Recep = mob:getID(); if (Mem_Recep == 16842781) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do -- Keep pets linked if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif (Mem_Recep == 16842839 or Mem_Recep == 16842846 or Mem_Recep == 16842853 or Mem_Recep == 16842860) then -- Floor 2 for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif (Mem_Recep == 16842886 or Mem_Recep == 16842895 or Mem_Recep == 16842904 or Mem_Recep == 16842938 or Mem_Recep == 16842947 or -- Floor 3 Mem_Recep == 16842956) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end end -- Summons a single stray every 30 seconds. if (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842781) and mob:AnimationSub() == 2) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do if (GetMobAction(i) == 0) then -- My Stray is deeaaaaaad! mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842839 or Mem_Recep == 16842846 or Mem_Recep == 16842853 or -- Floor 2 Mem_Recep == 16842860) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16842886 or Mem_Recep == 16842895 or Mem_Recep == 16842904 or -- Floor 3 Mem_Recep == 16842938 or Mem_Recep == 16842947 or Mem_Recep == 16842956) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); return; end end else mob:AnimationSub(2); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local rand = 0; local mobID = mob:getID(); local difX = player:getXPos()-mob:getXPos(); local difY = player:getYPos()-mob:getYPos(); local difZ = player:getZPos()-mob:getZPos(); local killeranimation = player:getAnimation(); local Distance = math.sqrt( math.pow(difX,2) + math.pow(difY,2) + math.pow(difZ,2) ); --calcul de la distance entre les "killer" et le memory receptacle -- print(mob:getID); mob:AnimationSub(0); -- Set ani. sub to default or the recepticles wont work properly if (VanadielMinute() % 2 == 1) then player:setVar("MemoryReceptacle",2); rnd = 2; else player:setVar("MemoryReceptacle",1); rnd = 1; end switch (mob:getID()) : caseof { [16842781] = function (x) GetNPCByID(16843057):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x0025); end end, [16842839] = function (x) GetNPCByID(16843053):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then player:startEvent(0x0021); else player:startEvent(0x0022); end end end, [16842846] = function (x) GetNPCByID(16843054):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then player:startEvent(0x0021); else player:startEvent(0x0022); end end end, [16842860] = function (x) GetNPCByID(16843056):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then player:startEvent(0x0021); else player:startEvent(0x0022); end end end, [16842853] = function (x) GetNPCByID(16843055):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then player:startEvent(0x0021); else player:startEvent(0x0022); end end end, [16842886] = function (x) GetNPCByID(16843050):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, [16842895] = function (x) GetNPCByID(16843051):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, [16842904] = function (x) GetNPCByID(16843052):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E) end end, [16842938] = function (x) GetNPCByID(16843058):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, [16842947] = function (x) GetNPCByID(16843059):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, [16842956] = function (x) GetNPCByID(16843060):openDoor(180); if (Distance <4 and killeranimation == 0) then player:startEvent(0x001E); end end, } end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ---------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (option==1) then player:setVar("MemoryReceptacle",0); end end;
gpl-3.0
wenhulove333/ScutServer
Sample/Koudai/Client/lua/scenes/HeroLvUp.lua
1
14046
------------------------------------------------------------------ -- HeroLvUp.lua -- Author : Zonglin Liu -- Version : 1.0 -- Date : -- Description: Ó¶±øÉý¼¶ ------------------------------------------------------------------ module("HeroLvUp", package.seeall) require("layers.HeroLvUpChoiceLayer") mScene = nil -- ³¡¾° function setGeneralID(generalID) mGeneralID = generalID end -- ³¡¾°Èë¿Ú function pushScene() initResource() createScene() end -- Í˳ö³¡¾° function popScene() MainScene.init() end function getBtnTable() return btnTable end; -- -------------------------˽ÓнӿÚ------------------------ -- -- ³õʼ»¯×ÊÔ´¡¢³ÉÔ±±äÁ¿ function initResource() btnTable = {} end -- ÊÍ·Å×ÊÔ´ function releaseResource() HeroLvUpChoiceLayer.releaseResource() if manLayer then manLayer:getParent():removeChild(manLayer, true) manLayer = nil end if showLayer ~= nil then showLayer:getParent():removeChild(showLayer, true) showLayer = nil end mLayer = nil mScene = nil mGeneralID = nil currentInfo = nil heroListInfo = nil mCurrentLevel=nil end -- ´´½¨³¡¾° function createScene() local scene = ScutScene:new() mScene = scene.root mScene:registerScriptHandler(SpriteEase_onEnterOrExit) scene:registerCallback(networkCallback) SlideInLReplaceScene(mScene,1) -- Ìí¼ÓÖ÷²ã mLayer= CCLayer:create() mScene:addChild(mLayer, 0) --Öмä²ã local midSprite=CCSprite:create(P("common/list_1040.png")) local boxSize=SZ(pWinSize.width,pWinSize.height*0.68) midSprite:setScaleX(boxSize.width/midSprite:getContentSize().width) midSprite:setScaleY(boxSize.height/midSprite:getContentSize().height) midSprite:setAnchorPoint(PT(0.5,0)) midSprite:setPosition(PT(pWinSize.width/2,pWinSize.height*0.145)) mLayer:addChild(midSprite,0) -- ´Ë´¦Ìí¼Ó³¡¾°³õʼÄÚÈÝ -- local tabName = { Language.ROLE_LVUP} -- createTabBar(tabName) --·µ»Ø°´Å¥ local exitBtn = ZyButton:new(Image.image_button, nil, nil, Language.IDS_BACK, FONT_NAME, FONT_SM_SIZE) exitBtn:setAnchorPoint(PT(1,0)) exitBtn:setPosition(PT(pWinSize.width*0.4, pWinSize.height*0.16)) exitBtn:addto(mLayer, 0) exitBtn:registerScriptHandler(popScene) --Éý¼¶°´Å¥ local button = ZyButton:new(Image.image_button, nil, nil, Language.ROLE_LVUP, FONT_NAME, FONT_SM_SIZE) button:setAnchorPoint(PT(0,0)) button:setPosition(PT(pWinSize.width*0.6, pWinSize.height*0.16)) button:addto(mLayer, 0) button:registerScriptHandler(LvUpAction) btnTable.lvUpBtn = button MainMenuLayer.init(1, mScene) showContent() end function SpriteEase_onEnterOrExit (tag) if tag == "exit" then releaseResource() end end --Tab½çÃæÇл» function createTabBar(tabName) local tabBar = ZyTabBar:new(Image.image_top_button_0, Image.image_top_button_1, tabName, FONT_NAME, FONT_SM_SIZE, 4, Image.image_LeftButtonNorPath, Image.image_rightButtonNorPath); tabBar:setCallbackFun(topTabBarAction); -----µã»÷Æô¶¯º¯Êý tabBar:addto(mLayer,0) ------Ìí¼Ó tabBar:setColor(ZyColor:colorYellow()) ---ÉèÖÃÑÕÉ« tabBar:setPosition(PT(SX(25),pWinSize.height*0.775)) -----ÉèÖÃ×ø±ê end function showContent() if showLayer ~= nil then showLayer:getParent():removeChild(showLayer, true) showLayer = nil end local layer = CCLayer:create() mLayer:addChild(layer, 0) showLayer = layer --Ó¶±ø´óͼƬ±³¾°] local imageBg = ZyButton:new("common/list_1085.png","common/list_1085.png",nil) imageBg:setAnchorPoint(PT(0,0)) local pos_y = pWinSize.height*0.34+pWinSize.height*0.475*0.5-imageBg:getContentSize().height*0.5 --pWinSize.height*0.825*0.95-imageBg:getContentSize().height imageBg:setPosition(PT(pWinSize.width*0.5-imageBg:getContentSize().width*0.5, pos_y)) imageBg:addto(layer, 0) imageBg:registerScriptHandler(key_hero) btnTable.imageBg = imageBg local image = nil if currentInfo and currentInfo.CurrHead then image = string.format("bigitem/%s.png", currentInfo.CurrHead) end if image then local headImage = CCSprite:create(P(image)) headImage:setAnchorPoint(PT(0,0)) local pos_x = imageBg:getContentSize().width*0.5-headImage:getContentSize().width*0.5 local pos_y = imageBg:getContentSize().height*0.09 headImage:setPosition(PT(pos_x, pos_y)) imageBg:addChild(headImage, 0) else local noticeLabel = CCLabelTTF:create(Language.ROLE_POINTCHOICE, FONT_NAME, FONT_SM_SIZE) noticeLabel:setAnchorPoint(PT(0.5, 0.5)) noticeLabel:setPosition(PT(imageBg:getContentSize().width*0.5, imageBg:getContentSize().height*0.5)) imageBg:addChild(noticeLabel, 0) end local cardInfo = {} if currentInfo then cardInfo = currentInfo.RecordTabel end btnTable.cardTable = {} for i=1,6 do local image, name, level,num = nil local tag = i local menberCallBack = key_to_choiceCost if cardInfo[i] then image = string.format("smallitem/%s.png", cardInfo[i].HeadID) name = cardInfo[i].ItemName num = cardInfo[i].ItemNum -- level = equiptInfo[i].ItemLv end local item = creatCardItem(image, name, level, tag, menberCallBack, num) local pos_x = pWinSize.width*0.1+pWinSize.width*0.65*(math.ceil(i/3)-1) local pos_y = imageBg:getPosition().y+imageBg:getContentSize().height-item:getContentSize().height*1.3*((i-1)%3+1) item:setAnchorPoint(PT(0,0)) item:setPosition(PT(pos_x, pos_y)) layer:addChild(item, 0) btnTable.cardTable [#btnTable.cardTable +1] = item end manInfo() if GuideLayer.judgeIsGuide(10) then GuideLayer.setScene(mScene) GuideLayer.init() end end; --Ñ¡ÔñÉý¼¶Ó¶±ø function key_hero() mCurrentLevel = nil sendAction(1401) end; --´´½¨¼¼ÄÜ£¬×°±¸ ¿¨Æ¬ С function creatCardItem(image, name, level, tag, menberCallBack, num) local menuItem = CCMenuItemImage:create(P(Image.image_touxiang_beijing), P(Image.image_touxiang_beijing)) local btn = CCMenu:createWithItem(menuItem) menuItem:setAnchorPoint(PT(0,0)) --ÏìÓ¦º¯Êý if menberCallBack then menuItem:registerScriptTapHandler(menberCallBack) end --Ë÷Òý if tag then menuItem:setTag(tag) end -- ͼƬ if image then local imageLabel = CCMenuItemImage:create(P(image),P(image)) if imageLabel == nil then return btn end imageLabel:setAnchorPoint(CCPoint(0.5, 0.5)) imageLabel:setPosition(PT(menuItem:getContentSize().width*0.5, menuItem:getContentSize().height*0.5)) menuItem:addChild(imageLabel,0) end --Ãû³Æ if name then local nameLabel = CCLabelTTF:create(name, FONT_NAME, FONT_SM_SIZE) nameLabel:setAnchorPoint(PT(0.5, 1)) nameLabel:setPosition(PT(menuItem:getContentSize().width*0.5, 0)) menuItem:addChild(nameLabel, 0) end if num then local nameLabel = CCLabelTTF:create("x"..num, FONT_NAME, FONT_SM_SIZE) nameLabel:setAnchorPoint(PT(1, 0)) nameLabel:setPosition(PT(menuItem:getContentSize().width*0.9, menuItem:getContentSize().height*0.1)) menuItem:addChild(nameLabel, 0) end btn:setContentSize(SZ(menuItem:getContentSize().width, menuItem:getContentSize().height)) return btn end; ----------------------------------------------------- --ÐÅÏ¢ function manInfo() if manLayer then manLayer:getParent():removeChild(manLayer, true) manLayer = nil end lot_width = pWinSize.width*0.8 lot_height = pWinSize.height*0.12 lot_x = (pWinSize.width-lot_width)*0.5 lot_y = pWinSize.height*0.22 local layer = CCLayer:create() layer:setAnchorPoint(PT(0,0)) layer:setPosition(PT(lot_x, lot_y)) mLayer:addChild(layer, 0) manLayer = layer local background = CCSprite:create(P("common/list_1052.9.png"));--±³¾°--common/transparentBg.png -- background:setScaleX(lot_width/background:getContentSize().width) background:setScaleY(lot_height/background:getContentSize().height) background:setAnchorPoint(PT(0.5,0)) background:setPosition(PT(lot_width*0.5,0)) layer:addChild(background,0) local pos_x = background:getPosition().x-background:getContentSize().width*0.48 local pos_y = lot_height*0.7 --²ß»®°¸°æ±¾ if currentInfo then --Ó¶±øÃû³Æ creatLabel(layer, Language.HERO_NAME, currentInfo.CurrGeneralName , pos_x, pos_y) --»ñµÃ¾­Ñé pos_y = lot_height*0.45 creatLabel(layer, Language.HERO_GETEXP, currentInfo.Experience , pos_x, pos_y) --Éý¼¶¾­Ñé pos_y = lot_height*0.2 if currentInfo.Percent~=0 then creatLabel(layer, Language.ROLE_UPEXP, currentInfo.UpExperience.."("..currentInfo.Percent..")" , pos_x, pos_y) else creatLabel(layer, Language.ROLE_UPEXP, currentInfo.UpExperience , pos_x, pos_y) end --µ±Ç°µÈ¼¶ pos_y = lot_height*0.7 pos_x = lot_width*0.52 creatLabel(layer, Language.HERO_CURRLV, currentInfo.CurrLv , pos_x, pos_y) --¿ÉÌáÉýµÈ¼¶ÖÁ pos_y = lot_height*0.45 if currentInfo.CurrLv==100 or currentInfo.NextLv==0 then creatLabel(layer, Language.HERO_NEXTLV, Language.HERO_SHANGXIAN , pos_x, pos_y) else creatLabel(layer, Language.HERO_NEXTLV, currentInfo.NextLv , pos_x, pos_y) end --Ì츳»ê¼¼ pos_y = lot_height*0.2 local skillInfo = SkillInfoConfig.getSkillInfo(currentInfo.AbilityID) local skillName = nil if skillInfo then skillName = skillInfo.AbilityName end creatLabel(layer, Language.PUB_ABILITY, skillName , pos_x, pos_y) end end; --´´½¨ÎÄ×Ö function creatLabel(parent, fitstName, secondName, x, y) if fitstName == nil then fitstName = "" end local firstLabel=CCLabelTTF:create(fitstName..":",FONT_NAME,FONT_SM_SIZE) firstLabel:setAnchorPoint(PT(0,0)) local color = ZyColor:colorYellow() if color~=nil then firstLabel:setColor(color) end firstLabel:setPosition(PT(x, y)) parent:addChild(firstLabel,0) if secondName == nil then secondName = "" end local secondLabel=CCLabelTTF:create(secondName,FONT_NAME,FONT_SM_SIZE) secondLabel:setAnchorPoint(PT(0,0)) secondLabel:setPosition(PT(firstLabel:getPosition().x+firstLabel:getContentSize().width, firstLabel:getPosition().y)) parent:addChild(secondLabel,0) -- return firstLabel,secondLabel end ------------------------------------------ -------------------------- --µã»÷Ñ¡ÔñÏûºÄ¿¨Æ¬ function key_to_choiceCost() if currentInfo then sendAction(1444) else ZyToast.show(mScene, Language.HERO_PLEASECHOICE,1,0.35) end end; --------------------------- function refreshWin() sendAction(1441) end ----µã»÷Éý¼¶°´Å¥ÏìÓ¦ function LvUpAction() if mGeneralID then if currentInfo.Status==0 then sendAction(1442) elseif currentInfo.Status==1 then local box = ZyMessageBoxEx:new() box:doQuery(mScene, nil,Language.HERO_TISHI , Language.IDS_SURE, Language.IDS_CANCEL,isAction) end else ZyToast.show(mScene, Language.HERO_PLEASECHOICE,1,0.35) end end function isAction(clickedButtonIndex) if clickedButtonIndex == 1 then--È·ÈÏ sendAction(1442) end end; -------------------- --²¥·ÅÓ¶±øÉý¼¶¶¯»­ function playAnimation() local attribuAni=ScutAnimation.CScutAnimationManager:GetInstance():LoadSprite("donghua_1006") attribuAni:play() attribuAni:registerFrameCallback("HeroLvUp.finishAnimation") mLayer:addChild(attribuAni, 1) attribuAni:setPosition(PT(pWinSize.width*0.5, pWinSize.height*0.5)) end --¶¯»­²¥·ÅÍê³Éºó function finishAnimation(pSprite, curAniIndex, curFrameIndex, nPlayingFlag) if nPlayingFlag == 2 then pSprite:registerFrameCallback("") delayRemove(pSprite) end end function delayRemove(sprite) if sprite ~= nil then local delayAct = CCDelayTime:create(0.1) local funcName = CCCallFuncN:create(HeroLvUp.removeTmpSprite) local act = CCSequence:createWithTwoActions(delayAct,funcName) sprite:runAction(act) sprite = nil end end function removeTmpSprite(sprite) if sprite ~= nil then sprite:removeFromParentAndCleanup(true) sprite = nil end end -------------- --·¢ËÍÇëÇó function sendAction(actionId, data,num) if actionId == 1441 then actionLayer.Action1441(mScene, nil, mGeneralID) elseif actionId == 1401 then actionLayer.Action1401(mScene, nil, nil, 1) elseif actionId == 1442 then actionLayer.Action1442(mScene, nil, mGeneralID) elseif actionId == 1444 then actionLayer.Action1444(mScene, nil, 1, 200) elseif actionId == 1445 then actionLayer.Action1445(mScene, nil, data,mGeneralID,num) end end -- ÍøÂç»Øµ÷ function networkCallback(pScutScene, lpExternalData) local actionId = ZyReader:getActionID() local userData = ScutRequestParam:getParamData(lpExternalData) if actionId == 1441 then--1441_Ó¶±øÉý¼¶½çÃæ½Ó¿Ú£¨ID=1441£© local serverInfo = actionLayer._1441Callback(pScutScene, lpExternalData) if serverInfo then currentInfo = serverInfo if mCurrentLevel and mCurrentLevel < currentInfo.CurrLv then playAnimation() end mCurrentLevel = currentInfo.CurrLv showContent() end elseif actionId == 1401 then local serverInfo = actionLayer._1401Callback(pScutScene, lpExternalData) if serverInfo then heroListInfo = serverInfo local type = 1 HeroLvUpChoiceLayer.init(mScene, type) HeroLvUpChoiceLayer.showList(serverInfo.RecordTabel) end elseif actionId == 1442 then local serverInfo = actionLayer._1442Callback(pScutScene, lpExternalData) if serverInfo then refreshWin() end elseif actionId == 1444 then local serverInfo = actionLayer._1444Callback(pScutScene, lpExternalData) if serverInfo then local type = 2 HeroLvUpChoiceLayer.setCardTable(currentInfo.RecordTabel) HeroLvUpChoiceLayer.init(mScene, type) HeroLvUpChoiceLayer.showList(serverInfo.RecordTabel) end elseif actionId == 1445 then local serverInfo = actionLayer._1445Callback(pScutScene, lpExternalData) if serverInfo then refreshWin() end end commonCallback.networkCallback(pScutScene, lpExternalData) end
mit
nyczducky/darkstar
scripts/zones/The_Sanctuary_of_ZiTah/mobs/Myxomycete.lua
13
2044
----------------------------------- -- Area: The Sanctuary of Zi'Tah -- MOB: Myxomycete ----------------------------------- require("scripts/globals/fieldsofvalor"); require("scripts/globals/weather"); function onMobRoam(mob) local Noble_Mold = 17273278; local Noble_Mold_PH = 0; local Noble_Mold_PH_Table = { 17273276, 17273277 }; local Noble_Mold_ToD = GetMobByID(Noble_Mold):getLocalVar("ToD"); if (Noble_Mold_ToD <= os.time()) then Noble_Mold_PH = math.random((0), (#Noble_Mold_PH_Table)); if (Noble_Mold_PH_Table[Noble_Mold_PH] ~= nil) then if ( GetMobAction(Noble_Mold) == 0 and ( GetMobByID(Noble_Mold_PH_Table[Noble_Mold_PH]):getWeather() == WEATHER_RAIN or GetMobByID(Noble_Mold_PH_Table[Noble_Mold_PH]):getWeather() == WEATHER_SQUALL ) ) then SetServerVariable("Noble_Mold_PH", Noble_Mold_PH_Table[Noble_Mold_PH]); DeterMob(Noble_Mold_PH_Table[Noble_Mold_PH], true); DeterMob(Noble_Mold, false); DespawnMob(Noble_Mold_PH_Table[Noble_Mold_PH]); SpawnMob(Noble_Mold, "", 0); end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkRegime(player, mob, 115, 1); checkRegime(player, mob, 116, 2); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local Myxomycete = mob:getID(); local Noble_Mold = 17273278; local Noble_Mold_PH_Table = { 17273276, 17273277 }; for i = 1, #Noble_Mold_PH_Table, 1 do if (Noble_Mold_PH_Table[i] ~= nil) then if (Myxomycete == Noble_Mold_PH_Table[i]) then GetMobByID(Noble_Mold):setLocalVar("ToD",os.time() + math.random((43200), (57600))); end end end end;
gpl-3.0
liloman/awesome
rc/widgets.lua
1
15422
-- Widgets local wibox=require("wibox") local vicious=require("vicious") local vlayout = require("wibox.layout") local common = require("awful.widget.common") local icons = loadrc("icons", "vbe/icons") local pomodoro = loadrc("pomodoro") pomodoro.init() -- Separators local sepopen = wibox.widget.imagebox(beautiful.icons .. "/widgets/left.png") local sepclose = wibox.widget.imagebox(beautiful.icons .. "/widgets/right.png") local spacer = wibox.widget.imagebox(beautiful.icons .. "/widgets/spacer.png") -- Date local datewidget = wibox.widget.textbox() local dateformat = "%H:%M" if screen.count() > 1 then dateformat = "%a %d/%m, " .. dateformat end vicious.register(datewidget, vicious.widgets.date, '<span color="' .. beautiful.fg_widget_clock .. '">' .. dateformat .. '</span>', 61) local dateicon = wibox.widget.imagebox(beautiful.icons .. "/widgets/clock.png") local cal = ( function() local calendar = nil local offset = 0 local remove_calendar = function() if calendar ~= nil then naughty.destroy(calendar) calendar = nil offset = 0 end end local add_calendar = function(inc_offset) local save_offset = offset remove_calendar() offset = save_offset + inc_offset local datespec = os.date("*t") datespec = datespec.year * 12 + datespec.month - 1 + offset datespec = (datespec % 12 + 1) .. " " .. math.floor(datespec / 12) local cal = awful.util.pread("ncal -w -m " .. datespec) -- Highlight the current date and month cal = cal:gsub("_.([%d ])", string.format('<span color="%s">%%1</span>', beautiful.fg_widget_clock)) cal = cal:gsub("^( +[^ ]+ [0-9]+) *", string.format('<span color="%s">%%1</span>', beautiful.fg_widget_clock)) -- Turn anything other than days in labels cal = cal:gsub("(\n[^%d ]+)", string.format('<span color="%s">%%1</span>', beautiful.fg_widget_label)) cal = cal:gsub("([%d ]+)\n?$", string.format('<span color="%s">%%1</span>', beautiful.fg_widget_label)) calendar = naughty.notify( { text = string.format('<span font="%s">%s</span>', "Terminus 8", cal:gsub(" +\n","\n")), timeout = 0, hover_timeout = 0.5, width = 160, screen = mouse.screen, }) end return { add = add_calendar, rem = remove_calendar } end)() datewidget:connect_signal("mouse::enter", function() cal.add(0) end) datewidget:connect_signal("mouse::leave", cal.rem) datewidget:buttons(awful.util.table.join( awful.button({ }, 3, function() cal.add(-1) end), awful.button({ }, 1, function() cal.add(1) end))) -- CPU usage local cpuwidget = wibox.widget.textbox() vicious.register(cpuwidget, vicious.widgets.cpu, function (widget, args) return string.format('<span color="' .. beautiful.fg_widget_value .. '">%2d%%</span>',args[1]) end, 10) local cpuicon = wibox.widget.imagebox(beautiful.icons .. "/widgets/cpu.png") -- Battery local batwidget =wibox.widget --if config.hostname == "guybrush" then batwidget.widget = wibox.widget.textbox() vicious.register(batwidget.widget, vicious.widgets.bat, function (widget, args) local color = beautiful.fg_widget_value local current = args[2] if current < 10 and args[1] == "-" then color = beautiful.fg_widget_value_important -- Maybe we want to display a small warning? if current ~= batwidget.lastwarn then batwidget.lastid = naughty.notify( { title = "Battery low!", preset = naughty.config.presets.critical, timeout = 20, text = "Battery level is currently " .. current .. "%.\n" .. args[3] .. " left before running out of power.", icon = icons.lookup({name = "battery-caution", type = "status"}), replaces_id = batwidget.lastid }).id batwidget.lastwarn = current end end return string.format('<span color="' .. color .. '">%s%d%%</span>', args[1], current) end, 59, "BAT0") -- end local baticon = wibox.widget.imagebox(beautiful.icons .. "/widgets/bat.png") ------ Network local netup = wibox.widget.textbox() local netdown = wibox.widget.textbox() local netupicon = wibox.widget.imagebox(beautiful.icons .. "/widgets/up.png") local netdownicon = wibox.widget.imagebox(beautiful.icons .. "/widgets/down.png") --local netgraph = awful.widget.graph() --netgraph:set_width(80):set_height(16) --netgraph:set_stack(true):set_scale(true) --netgraph:set_border_color(beautiful.fg_widget_border) --netgraph:set_stack_colors({ "#EF8171", "#cfefb3" }) --netgraph:set_background_color("#00000033") vicious.register(netup, vicious.widgets.net, function (widget, args) -- We sum up/down value for all interfaces local up = 0 local down = 0 local iface for name, value in pairs(args) do iface = name:match("^{(%S+) down_b}$") if iface and iface ~= "lo" then down = down + value end iface = name:match("^{(%S+) up_b}$") if iface and iface ~= "lo" then up = up + value end end -- Update the graph --netgraph:add_value(up, 1) --netgraph:add_value(down, 2) -- Format the string representation local format = function(val) if val > 500000 then return string.format("%.1f MB", val/1000000.) elseif val > 500 then return string.format("%.1f KB", val/1000.) else return string.format("%d B", val) end end -- Down netdown.text = string.format('<span color="' .. beautiful.fg_widget_value .. '">%08s</span>', format(down)) -- Up return string.format('<span color="' .. beautiful.fg_widget_value .. '">%08s</span>', format(up)) end, 3) vicious.register(netdown, vicious.widgets.net,netdown.text,3) ---- Memory usage local memwidget = wibox.widget.textbox() vicious.register(memwidget, vicious.widgets.mem, '<span color="' .. beautiful.fg_widget_value .. '">$1</span>', 19) local memicon = wibox.widget.imagebox(beautiful.icons .. "/widgets/mem.png") ---- Volume level local volwidget = wibox.widget.textbox() vicious.register(volwidget, vicious.widgets.volume, '<span color="' .. beautiful.fg_widget_value .. '">$2 $1</span>',17,"Master") local volicon=wibox.widget.imagebox(beautiful.icons .. "/widgets/vol.png") volume = loadrc("volume", "vbe/volume") volwidget:buttons(awful.util.table.join( awful.button({ }, 1, volume.mixer), awful.button({ }, 3, volume.toggle), awful.button({ }, 4, volume.increase), awful.button({ }, 5, volume.decrease))) ----Mocp client ----mocpwidget = widget({ type = "textbox" }) ------ Register widget ----vicious.register(mocpwidget, vicious.widgets.mocp, ----function (widget, args) ---- if args["{state}"] == "Stop" then ---- return " - " ---- else ---- return args["{Artist}"]..' - '.. args["{Title}"] ---- end ----end, 10) -- -- ---- File systems --local fs = { ["/"] = "root", -- ["/home"] = "home", -- ["/var"] = "var", -- ["/usr"] = "usr", -- ["/tmp"] = "tmp", -- ["/var/cache/build"] = "pbuilder" } ----local fsicon = widget({ type = "imagebox" }) --local fsicon = wibox.widget.imagebox() --fsicon.image = wibox.widget.imagebox(beautiful.icons .. "/widgets/disk.png") ----local fswidget = widget({ type = "textbox" }) --local fsiwidget = wibox.widget.textbox() --vicious.register(fswidget, vicious.widgets.fs, -- function (widget, args) -- local result = "" -- for path, name in pairs(fs) do -- local used = args["{" .. path .. " used_p}"] -- local color = beautiful.fg_widget_value -- if used then -- if used > 90 then -- color = beautiful.fg_widget_value_important -- end -- result = string.format( -- '%s%s<span color="' .. beautiful.fg_widget_label .. '">%s: </span>' .. -- '<span color="' .. color .. '">%2d%%</span>', -- result, #result > 0 and " " or "", name, used) -- end -- end -- return result -- end, 53) local systray = wibox.widget.systray() -- -- Wibox initialisation mywibox = {} local promptbox = {} local layoutbox = {} local taglist = {} for s = 1, screen.count() do promptbox[s] = awful.widget.prompt() layoutbox[s] = awful.widget.layoutbox(s) --Creamos los botones taglist.buttons = awful.util.table.join( awful.button({ }, 1, awful.tag.viewonly), awful.button({ modkey }, 1, awful.client.movetotag), awful.button({ }, 3, awful.tag.viewtoggle), awful.button({ modkey }, 3, awful.client.toggletag) ) -- Create the taglist taglist[s] = awful.widget.taglist(s, awful.widget.taglist.filter.all,taglist.buttons,'', -- -- Copia awful.widget.common.list_update para modificar el aspecto de la taglist function (w, buttons, label, data, objects) -- update the widgets, creating them if needed w:reset() for i, o in ipairs(objects) do local cache = data[o] local ib, tb, bgb, m, l if cache then ib = cache.ib tb = cache.tb bgb = cache.bgb m = cache.m else ib = wibox.widget.imagebox() tb = wibox.widget.textbox() --tb:set_text(i) bgb = wibox.widget.background() m = wibox.layout.margin(tb, 4, 4) l=wibox.layout.fixed.horizontal() l:fill_space(true) l:add(ib) l:add(m) -- And all of this gets a background bgb:set_widget(l) bgb:buttons(common.create_buttons(buttons, o)) data[o] = { ib = ib, tb = tb, bgb = bgb, m = m } end local text, bg, bg_image, icon = label(o) for i,vtag in ipairs(awful.tag.gettags(mouse.screen)) do --Localizamos espartanamente las tags... if string.find(tostring(text),vtag.name) then local position=awful.tag.getproperty(vtag,"position") if not position then text=" "..text.."*" else text=" "..text .. "<sup><small>"..position .."</small></sup>" end end end -- The text might be invalid, so use pcall if not pcall(tb.set_markup, tb, text) then tb:set_markup("<i>&lt;Invalid text&gt;</i>") end bgb:set_bg(bg) if type(bg_image) == "function" then bg_image = bg_image(tb,o,m,objects,i) end bgb:set_bgimage(bg_image) ib:set_image(icon) w:add(bgb) end end) -- /taglist -- Create the mywibox mywibox[s] = awful.wibox({ screen = s, fg = beautiful.fg_normal, bg = beautiful.bg_widget, position = "top", height = 16, }) -- Add widgets to the mywibox local on = function(n, what) if s == n or n > screen.count() then return what end return "" end -- Widgets that are aligned to the left --Los de la izquierda local izquierdo=vlayout.fixed.horizontal() izquierdo:add(taglist[s]) izquierdo:add(promptbox[s]) local derecho=vlayout.fixed.horizontal() derecho:add(layoutbox[s]) derecho:add(sepopen) derecho:add(cpuicon) derecho:add(cpuwidget) derecho:add(spacer) --derecho:add(volicon) derecho:add(memicon) derecho:add(memwidget) derecho:add(spacer) derecho:add(volwidget) derecho:add(spacer) --derecho:add(baticon) --derecho:add(batwidget) --derecho:add(spacer) derecho:add(netdown) derecho:add(netdownicon) derecho:add(netup) derecho:add(netupicon) --derecho:add(netgraph) derecho:add(spacer) derecho:add(dateicon) derecho:add(datewidget) derecho:add(sepclose) derecho:add(sepopen) derecho:add(systray) derecho:add(pomodoro.icon_widget) derecho:add(pomodoro.widget) derecho:add(sepclose) --Los ponemos a la derecha ahora local capa = vlayout.align.horizontal() capa:set_left(izquierdo) capa:set_right(derecho) mywibox[s]:set_widget(capa) -- Second mywibox para anadir el tasklist abajo mywibox[2] = awful.wibox({screen = s, fg = beautiful.fg_normal, bg = beautiful.bg_widget, position = "bottom", height = 16}) ------------ preparamos los tasklist local tasklist = {} tasklist.buttons = awful.util.table.join( awful.button({ }, 1, function (c) if c == client.focus then c.minimized = true else if not c:isvisible() then awful.tag.viewonly(c:tags()[1]) end -- This will also un-minimize -- the client, if needed client.focus = c c:raise() end end)) for s = 1, screen.count() do tasklist[s] = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, tasklist.buttons,'', -- -- Copia awful.widget.common.list_update para modificar el aspecto de la tasklist function (w, buttons, label, data, objects) -- update the widgets, creating them if needed w:reset() numClientes={} local swibox=mywibox[2] local min=beautiful.tasklist_max_width swibox.width=10 for i, o in ipairs(objects) do --Que las tasklist tengan um maximo de width para que no ocupe una sola toda el layout if screen[s].geometry.width>=swibox.width+min then swibox.width=swibox.width+min elseif screen[s].geometry.width~=swibox.width then awful.wibox.stretch(swibox,s) end local cache = data[o] local ib, tb, bgb, m, l if cache then ib = cache.ib tb = cache.tb bgb = cache.bgb m = cache.m else ib = wibox.widget.imagebox() tb = wibox.widget.textbox() tb:set_text(i) bgb = wibox.widget.background() m = wibox.layout.margin(tb, 4, 4) l=wibox.layout.fixed.horizontal() l:fill_space(true) l:add(ib) l:add(m) -- And all of this gets a background bgb:set_widget(l) bgb:buttons(common.create_buttons(buttons, o)) data[o] = { ib = ib, tb = tb, bgb = bgb, m = m } end local text, bg, bg_image, icon = label(o) text=i .." "..text numClientes[i]=o -- The text might be invalid, so use pcall if not pcall(tb.set_markup, tb, text) then tb:set_markup("<i>&lt;Invalid text&gt;</i>") end bgb:set_bg(bg) if type(bg_image) == "function" then bg_image = bg_image(tb,o,m,objects,i) end bgb:set_bgimage(bg_image) ib:set_image(icon) w:add(bgb) end end) end ------------------- FIN de tasklist mywibox[2]:set_widget(tasklist[s]) end config.keys.global = awful.util.table.join( config.keys.global, awful.key({ modkey }, "r", function () promptbox[mouse.screen]:run() end, "Prompt for a command")) config.taglist = taglist
gpl-2.0
nyczducky/darkstar
scripts/zones/Upper_Jeuno/npcs/_6s2.lua
14
4089
----------------------------------- -- Area: Upper Jeuno -- NPC: Galmut's door -- Starts and Finishes Quest: A Clock Most Delicate, Save the Clock Tower, The Clockmaster -- @zone 244 -- @pos -80 0 104 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) aClockMostdelicate = player:getQuestStatus(JEUNO,A_CLOCK_MOST_DELICATE); if (aClockMostdelicate == QUEST_AVAILABLE and player:getVar("aClockMostdelicateVar") == 1) then player:startEvent(0x0077); -- Start long cs quest with option "a clock most delicate" elseif (aClockMostdelicate == QUEST_AVAILABLE and player:getVar("aClockMostdelicateVar") == 2) then player:startEvent(0x0076); -- Start short cs quest with option "a clock most delicate" elseif (aClockMostdelicate == QUEST_ACCEPTED) then if (player:hasKeyItem(CLOCK_TOWER_OIL) == true) then player:startEvent(0x00ca); -- Ending quest "a clock most delicate" else player:startEvent(0x0075); -- During quest "a clock most delicate" end elseif (player:getQuestStatus(JEUNO,SAVE_THE_CLOCK_TOWER) == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_CLOCKMASTER) == QUEST_AVAILABLE) then player:startEvent(0x0098); -- Start & finish quest "The Clockmaster" elseif (player:getQuestStatus(JEUNO,THE_CLOCKMASTER) == QUEST_COMPLETED) then player:startEvent(0x006e); -- After quest "The Clockmaster" else player:startEvent(0x0074); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0077 and option == 1) then player:addQuest(JEUNO,A_CLOCK_MOST_DELICATE); player:setVar("aClockMostdelicateVar",0); elseif (csid == 0x0077 and option == 0) then player:setVar("aClockMostdelicateVar",2); elseif (csid == 0x0076 and option == 1) then player:addQuest(JEUNO,A_CLOCK_MOST_DELICATE); player:setVar("aClockMostdelicateVar",0); elseif (csid == 0x00ca) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12727); else player:addTitle(PROFESSIONAL_LOAFER); player:delKeyItem(CLOCK_TOWER_OIL); player:addGil(1200); player:messageSpecial(GIL_OBTAINED,1200); player:addItem(12727); player:messageSpecial(ITEM_OBTAINED,12727); player:addFame(JEUNO,30); player:completeQuest(JEUNO,A_CLOCK_MOST_DELICATE); player:addQuest(JEUNO,SAVE_THE_CLOCK_TOWER); -- Start next quest "Save the Clock Tower" end elseif (csid == 0x0098) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17083); else player:addQuest(JEUNO,THE_CLOCKMASTER); player:addTitle(TIMEKEEPER); player:addGil(1200); player:messageSpecial(GIL_OBTAINED,1200); player:addItem(17083); player:messageSpecial(ITEM_OBTAINED,17083); player:addFame(JEUNO,30); player:completeQuest(JEUNO,THE_CLOCKMASTER); end end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Abyssea-Misareaux/npcs/qm11.lua
14
1348
----------------------------------- -- Zone: Abyssea-Misareaux -- NPC: qm11 (???) -- Spawns Tuskertrap -- @pos ? ? ? 216 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3096,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17662474) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17662474):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3096); -- Inform player what items they need. 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
nyczducky/darkstar
scripts/globals/weaponskills/burning_blade.lua
23
1317
----------------------------------- -- Burning Blade -- Sword weapon skill -- Skill Level: 30 -- Desription: Deals Fire elemental damage to enemy. Damage varies with TP. -- Aligned with the Flame Gorget. -- Aligned with the Flame Belt. -- Element: Fire -- Modifiers: STR:20% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 2.00 2.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_FIRE; params.skill = SKILL_SWD; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp200 = 2.1; params.ftp300 = 3.4; params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nyczducky/darkstar
scripts/zones/Riverne-Site_B01/bcnms/storms_of_fate.lua
29
2594
----------------------------------- -- Area: Riverne Site #B01 -- Name: Storms of Fate -- @pos 299 -123 345 146 ----------------------------------- package.loaded["scripts/zones/Riverne-Site_B01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Riverne-Site_B01/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/status"); require("scripts/globals/bcnm"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:delStatusEffect(EFFECT_LEVEL_RESTRICTION); -- can't be capped at 50 for this fight ! end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_COMPLETED) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end if (ENABLE_COP_ZONE_CAP == 1) then -- restore level cap on exit if the setting is enabled player:addStatusEffect(EFFECT_LEVEL_RESTRICTION, 50, 0, 0); end; end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if (player:getQuestStatus(JEUNO,STORMS_OF_FATE) == QUEST_ACCEPTED and player:getVar('StormsOfFate') == 2) then player:addKeyItem(WHISPER_OF_THE_WYRMKING); player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_THE_WYRMKING); player:setVar('StormsOfFate',3); player:addTitle(CONQUEROR_OF_FATE); if (ENABLE_COP_ZONE_CAP == 1) then -- restore level cap on exit if the setting is enabled player:addStatusEffect(EFFECT_LEVEL_RESTRICTION, 50, 0, 0); end; end end end;
gpl-3.0
sjznxd/lc-20121231
applications/luci-tinyproxy/luasrc/model/cbi/tinyproxy.lua
80
7364
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008-2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("tinyproxy", translate("Tinyproxy"), translate("Tinyproxy is a small and fast non-caching HTTP(S)-Proxy")) s = m:section(TypedSection, "tinyproxy", translate("Server Settings")) s.anonymous = true s:tab("general", translate("General settings")) s:tab("privacy", translate("Privacy settings")) s:tab("filter", translate("Filtering and ACLs")) s:tab("limits", translate("Server limits")) o = s:taboption("general", Flag, "enabled", translate("Enable Tinyproxy server")) o.rmempty = false function o.write(self, section, value) if value == "1" then luci.sys.init.enable("tinyproxy") else luci.sys.init.disable("tinyproxy") end return Flag.write(self, section, value) end o = s:taboption("general", Value, "Port", translate("Listen port"), translate("Specifies the HTTP port Tinyproxy is listening on for requests")) o.optional = true o.datatype = "port" o.placeholder = 8888 o = s:taboption("general", Value, "Listen", translate("Listen address"), translate("Specifies the addresses Tinyproxy is listening on for requests")) o.optional = true o.datatype = "ipaddr" o.placeholder = "0.0.0.0" o = s:taboption("general", Value, "Bind", translate("Bind address"), translate("Specifies the address Tinyproxy binds to for outbound forwarded requests")) o.optional = true o.datatype = "ipaddr" o.placeholder = "0.0.0.0" o = s:taboption("general", Value, "DefaultErrorFile", translate("Error page"), translate("HTML template file to serve when HTTP errors occur")) o.optional = true o.default = "/usr/share/tinyproxy/default.html" o = s:taboption("general", Value, "StatFile", translate("Statistics page"), translate("HTML template file to serve for stat host requests")) o.optional = true o.default = "/usr/share/tinyproxy/stats.html" o = s:taboption("general", Flag, "Syslog", translate("Use syslog"), translate("Writes log messages to syslog instead of a log file")) o = s:taboption("general", Value, "LogFile", translate("Log file"), translate("Log file to use for dumping messages")) o.default = "/var/log/tinyproxy.log" o:depends("Syslog", "") o = s:taboption("general", ListValue, "LogLevel", translate("Log level"), translate("Logging verbosity of the Tinyproxy process")) o:value("Critical") o:value("Error") o:value("Warning") o:value("Notice") o:value("Connect") o:value("Info") o = s:taboption("general", Value, "User", translate("User"), translate("Specifies the user name the Tinyproxy process is running as")) o.default = "nobody" o = s:taboption("general", Value, "Group", translate("Group"), translate("Specifies the group name the Tinyproxy process is running as")) o.default = "nogroup" -- -- Privacy -- o = s:taboption("privacy", Flag, "XTinyproxy", translate("X-Tinyproxy header"), translate("Adds an \"X-Tinyproxy\" HTTP header with the client IP address to forwarded requests")) o = s:taboption("privacy", Value, "ViaProxyName", translate("Via hostname"), translate("Specifies the Tinyproxy hostname to use in the Via HTTP header")) o.placeholder = "tinyproxy" o.datatype = "hostname" s:taboption("privacy", DynamicList, "Anonymous", translate("Header whitelist"), translate("Specifies HTTP header names which are allowed to pass-through, all others are discarded. Leave empty to disable header filtering")) -- -- Filter -- o = s:taboption("filter", DynamicList, "Allow", translate("Allowed clients"), translate("List of IP addresses or ranges which are allowed to use the proxy server")) o.placeholder = "0.0.0.0" o.datatype = "ipaddr" o = s:taboption("filter", DynamicList, "ConnectPort", translate("Allowed connect ports"), translate("List of allowed ports for the CONNECT method. A single value \"0\" allows all ports")) o.placeholder = 0 o.datatype = "port" s:taboption("filter", FileUpload, "Filter", translate("Filter file"), translate("Plaintext file with URLs or domains to filter. One entry per line")) s:taboption("filter", Flag, "FilterURLs", translate("Filter by URLs"), translate("By default, filtering is done based on domain names. Enable this to match against URLs instead")) s:taboption("filter", Flag, "FilterExtended", translate("Filter by RegExp"), translate("By default, basic POSIX expressions are used for filtering. Enable this to activate extended regular expressions")) s:taboption("filter", Flag, "FilterCaseSensitive", translate("Filter case-sensitive"), translate("By default, filter strings are treated as case-insensitive. Enable this to make the matching case-sensitive")) s:taboption("filter", Flag, "FilterDefaultDeny", translate("Default deny"), translate("By default, the filter rules act as blacklist. Enable this option to only allow matched URLs or domain names")) -- -- Limits -- o = s:taboption("limits", Value, "Timeout", translate("Connection timeout"), translate("Maximum number of seconds an inactive connection is held open")) o.optional = true o.datatype = "uinteger" o.default = 600 o = s:taboption("limits", Value, "MaxClients", translate("Max. clients"), translate("Maximum allowed number of concurrently connected clients")) o.datatype = "uinteger" o.default = 10 o = s:taboption("limits", Value, "MinSpareServers", translate("Min. spare servers"), translate("Minimum number of prepared idle processes")) o.datatype = "uinteger" o.default = 5 o = s:taboption("limits", Value, "MaxSpareServers", translate("Max. spare servers"), translate("Maximum number of prepared idle processes")) o.datatype = "uinteger" o.default = 10 o = s:taboption("limits", Value, "StartServers", translate("Start spare servers"), translate("Number of idle processes to start when launching Tinyproxy")) o.datatype = "uinteger" o.default = 5 o = s:taboption("limits", Value, "MaxRequestsPerChild", translate("Max. requests per server"), translate("Maximum allowed number of requests per process. If it is exeeded, the process is restarted. Zero means unlimited.")) o.datatype = "uinteger" o.default = 0 -- -- Upstream -- s = m:section(TypedSection, "upstream", translate("Upstream Proxies"), translate("Upstream proxy rules define proxy servers to use when accessing certain IP addresses or domains.")) s.anonymous = true s.addremove = true t = s:option(ListValue, "type", translate("Policy"), translate("<em>Via proxy</em> routes requests to the given target via the specifed upstream proxy, <em>Reject access</em> disables any upstream proxy for the target")) t:value("proxy", translate("Via proxy")) t:value("reject", translate("Reject access")) ta = s:option(Value, "target", translate("Target host"), translate("Can be either an IP address or range, a domain name or \".\" for any host without domain")) ta.rmempty = true ta.placeholder = "0.0.0.0/0" ta.datatype = "host" v = s:option(Value, "via", translate("Via proxy"), translate("Specifies the upstream proxy to use for accessing the target host. Format is <code>address:port</code>")) v:depends({type="proxy"}) v.placeholder = "10.0.0.1:8080" return m
apache-2.0
nyczducky/darkstar
scripts/zones/The_Boyahda_Tree/mobs/Voluptuous_Vivian.lua
14
1126
----------------------------------- -- Area: The Boyahda Tree -- NM: Voluptuous Vivian (NM) ----------------------------------- require("scripts/zones/The_Boyahda_Tree/MobIDs"); require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_MAIN_2HOUR, 1); mob:setMobMod(MOBMOD_DRAW_IN, 2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(THE_VIVISECTOR); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- Set VV's ToD SetServerVariable("[POP]Voluptuous_Vivian", os.time(t) + math.random(57600,86400)); -- 16-24 hours DeterMob(mob:getID(), true); -- Set PH back to normal, then set to respawn spawn local PH = GetServerVariable("[PH]Voluptuous_Vivian"); SetServerVariable("[PH]Voluptuous_Vivian", 0); DeterMob(PH, false); GetMobByID(PH):setRespawnTime(GetMobRespawnTime(PH)); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Abyssea-La_Theine/npcs/qm18.lua
14
1844
----------------------------------- -- Zone: Abyssea-LaTheine -- NPC: qm18 (???) -- Spawns Hadhayosh -- @pos ? ? ? 132 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(17318448) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(MARBLED_MUTTON_CHOP) and player:hasKeyItem(BLOODIED_SABER_TOOTH) and player:hasKeyItem(BLOOD_SMEARED_GIGAS_HELM) and player:hasKeyItem(GLITTERING_PIXIE_CHOKER)) then player:startEvent(1020, MARBLED_MUTTON_CHOP, BLOODIED_SABER_TOOTH, GLITTERING_PIXIE_CHOKER, BLOOD_SMEARED_GIGAS_HELM); -- Ask if player wants to use KIs else player:startEvent(1021, MARBLED_MUTTON_CHOP, BLOODIED_SABER_TOOTH, GLITTERING_PIXIE_CHOKER, BLOOD_SMEARED_GIGAS_HELM); -- Do not ask, because player is missing at least 1. end end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1020 and option == 1) then SpawnMob(17318448):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(MARBLED_MUTTON_CHOP); player:delKeyItem(BLOODIED_SABER_TOOTH); player:delKeyItem(GLITTERING_PIXIE_CHOKER); player:delKeyItem(BLOOD_SMEARED_GIGAS_HELM); end end;
gpl-3.0
yiliaofan/sha2
test_sha2.lua
9
1259
require 'luarocks.require' require 'sha2' require 'lfs' print(sha2._VERSION) sha = { SHA256 = sha2.sha256, SHA384 = sha2.sha384, SHA512 = sha2.sha512, } shahex = { SHA256 = sha2.sha256hex, SHA384 = sha2.sha384hex, SHA512 = sha2.sha512hex, } local function bintohex(s) return (s:gsub('(.)', function(c) return string.format('%02x', string.byte(c)) end)) end for file in lfs.dir('testvectors') do local name, ext = file:match('^(.-)%.(.*)$') if ext == 'dat' then local s do local f = assert(io.open('testvectors/'..file, 'rb')) s = f:read('*a') f:close() end local hashes = {} do local f = assert(io.open('testvectors/'..name..'.info')) do local name, hash for line in f:lines() do if line:find'^SHA' then name = line:match'^(SHA.?.?.?)' hash = '' elseif hash then if #line == 0 then hashes[name] = hash hash = nil elseif hash then hash = hash .. line:match'^%s*(.-)%s*$' end end end end f:close() end for k,v in pairs(hashes) do local h = bintohex(sha[k](s)) print(file, k, #s, h == v and 'ok' or h .. ' ~= ' .. v) local h = shahex[k](s) print(file, k..'x', #s, h == v and 'ok' or h .. ' ~= ' .. v) end end end
mit
Goodzilam/Goodzila-bot_v1.3
plugins/inv.lua
46
1079
do local function callbackres(extra, success, result) local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then send_large_msg(chat, 'User is banned.') elseif is_gbanned(result.id) then send_large_msg(chat, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end if not is_admin(msg) then return 'Only admins can invite.' end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^[!/$&#@]invite (.*)$", "^([Ii]nvite (.*)$" }, run = run } end
gpl-2.0
nyczducky/darkstar
scripts/zones/Toraimarai_Canal/npcs/Transporter.lua
14
1296
----------------------------------- -- Area: Toraimarai Canal -- NPC: Transporter -- Involved In Windurst Mission 7-1 -- @zone 169 -- @pos 182 11 -60 169 ----------------------------------- package.loaded["scripts/zones/Toraimarai_Canal/TextIDs"] = nil; require("scripts/zones/Toraimarai_Canal/TextIDs"); ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0047); 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 == 0x0047 and option == 1) then player:setPos(0,0,-22,192,242); end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Mount_Zhayolm/npcs/qm1.lua
30
1334
----------------------------------- -- Area: Mount Zhayolm -- NPC: ??? (Spawn Brass Borer(ZNM T1)) -- @pos 399 -27 120 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 = 17027471; if (trade:hasItemQty(2590,1) and trade:getItemCount() == 1) then -- Trade Shadeleaves 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
nyczducky/darkstar
scripts/zones/Lower_Jeuno/npcs/Ruslan.lua
14
2119
----------------------------------- -- Area: Lower Jeuno -- NPC: Ruslan -- Involved In Quest: Wondering Minstrel -- Working 100% -- @zone = 245 -- @pos = -19 -1 -58 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL); if (wonderingstatus == QUEST_ACCEPTED) then prog = player:getVar("QuestWonderingMin_var") if (prog == 0) then -- WONDERING_MINSTREL + Rosewood Lumber: During Quest / Progression player:startEvent(0x2719,0,718); player:setVar("QuestWonderingMin_var",1); elseif (prog == 1) then -- WONDERING_MINSTREL + Rosewood Lumber: Quest Objective Reminder player:startEvent(0x271a,0,718); end elseif (wonderingstatus == QUEST_COMPLETED) then rand = math.random(3); if (rand == 1) then player:startEvent(0x271b); -- WONDERING_MINSTREL: After Quest else player:startEvent(0x2718); -- Standard Conversation end else player:startEvent(0x2718); -- Standard Conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Yhoator_Jungle/npcs/Telepoint.lua
17
1694
----------------------------------- -- Area: Yhoator Jungle -- NPC: Telepoint ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Yhoator_Jungle/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local item = trade:getItemId(); if (trade:getItemCount() == 1 and item > 4095 and item < 4104) then if (player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then player:tradeComplete(); player:addItem(613); player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(YHOATOR_GATE_CRYSTAL) == false) then player:addKeyItem(YHOATOR_GATE_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,YHOATOR_GATE_CRYSTAL); else player:messageSpecial(ALREADY_OBTAINED_TELE); 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
nyczducky/darkstar
scripts/globals/weaponskills/shijin_spiral.lua
22
1836
----------------------------------- -- Shijin Spiral -- Hand-to-Hand weapon skill -- Skill Level: N/A -- Delivers a fivefold attack that Plagues the target. Chance of inflicting Plague varies with TP. -- In order to obtain Shijin Spiral, the quest Martial Mastery must be completed. -- Aligned with the Flame Gorget, Light Gorget & Aqua Gorget. -- Aligned with the Flame Belt, Light Belt & Aqua Belt. -- Element: None -- Modifiers: DEX: 73~85% -- 100%TP 200%TP 300%TP -- 1.0625 1.0625 1.0625 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 5; params.ftp100 = 1.0625; params.ftp200 = 1.0625; params.ftp300 = 1.0625; params.str_wsc = 0.0; params.dex_wsc = 0.85 + (player:getMerit(MERIT_SHIJIN_SPIRAL) / 100); params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1.05; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.7 + (player:getMerit(MERIT_SHIJIN_SPIRAL) / 100); end if (damage > 0) then local duration = (tp/1000) + 4; if (target:hasStatusEffect(EFFECT_PLAGUE) == false) then target:addStatusEffect(EFFECT_PLAGUE, 5, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nyczducky/darkstar
scripts/zones/Rabao/npcs/Agado-Pugado.lua
14
5701
----------------------------------- -- Area: Rabao -- NPC: Agado-Pugado -- Starts and Finishes Quest: Trial by Wind -- @pos -17 7 -10 247 ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TrialByWind = player:getQuestStatus(OUTLANDS,TRIAL_BY_WIND); local WhisperOfGales = player:hasKeyItem(323); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local CarbuncleDebacle = player:getQuestStatus(WINDURST,CARBUNCLE_DEBACLE); local CarbuncleDebacleProgress = player:getVar("CarbuncleDebacleProgress"); --------------------------------------------------------------------- -- Carbuncle Debacle if (CarbuncleDebacle == QUEST_ACCEPTED and CarbuncleDebacleProgress == 5 and player:hasKeyItem(DAZEBREAKER_CHARM) == true) then player:startEvent(0x0056); -- get the wind pendulum, lets go to Cloister of Gales elseif (CarbuncleDebacle == QUEST_ACCEPTED and CarbuncleDebacleProgress == 6) then if (player:hasItem(1174) == false) then player:startEvent(0x0057,0,1174,0,0,0,0,0,0); -- "lost the pendulum?" This one too~??? else player:startEvent(0x0058); -- reminder to go to Cloister of Gales end; --------------------------------------------------------------------- -- Trial by Wind elseif ((TrialByWind == QUEST_AVAILABLE and player:getFameLevel(RABAO) >= 5) or (TrialByWind == QUEST_COMPLETED and realday ~= player:getVar("TrialByWind_date"))) then player:startEvent(0x0042,0,331); -- Start and restart quest "Trial by Wind" elseif (TrialByWind == QUEST_ACCEPTED and player:hasKeyItem(331) == false and WhisperOfGales == false) then player:startEvent(0x006b,0,331); -- Defeat against Avatar : Need new Fork elseif (TrialByWind == QUEST_ACCEPTED and WhisperOfGales == false) then player:startEvent(0x0043,0,331,3); elseif (TrialByWind == QUEST_ACCEPTED and WhisperOfGales) then numitem = 0; if (player:hasItem(17627)) then numitem = numitem + 1; end -- Garuda's Dagger if (player:hasItem(13243)) then numitem = numitem + 2; end -- Wind Belt if (player:hasItem(13562)) then numitem = numitem + 4; end -- Wind Ring if (player:hasItem(1202)) then numitem = numitem + 8; end -- Bubbly Water if (player:hasSpell(301)) then numitem = numitem + 32; end -- Ability to summon Garuda player:startEvent(0x0045,0,331,3,0,numitem); else player:startEvent(0x0046); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0042 and option == 1) then if (player:getQuestStatus(OUTLANDS,TRIAL_BY_WIND) == QUEST_COMPLETED) then player:delQuest(OUTLANDS,TRIAL_BY_WIND); end player:addQuest(OUTLANDS,TRIAL_BY_WIND); player:setVar("TrialByWind_date", 0); player:addKeyItem(TUNING_FORK_OF_WIND); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_WIND); elseif (csid == 0x006b) then player:addKeyItem(TUNING_FORK_OF_WIND); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_WIND); elseif (csid == 0x0045) then item = 0; if (option == 1) then item = 17627; -- Garuda's Dagger elseif (option == 2) then item = 13243; -- Wind Belt elseif (option == 3) then item = 13562; -- Wind Ring elseif (option == 4) then item = 1202; -- Bubbly Water end if (player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); else if (option == 5) then player:addGil(GIL_RATE*10000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil elseif (option == 6) then player:addSpell(301); -- Garuda Spell player:messageSpecial(GARUDA_UNLOCKED,0,0,3); else player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); -- Item end player:addTitle(HEIR_OF_THE_GREAT_WIND); player:delKeyItem(WHISPER_OF_GALES); --Whisper of Gales, as a trade for the above rewards player:setVar("TrialByWind_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(RABAO,30); player:completeQuest(OUTLANDS,TRIAL_BY_WIND); end elseif (csid == 0x0056 or csid == 0x0057) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(1174); player:messageSpecial(ITEM_OBTAINED,1174); player:setVar("CarbuncleDebacleProgress",6); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1174); end; end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/AlTaieu/mobs/Aw_euvhi.lua
21
1552
----------------------------------- -- Area: AlTaieu -- MOB: Aw_euvhi ----------------------------------- package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil; ----------------------------------- require("scripts/zones/AlTaieu/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local mobID = mob:getID(); -- This should have just been 3 mob names with 3 scripts because ID shifts (and sanity).. if (mobID == 16912823 or mobID == 16912825 or mobID == 16912827) then if (player:hasKeyItem(BLACK_CARD) == false) then player:addKeyItem(BLACK_CARD); player:messageSpecial(KEYITEM_OBTAINED,BLACK_CARD); end elseif (mobID == 16912811 or mobID == 16912813 or mobID == 16912815) then if (player:hasKeyItem(WHITE_CARD) == false) then player:addKeyItem(WHITE_CARD); player:messageSpecial(KEYITEM_OBTAINED,WHITE_CARD); end elseif (mobID == 16912817 or mobID == 16912821 or mobID == 16912819) then if (player:hasKeyItem(RED_CARD) == false) then player:addKeyItem(RED_CARD); player:messageSpecial(KEYITEM_OBTAINED,RED_CARD); end end end;
gpl-3.0
LexLoki/Udemy-LOVE_game_development
Snake/main.lua
1
1618
local snake = require 'snake' require 'audio' local cell_size = 32 local grid_size = {x=15,y=15} local world_size = {width = cell_size*grid_size.x,height = cell_size*grid_size.y} local origin local checkCollision local gameIsOver function love.load() love.graphics.setNewFont(14) audio.load() snake.load(cell_size) origin = {x=0,y=0} love.window.setMode(world_size.width,world_size.height) gameIsOver = false end function love.update(dt) if not gameIsOver then if not snake.update(dt) or checkCollision() then gameIsOver = true end end end function love.keypressed(key) if gameIsOver then if key=='return' then snake.load(cell_size) gameIsOver = false end else snake.keypressed(key) end end function love.draw() local w,h = love.graphics.getDimensions() love.graphics.setColor(255,255,255) love.graphics.rectangle('fill',0,0,w,h) love.graphics.setColor(0,0,0) love.graphics.rectangle('fill',origin.x,origin.y,world_size.width,world_size.height) love.graphics.setColor(255,0,0) love.graphics.rectangle('line',origin.x,origin.y,world_size.width,world_size.height) snake.draw(origin) love.graphics.print('Score: '..snake.score,10,10) if gameIsOver then love.graphics.setColor(0,0,0,160) love.graphics.rectangle('fill',0,0,w,h) love.graphics.setColor(255,255,255) love.graphics.setNewFont(40) love.graphics.printf('Game over!\nYour score: '..snake.score,0,h/4,w,'center') love.graphics.setNewFont(14) end end function checkCollision() local p = snake.headPos() if p.x<0 or p.y<0 or p.x>=grid_size.x or p.y>=grid_size.y then return true end return false end
mit
mehrpouya81/giantbot
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
dtrip/awesome
lib/wibox/widget/piechart.lua
2
7300
--------------------------------------------------------------------------- -- Display percentage in a circle. -- -- Note that this widget makes no attempts to prevent overlapping labels or -- labels drawn outside of the widget boundaries. -- --@DOC_wibox_widget_defaults_piechart_EXAMPLE@ -- @author Emmanuel Lepage Valle -- @copyright 2012 Emmanuel Lepage Vallee -- @widgetmod wibox.widget.piechart --------------------------------------------------------------------------- local color = require( "gears.color" ) local base = require( "wibox.widget.base" ) local beautiful = require( "beautiful" ) local gtable = require( "gears.table" ) local pie = require( "gears.shape" ).pie local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1) local module = {} local piechart = {} local function draw_label(cr,angle,radius,center_x,center_y,text) local edge_x = center_x+(radius/2)*math.cos(angle) local edge_y = center_y+(radius/2)*math.sin(angle) cr:move_to(edge_x, edge_y) cr:rel_line_to(radius*math.cos(angle), radius*math.sin(angle)) local x,y = cr:get_current_point() cr:rel_line_to(x > center_x and radius/2 or -radius/2, 0) local ext = cr:text_extents(text) cr:rel_move_to( (x>center_x and radius/2.5 or (-radius/2.5 - ext.width)), ext.height/2 ) cr:show_text(text) --TODO eventually port away from the toy API cr:stroke() cr:arc(edge_x, edge_y,2,0,2*math.pi) cr:arc(x+(x>center_x and radius/2 or -radius/2),y,2,0,2*math.pi) cr:fill() end local function compute_sum(data) local ret = 0 for _, entry in ipairs(data) do ret = ret + entry[2] end return ret end local function draw(self, _, cr, width, height) if not self._private.data_list then return end local radius = (height > width and width or height) / 4 local sum, start, count = compute_sum(self._private.data_list),0,0 local has_label = self._private.display_labels ~= false -- Labels need to be drawn later so the original source is kept -- use get_source() wont work are the reference cannot be set from Lua(?) local labels = {} local border_width = self:get_border_width() or 1 local border_color = self:get_border_color() border_color = border_color and color(border_color) -- Draw the pies cr:save() cr:set_line_width(border_width) -- Alternate from a given sets or colors local colors = self:get_colors() local col_count = colors and #colors or 0 for _, entry in ipairs(self._private.data_list) do local k, v = entry[1], entry[2] local end_angle = start + 2*math.pi*(v/sum) local col = colors and color(colors[math.fmod(count,col_count)+1]) or nil pie(cr, width, height, start, end_angle, radius) if col then cr:save() cr:set_source(color(col)) end if border_width > 0 then if col then cr:fill_preserve() cr:restore() end -- By default, it uses the fg color if border_color then cr:set_source(border_color) end cr:stroke() elseif col then cr:fill() cr:restore() end -- Store the label position for later if has_label then table.insert(labels, { --[[angle ]] start+(end_angle-start)/2, --[[radius ]] radius, --[[center_x]] width/2, --[[center_y]] height/2, --[[text ]] k, }) end start,count = end_angle,count+1 end cr:restore() -- Draw the labels if has_label then for _, v in ipairs(labels) do draw_label(cr, unpack(v)) end end end local function fit(_, _, width, height) return width, height end --- The pie chart data list. -- -- @property data_list -- @tparam table data_list Sorted table where each entry has a label as its -- first value and a number as its second value. -- @propemits false false --- The pie chart data. -- -- @property data -- @tparam table data Labels as keys and number as value. -- @propemits false false --- The border color. -- -- If none is set, it will use current foreground (text) color. -- --@DOC_wibox_widget_piechart_border_color_EXAMPLE@ -- @property border_color -- @tparam color border_color -- @propemits true false -- @propbeautiful -- @see gears.color --- The pie elements border width. -- --@DOC_wibox_widget_piechart_border_width_EXAMPLE@ -- @property border_width -- @tparam[opt=1] number border_width -- @propemits true false -- @propbeautiful --- The pie chart colors. -- -- If no color is set, only the border will be drawn. If less colors than -- required are set, colors will be re-used in order. -- -- @property colors -- @tparam table colors A table of colors, one for each elements. -- @propemits true false -- @propbeautiful -- @see gears.color --- The border color. -- -- If none is set, it will use current foreground (text) color. -- @beautiful beautiful.piechart_border_color -- @param color -- @see gears.color --- If the pie chart has labels. -- --@DOC_wibox_widget_piechart_label_EXAMPLE@ -- @property display_labels -- @param[opt=true] boolean --- The pie elements border width. -- -- @beautiful beautiful.piechart_border_width -- @tparam[opt=1] number border_width --- The pie chart colors. -- -- If no color is set, only the border will be drawn. If less colors than -- required are set, colors will be re-used in order. -- @beautiful beautiful.piechart_colors -- @tparam table colors A table of colors, one for each elements -- @see gears.color for _, prop in ipairs {"data_list", "border_color", "border_width", "colors", "display_labels" } do piechart["set_"..prop] = function(self, value) self._private[prop] = value self:emit_signal("property::"..prop) if prop == "data_list" then self:emit_signal("property::data") else self:emit_signal("property::"..prop, value) end self:emit_signal("widget::redraw_needed") end piechart["get_"..prop] = function(self) return self._private[prop] or beautiful["piechart_"..prop] end end function piechart:set_data(value) local list = {} for k, v in pairs(value) do table.insert(list, { k, v }) end self:set_data_list(list) end function piechart:get_data() local list = {} for _, entry in ipairs(self:get_data_list()) do list[entry[1]] = entry[2] end return list end --- Create a new piechart. -- -- @constructorfct wibox.widget.piechart -- @tparam table data_list The data. local function new(data_list) local ret = base.make_widget(nil, nil, { enable_properties = true, }) gtable.crush(ret, piechart) rawset(ret, "fit" , fit ) rawset(ret, "draw", draw) ret:set_data_list(data_list) return ret end --@DOC_widget_COMMON@ --@DOC_object_COMMON@ return setmetatable(module, { __call = function(_, ...) return new(...) end }) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
nyczducky/darkstar
scripts/globals/items/seito.lua
42
1047
----------------------------------------- -- ID: 17797 -- Item: Seito -- Additional Effect: Silence -- TODO: Enchantment: Ensilence ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance or applyResistanceAddEffect(player,target,ELE_WIND,0) <= 0.5) then return 0,0,0; else if (not target:hasStatusEffect(EFFECT_SILENCE)) then target:addStatusEffect(EFFECT_SILENCE, 1, 0, 60); end return SUBEFFECT_SILENCE, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_SILENCE; end end; ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) end;
gpl-3.0
wenhulove333/ScutServer
Sample/Koudai/Client/lua/scenes/CompetitiveBattle.lua
1
3387
------------------------------------------------------------------ -- CompetitiveBattle.lua -- Author : Zonglin Liu -- Version : 1.0 -- Date : -- Description: ------------------------------------------------------------------ module("CompetitiveBattle", package.seeall) function setBattleInfo(info, scene, battleType) mBattleInfo = info mScene = scene _battleType = battleType end -- ³¡¾°Èë¿Ú function pushScene() initResource() createScene() end -- Í˳ö³¡¾° function closeAction() closeFightLayer() if mLayer then mLayer:getParent():removeChild(mLayer, true) mLayer = nil end releaseResource() afterClose() end function afterClose() MainMenuLayer.refreshWin() if _battleType == 4 then--ºÃÓÑ elseif _battleType == 1 then--¾º¼¼³¡ CompetitiveScene.refreshWin() elseif _battleType == 2 then--Ðżþ MainMenuLayer.refreshWin() elseif _battleType == 7 then--Ðżþ»Ø·Å MainMenuLayer.refreshWin() end end -- -------------------------˽ÓнӿÚ------------------------ -- -- ³õʼ»¯×ÊÔ´¡¢³ÉÔ±±äÁ¿ function initResource() end -- ÊÍ·Å×ÊÔ´ function releaseResource() mLayer = nil fightLayer=nil mBattleInfo=nil end -- ´´½¨³¡¾° function createScene() -- Ìí¼ÓÖ÷²ã mLayer= CCLayer:create() mScene:addChild(mLayer, 1) local actionBtn=UIHelper.createActionRect(pWinSize) actionBtn:setPosition(PT(0,0)) mLayer:addChild(actionBtn,0) creatBg() startFight(mBattleInfo) end function creatBg() local imageBg = CCSprite:create(P("map/map_1001.jpg")) imageBg:setScaleX(pWinSize.width/imageBg:getContentSize().width) imageBg:setScaleY(pWinSize.height/imageBg:getContentSize().height) imageBg:setAnchorPoint(PT(0,0)) imageBg:setPosition(PT(0,0)) mLayer:addChild(imageBg, 0) end; ----------------¿ªÊ¼Õ½¶· function startFight(info) if fightLayer then fightLayer:getParent():removeChild(fightLayer, true) fightLayer = nil end local layer = CCLayer:create() mLayer:addChild(layer, 0) fightLayer = layer local battleType = _battleType if battleType==7 then IsOverCombat = 1 else IsOverCombat = nil--1Ìø¹ý end PlotFightLayer.setFightInfo(info,IsOverCombat,battleType) PlotFightLayer.init(fightLayer) end; function battleOver() if mBattleInfo.SportsPrizeStr and mBattleInfo.SportsPrizeStr ~= "" then showMysteria()--ÉñÃØÊ¼þ else showResult() end end function showMysteria() local box = ZyMessageBoxEx:new() box:isGrilShow(true) box:doPrompt(mScene, nil, mBattleInfo.SportsPrizeStr , Language.IDS_SURE,showResult) end; function showResult() local resultStr = "" if mBattleInfo.IsWin == 1 then resultStr = resultStr..Language.PLOT_WIN else resultStr = resultStr..Language.PLOT_FALSE end resultStr = resultStr..Language.IDS_COMMA..Language.IDS_PRICE..Language.IDS_COLON if mBattleInfo.GameCoin ~= nil and mBattleInfo.GameCoin > 0 then resultStr = resultStr..mBattleInfo.GameCoin..Language.IDS_GOLD end -- IDS_COMMA local box = ZyMessageBoxEx:new() box:isGrilShow(true) box:doPrompt(mScene, nil, resultStr,Language.IDS_OK,closeAction) end; function closeFightLayer() if fightLayer then fightLayer:getParent():removeChild(fightLayer, true) fightLayer = nil end PlotFightLayer.releaseResource() end;
mit
nyczducky/darkstar
scripts/zones/Spire_of_Holla/bcnms/ancient_flames_beckon.lua
29
4222
----------------------------------- -- Area: Spire_of_Holla -- Name: ancient_flames_backon -- KSNM30 ----------------------------------- package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/globals/teleports"); require("scripts/zones/Spire_of_Holla/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) print("instance code "); end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- printf("leavecode: %u",leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then if (player:hasKeyItem(LIGHT_OF_MEA) and player:hasKeyItem(LIGHT_OF_DEM)) then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,3); elseif (player:hasKeyItem(LIGHT_OF_MEA) or player:hasKeyItem(LIGHT_OF_DEM)) then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,2); end elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS) then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,1); else player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); -- can't tell which cs is playing when you're doing it again to help end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7D01) then if (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then if (player:hasKeyItem(LIGHT_OF_MEA) and player:hasKeyItem(LIGHT_OF_DEM)) then player:addExp(1500); player:addKeyItem(LIGHT_OF_HOLLA); player:messageSpecial(CANT_REMEMBER,LIGHT_OF_HOLLA); player:completeMission(COP,THE_MOTHERCRYSTALS); player:setVar("PromathiaStatus",0) player:addMission(COP,AN_INVITATION_WEST); player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_LUFAISE,0,1); elseif (not(player:hasKeyItem(LIGHT_OF_HOLLA))) then player:setVar("cspromy3",1) player:addKeyItem(LIGHT_OF_HOLLA); player:addExp(1500); player:messageSpecial(CANT_REMEMBER,LIGHT_OF_HOLLA); player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMHOLLA,0,1); end elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS) then player:addExp(1500); player:completeMission(COP,BELOW_THE_ARKS); player:addMission(COP,THE_MOTHERCRYSTALS) player:setVar("cspromy2",1) player:setVar("PromathiaStatus",0) player:addKeyItem(LIGHT_OF_HOLLA); player:messageSpecial(CANT_REMEMBER,LIGHT_OF_HOLLA); player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMHOLLA,0,1); else player:addExp(1500); player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMHOLLA,0,1); end end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Kazham/npcs/Hozie_Naharaf.lua
17
1071
----------------------------------- -- Area: Kazham -- NPC: Hozie Naharaf -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00B3); -- scent from Blue Rafflesias else player:startEvent(0x0059); 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
ahmedjabbar/uor
plugins/help.lua
1
1104
--[[ # #ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ #:(( # For More Information ....! # Developer : Ahmed < @ahmedjabbar1 > # our channel: @p444p # Version: 1.1 #:)) #ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ # ]] do local function run(msg, matches) if is_momod(msg) and matches[1]== "help" then return [[ WeLcoOomE 🎭 There are four lists assistant💡 [توجد اربعة قوائم للاوامر] __________________________ 🔹- /list1 — اوامر ادارة المجموعة 🔹- /list2 — اوامر حماية المجموعة 🔹- /list3 — اوامر اضافية للمجموعات 🔹- /sudo -- اوامر خاصة بالمطور ____________________ Channel : @p444p 🎗 ]] end end return { description = "Help list", usage = "Help list", patterns = { "[#!/](help)" }, run = run } end
gpl-2.0
oldstylejoe/vlc-timed
share/lua/playlist/france2.lua
113
2115
--[[ $Id$ Copyright © 2008 the VideoLAN team Authors: Antoine Cellerier <dionoea at videolan dot org> 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "jt.france2.fr/player/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "class=\"editiondate\"" ) then _,_,editiondate = string.find( line, "<h1>(.-)</h1>" ) end if string.match( line, "mms.*%.wmv" ) then _,_,video = string.find( line, "mms(.-%.wmv)" ) video = "mmsh"..video table.insert( p, { path = video; name = editiondate } ) end if string.match( line, "class=\"subjecttimer\"" ) then oldtime = time _,_,time = string.find( line, "href=\"(.-)\"" ) if oldtime then table.insert( p, { path = video; name = name; duration = time - oldtime; options = { ':start-time='..tostring(oldtime); ':stop-time='..tostring(time) } } ) end name = vlc.strings.resolve_xml_special_chars( string.gsub( line, "^.*>(.*)<..*$", "%1" ) ) end end if oldtime then table.insert( p, { path = video; name = name; options = { ':start-time='..tostring(time) } } ) end return p end
gpl-2.0
catinred2/some-mmorpg
server/test/test_srp.lua
8
1138
local skynet = require "skynet" local srp = require "srp" local function protect (...) local ok = pcall (...) assert (ok == false) end skynet.start (function () local I = "jintiao" local p = "123abc*()DEF" -- call at server side when user register new user protect (srp.create_verifier) protect (srp.create_verifier, I) local s, v = srp.create_verifier (I, p) assert (s and v) -- call at client side when user try to login local a, A = srp.create_client_key () -- call at server side. A is send from client to server protect (srp.create_server_session_key) protect (srp.create_server_session_key, v) local Ks, b, B = srp.create_server_session_key (v, A) -- call at client side. s, B is send from server to client protect (srp.create_client_session_key) protect (srp.create_client_session_key, I) local Kc = srp.create_client_session_key (I, p, s, a, A, B) -- we should not use this in real world, K must not expose to network -- use this key to encrypt something then verify it on other side is more reasonable if assert (Ks == Kc) then print ("srp test passed") else print ("srp test failed") end end)
mit
AquariaOSE/Aquaria
files/scripts/entities/vine.lua
5
2527
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- SPORE SEED v.growEmitter = 0 v.done = false v.lifeTime = 0 function init(me) setupEntity(me) entity_setTexture(me, "Naija/Thorn") --[[ entity_setWidth(me, 64) entity_setHeight(me, 512) ]]-- entity_setEntityLayer(me, -1) entity_initEmitter(me, v.growEmitter, "SporeSeedGrow") entity_setCollideRadius(me, 0) entity_setState(me, STATE_IDLE) entity_setInternalOffset(me, 0, -128) v.lifeTime = 5 entity_alpha(me, 0) entity_alpha(me, 1, 0.1) entity_scale(me, 1, 0) entity_scale(me, 1, 1, 0.5, 0, 0, 1) entity_clampToSurface(me) end function postInit(me) entity_rotateToSurfaceNormal(me) end function songNote(me, note) end function update(me, dt) if not v.done then v.lifeTime = v.lifeTime - dt if v.lifeTime < 0 then entity_delete(me, 0.2) v.done = true end local sx, sy = entity_getScale(me) local len = 256*sy local x1, y1 = entity_getPosition(me) local fx, fy = entity_getNormal(me) local x2 = x1 + fx*len local y2 = y1 + fy*len local ent = getFirstEntity() while ent~=0 do if entity_getEntityType(ent) ~= ET_NEUTRAL and ent ~= me and entity_isDamageTarget(ent, DT_AVATAR_VINE) then local dmg = 0.5 if entity_getEntityType(ent)==ET_AVATAR and isForm(FORM_NATURE) then dmg = 0 end if entity_collideCircleVsLine(ent, x1,y1,x2,y2,16) then if dmg ~= 0 then entity_damage(ent, me, 0.5, DT_AVATAR_VINE) end end end ent = getNextEntity() end end end function hitSurface(me) end function enterState(me) end function damage(me, attacker, bone, damageType, dmg) return false end function exitState(me) end
gpl-2.0
ichiinisanshi/Learning-with-Penny-the-Pony
tagalog_alphabet.lua
1
47692
local storyboard = require("storyboard") local scene = storyboard.newScene() local widget = require("widget") local external = require("external") function scene:willEnterScene( event ) local group = self.view storyboard.removeAll() storyboard.removeScene("balloonGame") end function scene:createScene( event ) local screenGroup = self.view local nextButton, restartButton, bubble1, bubble2, bubble3, bubble4, bubble5, bubble6 local letter1, letter2, letter3, letter4, letter5, letter6 local function1, function2, function3, function4, function5, function6 local destroyObjects local answer1 = false local answer2 = false local answer3 = false local answer4 = false local answer5 = false local answer6 = false local set, answer local rand = 1 local trackNum = 10 local instruction = display.newImage("images/instructions/tagalog_arrangeAlphabet.png") instruction.x = display.contentWidth * 0.5 instruction.y = display.contentHeight * 0.5 instruction:scale(0.7,0.7) external.intruct("tagAlphabet") local bg = display.newImageRect("images/backgrounds/BG_alphabet.png", display.contentWidth, display.contentHeight) bg.x = display.contentWidth * 0.5 bg.y = display.contentHeight * 0.5 screenGroup:insert(bg) local trackText = display.newText("Buhay: "..trackNum, 0, 0, "Chinacat", 50) trackText.x = display.contentWidth * 0.52 trackText.y = display.contentHeight * 0.85 trackText:setFillColor(0,0,0) screenGroup:insert(trackText) local message = display.newText("Mahusay!!", 0, 0, "Chinacat", 55) message.x = display.contentWidth * 0.5 message.y = display.contentHeight * 0.15 message.alpha = 0 message:setFillColor(0,0,0) screenGroup:insert(message) local function endGame() destroyObjects() external.correctionEffects("yehey") message.alpha = 1 restartButton.alpha = 1 -- returnButton.alpha = 1 --backButton.alpha = 0 trackText.alpha = 0 end local function keepTrack() if trackNum == 1 then trackNum = trackNum - 1 trackText.text = "Buhay: "..trackNum restartButton.alpha = 1 -- returnButton.alpha = 1 --backButton.alpha = 0 destroyObjects() else trackNum = trackNum - 1 trackText.text = "Buhay: "..trackNum end end local function newSet() local rand2 = math.random(1,4) if rand == 1 then if rand2 == 1 then set = {'B','C','A','E','D','-'} elseif rand2 == 2 then set = {'D','A','C','E','B','-'} elseif rand2 == 3 then set = {'C','D','B','A','E','-'} elseif rand2 == 4 then set = {'E','B','C','D','A','-'} end answer = {'A','B','C','D','E'} elseif rand == 2 then if rand2 == 1 then set = {'G','I','H','J','F','-'} elseif rand2 == 2 then set = {'H','F','G','I','J','-'} elseif rand2 == 3 then set = {'J','H','I','F','G','-'} elseif rand2 == 4 then set = {'I','J','F','G','H','-'} end answer = {'F','G','H','I','J'} elseif rand == 3 then if rand2 == 1 then set = {'O','L','N','M','K','-'} elseif rand2 == 2 then set = {'M','L','N','K','O','-'} elseif rand2 == 3 then set = {'N','O','K','M','L','-'} elseif rand2 == 4 then set = {'L','N','O','K','M','-'} end answer = {'K','L','M','N','O'} elseif rand == 4 then if rand2 == 1 then set = {'Q','S','R','T','P','-'} elseif rand2 == 2 then set = {'S','T','Q','P','R','-'} elseif rand2 == 3 then set = {'T','P','R','Q','S','-'} elseif rand2 == 4 then set = {'P','S','T','Q','R','-'} end answer = {'P','Q','R','S','T'} elseif rand == 5 then if rand2 == 1 then set = {'Z','X','Y','V','W','U'} elseif rand2 == 2 then set = {'X','W','V','Z','U','Y'} elseif rand2 == 3 then set = {'U','Z','Y','X','V','W'} elseif rand2 == 4 then set = {'X','Y','W','U','V','Z'} end answer = {'U','V','W','X','Y','Z'} end end local function createSet() bubble1 = display.newImage("images/bubble.png") if rand == 5 then bubble1.x = display.contentWidth * 0.1875 else bubble1.x = display.contentWidth * 0.25 end bubble1.y = display.contentHeight * 0.3 bubble1:scale(3.5,3.5) screenGroup:insert(bubble1) bubble2 = display.newImage("images/bubble.png") if rand == 5 then bubble2.x = display.contentWidth * 0.3125 else bubble2.x = display.contentWidth * 0.375 end bubble2.y = display.contentHeight * 0.2 bubble2:scale(3.5,3.5) screenGroup:insert(bubble2) bubble3 = display.newImage("images/bubble.png") if rand == 5 then bubble3.x = display.contentWidth * 0.4375 else bubble3.x = display.contentWidth * 0.5 end bubble3.y = display.contentHeight * 0.1 bubble3:scale(3.5,3.5) screenGroup:insert(bubble3) bubble4 = display.newImage("images/bubble.png") if rand == 5 then bubble4.x = display.contentWidth * 0.5625 else bubble4.x = display.contentWidth * 0.625 end bubble4.y = display.contentHeight * 0.2 bubble4:scale(3.5,3.5) screenGroup:insert(bubble4) bubble5 = display.newImage("images/bubble.png") if rand == 5 then bubble5.x = display.contentWidth * 0.6875 else bubble5.x = display.contentWidth * 0.75 end bubble5.y = display.contentHeight * 0.3 bubble5:scale(3.5,3.5) screenGroup:insert(bubble5) bubble6 = display.newImage("images/bubble.png") bubble6.x = display.contentWidth * 0.8125 bubble6.y = display.contentHeight * 0.5 bubble6:scale(3.5,3.5) if rand ~= 5 then bubble6.alpha = 0 end screenGroup:insert(bubble6) letter1 = display.newText(set[1], 0, 0, "HVD Comic Serif Pro", 40) letter1.x = bubble1.x letter1.y = bubble1.y letter1:setFillColor(0,0,0) screenGroup:insert(letter1) letter2 = display.newText(set[2], 0, 0, "HVD Comic Serif Pro", 40) letter2.x = bubble2.x letter2.y = bubble2.y letter2:setFillColor(0,0,0) screenGroup:insert(letter2) letter3 = display.newText(set[3], 0, 0, "HVD Comic Serif Pro", 40) letter3.x = bubble3.x letter3.y = bubble3.y letter3:setFillColor(0,0,0) screenGroup:insert(letter3) letter4 = display.newText(set[4], 0, 0, "HVD Comic Serif Pro", 40) letter4.x = bubble4.x letter4.y = bubble4.y letter4:setFillColor(0,0,0) screenGroup:insert(letter4) letter5 = display.newText(set[5], 0, 0, "HVD Comic Serif Pro", 40) letter5.x = bubble5.x letter5.y = bubble5.y letter5:setFillColor(0,0,0) screenGroup:insert(letter5) letter6 = display.newText(set[6], 0, 0, "HVD Comic Serif Pro", 40) letter6.x = bubble6.x letter6.y = bubble6.y letter6:setFillColor(0,0,0) if rand ~= 5 then letter6.alpha = 0 end screenGroup:insert(letter6) end local function endLevel() nextButton.alpha = 1 end local function setFunctions() function function1() if answer1 == false and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[1] == answer[1] then answer1 = true if rand == 5 then transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[1] == answer[2] then answer2 = true if rand == 5 then transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[1] == answer[3] then answer3 = true if rand == 5 then transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == false and answer5 == false and answer6 == false then if set[1] == answer[4] then answer4 = true if rand == 5 then transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == false and answer6 == false then if set[1] == answer[5] then answer5 = true if rand == 5 then transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endLevel, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == true and answer6 == false then if set[1] == answer[6] then answer6 = true if rand == 5 then transition.to(bubble1, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter1, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endGame, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end end end function function2() if answer1 == false and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[2] == answer[1] then answer1 = true if rand == 5 then transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[2] == answer[2] then answer2 = true if rand == 5 then transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[2] == answer[3] then answer3 = true if rand == 5 then transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == false and answer5 == false and answer6 == false then if set[2] == answer[4] then answer4 = true if rand == 5 then transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == false and answer6 == false then if set[2] == answer[5] then answer5 = true if rand == 5 then transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endLevel, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == true and answer6 == false then if set[2] == answer[6] then answer6 = true if rand == 5 then transition.to(bubble2, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter2, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endGame, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end end end function function3() if answer1 == false and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[3] == answer[1] then answer1 = true if rand == 5 then transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[3] == answer[2] then answer2 = true if rand == 5 then transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[3] == answer[3] then answer3 = true if rand == 5 then transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == false and answer5 == false and answer6 == false then if set[3] == answer[4] then answer4 = true if rand == 5 then transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == false and answer6 == false then if set[3] == answer[5] then answer5 = true if rand == 5 then transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endLevel, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == true and answer6 == false then if set[3] == answer[6] then answer6 = true if rand == 5 then transition.to(bubble3, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter3, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endGame, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end end end function function4() if answer1 == false and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[4] == answer[1] then answer1 = true if rand == 5 then transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[4] == answer[2] then answer2 = true if rand == 5 then transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[4] == answer[3] then answer3 = true if rand == 5 then transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == false and answer5 == false and answer6 == false then if set[4] == answer[4] then answer4 = true if rand == 5 then transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == false and answer6 == false then if set[4] == answer[5] then answer5 = true if rand == 5 then transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endLevel, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == true and answer6 == false then if set[4] == answer[6] then answer6 = true if rand == 5 then transition.to(bubble4, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter4, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endGame, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end end end function function5() if answer1 == false and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[5] == answer[1] then answer1 = true if rand == 5 then transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.25, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[5] == answer[2] then answer2 = true if rand == 5 then transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.375, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[5] == answer[3] then answer3 = true if rand == 5 then transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.5, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == false and answer5 == false and answer6 == false then if set[5] == answer[4] then answer4 = true if rand == 5 then transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.625, y = display.contentHeight * 0.7, time = 350}) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == false and answer6 == false then if set[5] == answer[5] then answer5 = true if rand == 5 then transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) else transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.75, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endLevel, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == true and answer6 == false then if set[5] == answer[6] then answer6 = true if rand == 5 then transition.to(bubble5, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter5, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endGame, 1) end external.soundEffects("pop") else keepTrack() external.correctionEffects("wrong") system.vibrate() end end end local function function6() if answer1 == false and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[6] == answer[1] then answer1 = true transition.to(bubble6, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) transition.to(letter6, {alpha = 0, x = display.contentWidth * 0.1865, y = display.contentHeight * 0.7, time = 350}) else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == false and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[6] == answer[2] then answer2 = true transition.to(bubble6, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter6, {alpha = 0, x = display.contentWidth * 0.3125, y = display.contentHeight * 0.7, time = 350}) else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == false and answer4 == false and answer5 == false and answer6 == false then if set[6] == answer[3] then answer3 = true transition.to(bubble6, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) transition.to(letter6, {alpha = 0, x = display.contentWidth * 0.4375, y = display.contentHeight * 0.7, time = 350}) else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == false and answer5 == false and answer6 == false then if set[6] == answer[4] then answer4 = true transition.to(bubble6, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) transition.to(letter6, {alpha = 0, x = display.contentWidth * 0.5625, y = display.contentHeight * 0.7, time = 350}) else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == false and answer6 == false then if set[6] == answer[5] then answer5 = true transition.to(bubble6, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) transition.to(letter6, {alpha = 0, x = display.contentWidth * 0.6875, y = display.contentHeight * 0.7, time = 350}) else keepTrack() external.correctionEffects("wrong") system.vibrate() end elseif answer1 == true and answer2 == true and answer3 == true and answer4 == true and answer5 == true and answer6 == false then if set[6] == answer[6] then answer6 = true if rand == 5 then transition.to(bubble6, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) transition.to(letter6, {alpha = 0, x = display.contentWidth * 0.8125, y = display.contentHeight * 0.7, time = 350}) timer.performWithDelay(500, endGame, 1) end else keepTrack() external.correctionEffects("wrong") system.vibrate() end end end bubble1:addEventListener("tap", function1) bubble2:addEventListener("tap", function2) bubble3:addEventListener("tap", function3) bubble4:addEventListener("tap", function4) bubble5:addEventListener("tap", function5) bubble6:addEventListener("tap", function6) if rand == 5 then bubble6:addEventListener("tap", function6) end end function destroyObjects() set = {} answer = {} answer1 = false answer2 = false answer3 = false answer4 = false answer5 = false answer6 = false bubble1:removeSelf() bubble2:removeSelf() bubble3:removeSelf() bubble4:removeSelf() bubble5:removeSelf() bubble6:removeSelf() letter1:removeSelf() letter2:removeSelf() letter3:removeSelf() letter4:removeSelf() letter5:removeSelf() letter6:removeSelf() end nextButton = widget.newButton { defaultFile = "buttons/tagalog/next1.png", overFile = "buttons/tagalog/next1_1.png", onRelease = function() rand = rand + 1 nextButton.alpha = 0 destroyObjects() newSet() createSet() setFunctions() end, } nextButton.x = display.contentWidth * 0.51 nextButton.y = display.contentHeight * 0.35 nextButton.alpha = 0 nextButton:scale(2,2) nextButton.alpha = 0 screenGroup:insert(nextButton) restartButton = widget.newButton { defaultFile = "buttons/tagalog/replay1.png", overFile = "buttons/tagalog/replay1_1.png", onRelease = function() rand = 1 trackNum = 10 trackText.text = "Buhay: "..trackNum trackText.alpha = 1 restartButton.alpha = 0 message.alpha = 0 newSet() createSet() setFunctions() end, } restartButton.x = display.contentWidth * 0.51 restartButton.y = display.contentHeight * 0.4 restartButton.alpha = 0 restartButton:scale(2,2) restartButton.alpha = 0 screenGroup:insert(restartButton) local returnButton = widget.newButton{ defaultFile = "buttons/menu.png", overFile = "buttons/menuOver.png", onRelease = function() storyboard.gotoScene("anotherMenu", "fade", 300) end, } returnButton.x = display.contentWidth * 0.075 returnButton.y = display.contentHeight * 0.1 returnButton:scale(1.2,1.2) returnButton.alpha = 0 screenGroup:insert(returnButton) local backButton = widget.newButton{ defaultFile = "images/homeButton.png", overFile = "images/homeButtonOver.png", onRelease = function() storyboard.gotoScene("anotherMenu", "fade", 300) end, } backButton.x = display.contentWidth * 0.075 backButton.y = display.contentHeight * 0.1 backButton:scale(1.2,1.2) screenGroup:insert(backButton) local function disappearScreen() --transition.to(logo, {alpha = 0, time = 2000}) transition.to(instruction, {alpha = 0, time = 1500}) timer.performWithDelay(1000, mainSplash, 1) end timer.performWithDelay(1500, disappearScreen, 1) newSet() createSet() setFunctions() end function scene:exitScene( event ) end scene:addEventListener( "exitScene", scene ) scene:addEventListener( "createScene", scene ) scene:addEventListener( "willEnterScene", scene ) return scene
mit
nyczducky/darkstar
scripts/zones/Port_San_dOria/npcs/Nogelle.lua
16
2431
----------------------------------- -- Area: Port San d'Oria -- NPC: Nogelle -- Starts Lufet's Lake Salt ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end if (player:getQuestStatus(SANDORIA,LUFET_S_LAKE_SALT) == QUEST_ACCEPTED) then local count = trade:getItemCount(); LufetSalt = trade:hasItemQty(1019,3); if (LufetSalt == true and count == 3) then player:tradeComplete(); player:addFame(SANDORIA,30); player:addGil(GIL_RATE*600); player:addTitle(BEAN_CUISINE_SALTER); player:completeQuest(SANDORIA,LUFET_S_LAKE_SALT); player:startEvent(0x000b); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local LufetsLakeSalt = player:getQuestStatus(SANDORIA,LUFET_S_LAKE_SALT); if (LufetsLakeSalt == 0) then player:startEvent(0x000c); elseif (LufetsLakeSalt == 1) then player:startEvent(0x000a); elseif (LufetsLakeSalt == 2) then player:startEvent(0x020a); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x000c and option == 1) then player:addQuest(SANDORIA,LUFET_S_LAKE_SALT); elseif (csid == 0x000b) then player:messageSpecial(GIL_OBTAINED,GIL_RATE*600); end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Port_Jeuno/npcs/Sanosuke.lua
14
1563
----------------------------------- -- Area: Port Jeuno -- NPC: Sanosuke -- Involved in Quest: A Thief in Norg!? -- @pos -63 7 0 246 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(OUTLANDS,A_THIEF_IN_NORG) == QUEST_ACCEPTED) then aThiefinNorgCS = player:getVar("aThiefinNorgCS"); if (aThiefinNorgCS == 1) then player:startEvent(0x0130); elseif (aThiefinNorgCS == 2) then player:startEvent(0x0131); elseif (aThiefinNorgCS >= 3) then player:startEvent(0x0132); end else player:startEvent(0x012f); 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 == 0x0130) then player:setVar("aThiefinNorgCS",2); end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Abyssea-Altepa/npcs/qm12.lua
10
1394
----------------------------------- -- Zone: Abyssea-Altepa -- NPC: qm12 (???) -- Spawns Dragua -- @pos ? ? ? 218 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(17670553) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(BLOODIED_DRAGON_EAR)) then player:startEvent(1020, BLOODIED_DRAGON_EAR); -- Ask if player wants to use KIs else player:startEvent(1021, BLOODIED_DRAGON_EAR); -- Do not ask, because player is missing at least 1. 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 == 1020 and option == 1) then SpawnMob(17670553):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(BLOODIED_DRAGON_EAR); end end;
gpl-3.0
aminba/bot
plugins/weather.lua
11
1255
function get_weather(location) print("Finding weather in ", location) b, c, h = http.request("http://api.openweathermap.org/data/2.5/weather?q=" .. location .. "&units=metric") weather = json:decode(b) print("Weather returns", weather) local city = weather.name local country = weather.sys.country temp = 'The temperature in ' .. city .. ' (' .. country .. ')' temp = temp .. ' is ' .. weather.main.temp .. '°C' conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end function run(msg, matches) if string.len(matches[1]) > 2 then city = matches[1] else city = "Madrid,ES" end return get_weather(city) end return { description = "weather in that city (Madrid is default)", usage = "!weather (city)", patterns = {"^!weather(.*)$"}, run = run }
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Windurst_Walls/npcs/Tsuaora-Tsuora.lua
38
1043
----------------------------------- -- Area: Windurst Walls -- NPC: Tsuaora-Tsuora -- Type: Standard NPC -- @zone: 239 -- @pos 71.489 -3.418 -67.809 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x002a); 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
Lord-Mohammad/uzzy
plugins/banhammer.lua
294
10470
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
noooway/love2d_arkanoid_tutorial
3-08_LifeAndNextLevelBonuses/balls.lua
8
9287
local vector = require "vector" local sign = math.sign or function(x) return x < 0 and -1 or x > 0 and 1 or 0 end local balls = {} balls.image = love.graphics.newImage( "img/800x600/ball.png" ) local x_tile_pos = 0 local y_tile_pos = 0 local tile_width = 18 local tile_height = 18 local tileset_width = 18 local tileset_height = 18 balls.quad = love.graphics.newQuad( x_tile_pos, y_tile_pos, tile_width, tile_height, tileset_width, tileset_height ) balls.radius = tile_width / 2 local ball_x_shift = -28 local platform_height = 16 local platform_starting_pos = vector( 300, 500 ) local ball_platform_initial_separation = vector( ball_x_shift, -1 * platform_height / 2 - balls.radius - 1 ) local initial_launch_speed_magnitude = 300 balls.current_balls = {} balls.no_more_balls = false function balls.new_ball( position, speed, platform_launch_speed_magnitude, stuck_to_platform ) return( { position = position, speed = speed, platform_launch_speed_magnitude = platform_launch_speed_magnitude, stuck_to_platform = stuck_to_platform, radius = balls.radius, collision_counter = 0, separation_from_platform_center = ball_platform_initial_separation, quad = balls.quad } ) end function balls.add_ball( single_ball ) table.insert( balls.current_balls, single_ball ) end function balls.update_ball( single_ball, dt, platform ) if single_ball.stuck_to_platform then balls.follow_platform( single_ball, platform ) else single_ball.position = single_ball.position + single_ball.speed * dt end end function balls.update( dt, platform ) for _, ball in ipairs( balls.current_balls ) do balls.update_ball( ball, dt, platform ) end balls.check_balls_escaped_from_screen() end function balls.draw_ball( single_ball ) love.graphics.draw( balls.image, single_ball.quad, single_ball.position.x - single_ball.radius, single_ball.position.y - single_ball.radius ) end function balls.draw() for _, ball in ipairs( balls.current_balls ) do balls.draw_ball( ball ) end end function balls.follow_platform( single_ball, platform ) local platform_center = vector( platform.position.x + platform.width / 2, platform.position.y + platform.height / 2 ) single_ball.position = platform_center + single_ball.separation_from_platform_center end function balls.launch_single_ball_from_platform() for _, single_ball in pairs( balls.current_balls ) do if single_ball.stuck_to_platform then single_ball.stuck_to_platform = false local platform_halfwidth = 70 local launch_direction = vector( single_ball.separation_from_platform_center.x / platform_halfwidth, -1 ) single_ball.speed = launch_direction / launch_direction:len() * single_ball.platform_launch_speed_magnitude break end end end function balls.launch_all_balls_from_platform() for _, single_ball in pairs( balls.current_balls ) do if single_ball.stuck_to_platform then single_ball.stuck_to_platform = false local platform_halfwidth = 70 local launch_direction = vector( single_ball.separation_from_platform_center.x / platform_halfwidth, -1 ) single_ball.speed = launch_direction / launch_direction:len() * single_ball.platform_launch_speed_magnitude end end end function balls.wall_rebound( single_ball, shift_ball ) balls.normal_rebound( single_ball, shift_ball ) balls.min_angle_rebound( single_ball ) balls.increase_collision_counter( single_ball ) balls.increase_speed_after_collision( single_ball ) end function balls.platform_rebound( single_ball, shift_ball, platform ) balls.increase_collision_counter( single_ball ) balls.increase_speed_after_collision( single_ball ) if not platform.glued then balls.bounce_from_sphere( single_ball, shift_ball, platform ) else single_ball.stuck_to_platform = true local actual_shift = balls.determine_actual_shift( shift_ball ) single_ball.position = single_ball.position + actual_shift single_ball.platform_launch_speed_magnitude = single_ball.speed:len() balls.compute_ball_platform_separation( single_ball, platform ) end end function balls.compute_ball_platform_separation( single_ball, platform ) local platform_center = vector( platform.position.x + platform.width / 2, platform.position.y + platform.height / 2 ) local ball_center = single_ball.position:clone() single_ball.separation_from_platform_center = ball_center - platform_center print( single_ball.separation_from_platform_center ) end function balls.brick_rebound( single_ball, shift_ball ) balls.normal_rebound( single_ball, shift_ball ) balls.increase_collision_counter( single_ball ) balls.increase_speed_after_collision( single_ball ) end function balls.normal_rebound( single_ball, shift_ball ) local actual_shift = balls.determine_actual_shift( shift_ball ) single_ball.position = single_ball.position + actual_shift if actual_shift.x ~= 0 then single_ball.speed.x = -single_ball.speed.x end if actual_shift.y ~= 0 then single_ball.speed.y = -single_ball.speed.y end end function balls.determine_actual_shift( shift_ball ) local actual_shift = vector( 0, 0 ) local min_shift = math.min( math.abs( shift_ball.x ), math.abs( shift_ball.y ) ) if math.abs( shift_ball.x ) == min_shift then actual_shift.x = shift_ball.x else actual_shift.y = shift_ball.y end return actual_shift end function balls.bounce_from_sphere( single_ball, shift_ball, platform ) local actual_shift = balls.determine_actual_shift( shift_ball ) single_ball.position = single_ball.position + actual_shift if actual_shift.x ~= 0 then single_ball.speed.x = -single_ball.speed.x end if actual_shift.y ~= 0 then local sphere_radius = 200 local ball_center = single_ball.position local platform_center = platform.position + vector( platform.width / 2, platform.height / 2 ) local separation = ( ball_center - platform_center ) local normal_direction = vector( separation.x / sphere_radius, -1 ) local v_norm = single_ball.speed:projectOn( normal_direction ) local v_tan = single_ball.speed - v_norm local reverse_v_norm = v_norm * (-1) single_ball.speed = reverse_v_norm + v_tan end end function balls.min_angle_rebound( single_ball ) local min_horizontal_rebound_angle = math.rad( 20 ) local vx, vy = single_ball.speed:unpack() local new_vx, new_vy = vx, vy rebound_angle = math.abs( math.atan( vy / vx ) ) if rebound_angle < min_horizontal_rebound_angle then new_vx = sign( vx ) * single_ball.speed:len() * math.cos( min_horizontal_rebound_angle ) new_vy = sign( vy ) * single_ball.speed:len() * math.sin( min_horizontal_rebound_angle ) end single_ball.speed = vector( new_vx, new_vy ) end function balls.increase_collision_counter( single_ball ) single_ball.collision_counter = single_ball.collision_counter + 1 end function balls.increase_speed_after_collision( single_ball ) local speed_increase = 20 local each_n_collisions = 10 if single_ball.collision_counter ~= 0 and single_ball.collision_counter % each_n_collisions == 0 then single_ball.speed = single_ball.speed + single_ball.speed:normalized() * speed_increase end end function balls.reset() balls.no_more_balls = false for i in pairs( balls.current_balls ) do balls.current_balls[i] = nil end local position = platform_starting_pos + ball_platform_initial_separation local speed = vector( 0, 0 ) local platform_launch_speed_magnitude = initial_launch_speed_magnitude local stuck_to_platform = true balls.add_ball( balls.new_ball( position, speed, platform_launch_speed_magnitude, stuck_to_platform ) ) end function balls.check_balls_escaped_from_screen() for i, single_ball in pairs( balls.current_balls ) do local x, y = single_ball.position:unpack() local ball_top = y - single_ball.radius if ball_top > love.graphics.getHeight() then table.remove( balls.current_balls, i ) end end if next( balls.current_balls ) == nil then balls.no_more_balls = true end end function balls.react_on_slow_down_bonus() local slowdown = 0.7 for _, single_ball in pairs( balls.current_balls ) do single_ball.speed = single_ball.speed * slowdown end end function balls.react_on_accelerate_bonus() local accelerate = 1.3 for _, single_ball in pairs( balls.current_balls ) do single_ball.speed = single_ball.speed * accelerate end end function balls.react_on_add_new_ball_bonus() local first_ball = balls.current_balls[1] local new_ball_position = first_ball.position:clone() local new_ball_speed = first_ball.speed:rotated( math.pi / 4 ) local new_ball_launch_speed_magnitude = first_ball.platform_launch_speed_magnitude local new_ball_stuck = first_ball.stuck_to_platform balls.add_ball( balls.new_ball( new_ball_position, new_ball_speed, new_ball_launch_speed_magnitude, new_ball_stuck ) ) end return balls
mit
Quenty/NevermoreEngine
src/scoredactionservice/src/Client/InputList/InputListScoreHelper.lua
1
2889
--[=[ Distributes the scored action to the correct providers based upon input mode @class InputListScoreHelper ]=] local require = require(script.Parent.loader).load(script) local BaseObject = require("BaseObject") local InputKeyMapList = require("InputKeyMapList") local InputKeyMapListUtils = require("InputKeyMapListUtils") local Rx = require("Rx") local Set = require("Set") local InputListScoreHelper = setmetatable({}, BaseObject) InputListScoreHelper.ClassName = "InputListScoreHelper" InputListScoreHelper.__index = InputListScoreHelper function InputListScoreHelper.new(serviceBag, provider, scoredAction, inputKeyMapList) local self = setmetatable(BaseObject.new(), InputListScoreHelper) self._serviceBag = assert(serviceBag, "No serviceBag") self._provider = assert(provider, "No provider") self._scoredAction = assert(scoredAction, "No scoredAction") self._inputKeyMapList = assert(inputKeyMapList, "No inputKeyMapList") assert(InputKeyMapList.isInputKeyMapList(inputKeyMapList), "Bad inputKeyMapList") self._currentTypes = {} self._maid:GiveTask(InputKeyMapListUtils.observeActiveInputKeyMap(self._inputKeyMapList, self._serviceBag):Pipe({ Rx.switchMap(function(activeInputKeyMap) if activeInputKeyMap then return activeInputKeyMap:ObserveInputTypesList() else return Rx.of({}) end end) }):Subscribe(function(inputTypeList) self:_updateInputTypeSet(inputTypeList) end)) self._maid:GiveTask(function() local current, _ = next(self._currentTypes) while current do self:_unregisterAction(current) -- Paranoid nil to prevent infinite loop self._currentTypes[current] = nil current, _ = next(self._currentTypes) end end) return self end function InputListScoreHelper:_updateInputTypeSet(inputTypeList) local remaining = Set.copy(self._currentTypes) -- Register inputTypes for _, inputType in pairs(inputTypeList) do if not self._currentTypes[inputType] then self._currentTypes[inputType] = true -- This works pretty ok, but there's no communication between -- inputType -> inputType, so we might get a conflict in mapping -- with 2 types, if there are multiple options per a mode. local pickerForType = self._provider:GetOrCreatePicker(inputType) pickerForType:AddAction(self._scoredAction) end remaining[inputType] = nil end -- Unregister old types for inputType, _ in pairs(remaining) do self:_unregisterAction(inputType) end end function InputListScoreHelper:_unregisterAction(inputType) if not self._currentTypes[inputType] then warn("[InputListScoreHelper] - Already unregistered") end self._currentTypes[inputType] = nil local pickerForType = self._provider:FindPicker(inputType) if pickerForType then pickerForType:RemoveAction(self._scoredAction) else warn("No pickerForType was registered. This should not occur.") end end return InputListScoreHelper
mit
Quenty/NevermoreEngine
src/camera/src/Client/Utility/CameraFrame.lua
1
4515
--[=[ Represents a camera state at a certain point. Can perform math on this state. @class CameraFrame ]=] local require = require(script.Parent.loader).load(script) local QFrame = require("QFrame") local CameraFrame = {} CameraFrame.ClassName = "CameraFrame" CameraFrame.__index = CameraFrame --[=[ Constructs a new CameraFrame @param qFrame QFrame @param fieldOfView number @return CameraFrame ]=] function CameraFrame.new(qFrame, fieldOfView) local self = setmetatable({}, CameraFrame) self.QFrame = qFrame or QFrame.new() self.FieldOfView = fieldOfView or 0 return self end --[=[ Returns whether a value is a CameraFrame @param value any @return boolean ]=] function CameraFrame.isCameraFrame(value) return getmetatable(value) == CameraFrame end --[=[ @prop CFrame CFrame @within CameraFrame ]=] --[=[ @prop Position Vector3 @within CameraFrame ]=] --[=[ @prop FieldOfView number @within CameraFrame ]=] --[=[ @prop QFrame QFrame @within CameraFrame ]=] --[=[ @prop QFrame QFrame @within CameraFrame ]=] function CameraFrame:__index(index) if index == "CFrame" then return QFrame.toCFrame(self.QFrame) or warn("[CameraFrame] - NaN") elseif index == "Position" then return QFrame.toPosition(self.QFrame) or warn("[CameraFrame] - NaN") elseif CameraFrame[index] then return CameraFrame[index] else error(("'%s' is not a valid index of CameraState"):format(tostring(index))) end end function CameraFrame:__newindex(index, value) if index == "CFrame" then assert(typeof(value) == "CFrame", "Bad value") local qFrame = QFrame.fromCFrameClosestTo(value, self.QFrame) assert(qFrame, "Failed to convert") -- Yikes if this fails, but it occurs rawset(self, "QFrame", qFrame) elseif index == "Position" then assert(typeof(value) == "Vector3", "Bad value") local q = self.QFrame rawset(self, "QFrame", QFrame.new(value.x, value.y, value.z, q.W, q.X, q.Y, q.Z)) elseif index == "FieldOfView" or index == "QFrame" then rawset(self, index, value) else error(("'%s' is not a valid index of CameraState"):format(tostring(index))) end end --[=[ Linearly adds the camera frames together. @param a CameraFrame @param b CameraFrame @return CameraFrame ]=] function CameraFrame.__add(a, b) assert(CameraFrame.isCameraFrame(a) and CameraFrame.isCameraFrame(b), "CameraFrame + non-CameraFrame attempted") return CameraFrame.new(a.QFrame + b.QFrame, a.FieldOfView + b.FieldOfView) end --[=[ Linearly subtractions the camera frames together. @param a CameraFrame @param b CameraFrame @return CameraFrame ]=] function CameraFrame.__sub(a, b) assert(CameraFrame.isCameraFrame(a) and CameraFrame.isCameraFrame(b), "CameraFrame - non-CameraFrame attempted") return CameraFrame.new(a.QFrame - b.QFrame, a.FieldOfView - b.FieldOfView) end --[=[ Inverts the QFrame and the field of view. @param a CameraFrame @return CameraFrame ]=] function CameraFrame.__unm(a) return CameraFrame.new(-a.QFrame, -a.FieldOfView) end --[=[ Multiplies the camera frame with the given value @param a CameraFrame | number @param b CameraFrame | number @return CameraFrame ]=] function CameraFrame.__mul(a, b) if type(a) == "number" and CameraFrame.isCameraFrame(b) then return CameraFrame.new(a*b.QFrame, a*b.FieldOfView) elseif CameraFrame.isCameraFrame(b) and type(b) == "number" then return CameraFrame.new(a.QFrame*b, a.FieldOfView*b) elseif CameraFrame.isCameraFrame(a) and CameraFrame.isCameraFrame(b) then return CameraFrame.new(a.QFrame*b.QFrame, a.FieldOfView*b.FieldOfView) else error("CameraFrame * non-CameraFrame attempted") end end --[=[ Divides the camera frame by the value @param a CameraFrame @param b number @return CameraFrame ]=] function CameraFrame.__div(a, b) if CameraFrame.isCameraFrame(a) and type(b) == "number" then return CameraFrame.new(a.QFrame/b, a.FieldOfView/b) else error("CameraFrame * non-CameraFrame attempted") end end --[=[ Takes the camera frame to the Nth power @param a CameraFrame @param b number @return CameraFrame ]=] function CameraFrame.__pow(a, b) if CameraFrame.isCameraFrame(a) and type(b) == "number" then return CameraFrame.new(a.QFrame^b, a.FieldOfView^b) else error("CameraFrame ^ non-CameraFrame attempted") end end --[=[ Compares the camera frame to make sure they're equal @param a CameraFrame @param b CameraFrame @return boolean ]=] function CameraFrame.__eq(a, b) return a.QFrame == b.QFrame and a.FieldOfView == b.FieldOfView end return CameraFrame
mit
ffxiphoenix/darkstar
scripts/zones/Dynamis-Tavnazia/bcnms/dynamis_Tavnazia.lua
16
1139
----------------------------------- -- Area: dynamis_Tavnazia -- Name: dynamis_Tavnazia ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaTavnazia]UniqueID",player:getDynamisUniqueID(1289)); SetServerVariable("[DynaTavnazia]Boss_Trigger",0); SetServerVariable("[DynaTavnazia]Already_Received",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaTavnazia]UniqueID")); local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then SetServerVariable("[DynaTavnazia]UniqueID",0); end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/weaponskills/shadowstitch.lua
18
1531
----------------------------------- -- Shadowstitch -- Dagger weapon skill -- Skill level: 70 -- Binds target. Chance of binding varies with TP. -- Does stack with Sneak Attack. -- Aligned with the Aqua Gorget. -- Aligned with the Aqua Belt. -- Element: None -- Modifiers: CHR:100% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.3; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.chr_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 5) + 5; if (target:hasStatusEffect(EFFECT_BIND) == false) then target:addStatusEffect(EFFECT_BIND, 1, 0, duration); end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Den_of_Rancor/npcs/_4g6.lua
17
2120
----------------------------------- -- Area: Den of Rancor -- NPC: Lantern (SE) -- @pos -59 45 24 160 ----------------------------------- package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Den_of_Rancor/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local Lantern_ID = 17433047 local LSW = GetNPCByID(Lantern_ID):getAnimation(); local LNW = GetNPCByID(Lantern_ID+1):getAnimation(); local LNE = GetNPCByID(Lantern_ID+2):getAnimation(); local LSE = GetNPCByID(Lantern_ID+3):getAnimation(); -- Trade Crimson Rancor Flame if (trade:hasItemQty(1139,1) and trade:getItemCount() == 1) then if (LSE == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit elseif (LSE == 9) then npc:openDoor(LANTERNS_STAY_LIT); local ALL = LNW+LNE+LSW; player:tradeComplete(); player:addItem(1138); -- Unlit Lantern if ALL == 27 then player:messageSpecial(LANTERN_OFFSET + 9); elseif ALL == 26 then player:messageSpecial(LANTERN_OFFSET + 10); elseif ALL == 25 then player:messageSpecial(LANTERN_OFFSET + 11); elseif ALL == 24 then player:messageSpecial(LANTERN_OFFSET + 12); GetNPCByID(Lantern_ID+3):closeDoor(1); GetNPCByID(Lantern_ID+2):closeDoor(1); GetNPCByID(Lantern_ID+1):closeDoor(1); GetNPCByID(Lantern_ID):closeDoor(1); GetNPCByID(Lantern_ID+4):openDoor(30); GetNPCByID(Lantern_ID+3):openDoor(30); GetNPCByID(Lantern_ID+2):openDoor(30); GetNPCByID(Lantern_ID+1):openDoor(30); GetNPCByID(Lantern_ID):openDoor(30); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local npca = npc:getAnimation() if (npca == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit else player:messageSpecial(LANTERN_OFFSET + 20); -- unlit end return 0; end;
gpl-3.0
AfuSensi/Mr.Green-MTA-Resources
resources/[gameplay]/gcshop/items/coloredprojectiles/customcorona/customcorona_c_helper_functions.lua
4
4135
-- -- c_helper_functions.lua -- --------------------------------------------------------------------------------------------------- -- Version check --------------------------------------------------------------------------------------------------- function isMTAUpToDate() local mtaVer = getVersion().sortable -- outputDebugString("MTA Version: "..tostring(mtaVer)) if getVersion ().sortable < "1.3.4-9.05899" then return false else return true end end --------------------------------------------------------------------------------------------------- -- DepthBuffer access --------------------------------------------------------------------------------------------------- function isDepthBufferAccessible() if tostring(dxGetStatus().DepthBufferFormat)=='unknown' then return false else return true end end --------------------------------------------------------------------------------------------------- -- Toint --------------------------------------------------------------------------------------------------- function toint(n) local s = tostring(n) local i = s:find('%.') if i then return tonumber(s:sub(1, i-1)) else return n end end --------------------------------------------------------------------------------------------------- -- debug coronas --------------------------------------------------------------------------------------------------- local coronaDebugSwitch = false addCommandHandler( "debugCustomCoronas", function() if isDebugViewActive() then coronaDebugSwitch = switchDebugCoronas(not coronaDebugSwitch) end end ) function switchDebugCoronas(switch) if switch then addEventHandler("onClientRender",root,renderDebugCoronas) else -- outputDebugString('Debug mode: OFF') removeEventHandler("onClientRender",root,renderDebugCoronas) end return switch end local scx,scy = guiGetScreenSize() function renderDebugCoronas() dxDrawText('Framerate: '..fpscheck()..' FPS',scx/2,25) dxDrawText('Type 1: '..coronaTable.numberType[1]..' Type 2: '..coronaTable.numberType[2],scx/2,40) dxDrawText('Type Material: '..coronaTable.numberType[3],scx/2,55) dxDrawText('DistFade: '..shaderSettings.gDistFade[1]..' TempFade: '..coronaTable.tempFade,scx/2,70) if (#coronaTable.outputCoronas<1) then return end dxDrawText('Visible: '..coronaTable.thisCorona..' Sorted: '..coronaTable.sorted,scx/2,10) end local frames,lastsec,fpsOut = 0,0,0 function fpscheck() local frameticks = getTickCount() frames = frames + 1 if frameticks - 1000 > lastsec then local prog = ( frameticks - lastsec ) lastsec = frameticks fps = frames / (prog / 1000) frames = fps * ((prog - 1000) / 1000) fpsOut = tostring(math.floor( fps )) end return fpsOut end --------------------------------------------------------------------------------------------------- -- corona sorting --------------------------------------------------------------------------------------------------- function sortedOutput(inTable,isSo,distFade,maxEntities) local outTable = {} for index,value in ipairs(inTable) do if inTable[index].enabled then local dist = getElementFromCameraDistance(value.pos[1],value.pos[2],value.pos[3]) if dist <= distFade then local w = #outTable + 1 if not outTable[w] then outTable[w] = {} end outTable[w].enabled = value.enabled outTable[w].material = value.material outTable[w].cType = value.cType outTable[w].shader = value.shader outTable[w].size = value.size outTable[w].dBias = value.dBias outTable[w].pos = value.pos outTable[w].dist = dist outTable[w].color = value.color end end end if isSo and (#outTable > maxEntities) then table.sort(outTable, function(a, b) return a.dist < b.dist end) end return outTable end function findEmptyEntry(inTable) for index,value in ipairs(inTable) do if not value.enabled then return index end end return #inTable + 1 end function getElementFromCameraDistance(hx,hy,hz) local cx,cy,cz,clx,cly,clz,crz,cfov = getCameraMatrix() local dist = getDistanceBetweenPoints3D(hx,hy,hz,cx,cy,cz) return dist end
mit
Quenty/NevermoreEngine
src/playerthumbnailutils/src/Shared/PlayerThumbnailUtils.lua
1
2280
--[=[ Reimplementation of Player:GetUserThumbnailAsync but as a promise with retry logic. @class PlayerThumbnailUtils ]=] local require = require(script.Parent.loader).load(script) local Players = game:GetService("Players") local Promise = require("Promise") local MAX_TRIES = 5 local PlayerThumbnailUtils = {} --[=[ Promises a user thumbnail with retry enabled. ```lua PlayerThumbnailUtils.promiseUserThumbnail(4397833):Then(function(image) imageLabel.Image = image end) ``` @param userId number @param thumbnailType ThumbnailType? @param thumbnailSize ThumbnailSize? @return Promise<string> ]=] function PlayerThumbnailUtils.promiseUserThumbnail(userId, thumbnailType, thumbnailSize) assert(type(userId) == "number", "Bad userId") thumbnailType = thumbnailType or Enum.ThumbnailType.HeadShot thumbnailSize = thumbnailSize or Enum.ThumbnailSize.Size100x100 local promise promise = Promise.spawn(function(resolve, reject) local tries = 0 repeat tries = tries + 1 local content, isReady local ok, err = pcall(function() content, isReady = Players:GetUserThumbnailAsync(userId, thumbnailType, thumbnailSize) end) -- Don't retry if we immediately error (timeout exceptions!) if not ok then return reject(err) end if isReady then return resolve(content) else task.wait(0.05) end until tries >= MAX_TRIES or (not promise:IsPending()) reject() end) return promise end --[=[ Promises a player userName with retries enabled. See UserServiceUtils for display name and a more up-to-date API. @param userId number @return Promise<string> ]=] function PlayerThumbnailUtils.promiseUserName(userId) assert(type(userId) == "number", "Bad userId") local promise promise = Promise.spawn(function(resolve, reject) local tries = 0 repeat tries = tries + 1 local name local ok, err = pcall(function() name = Players:GetNameFromUserIdAsync(userId) end) -- Don't retry if we immediately error (timeout exceptions!) if not ok then return reject(err) end if type(name) == "string" then return resolve(name) else task.wait(0.05) end until tries >= MAX_TRIES or (not promise:IsPending()) reject() end) return promise end return PlayerThumbnailUtils
mit
bgarrels/vlc-2.1
share/lua/modules/simplexml.lua
103
3732
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream, errormsg) if not stream then return nil, errormsg end local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} local nodetype, nodename = reader:next_node() while nodetype > 0 do if nodetype == 1 then local node = { name= nodename, attributes= {}, children= {} } local attr, value = reader:next_attr() while attr ~= nil do node.attributes[attr] = value attr, value = reader:next_attr() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 2 then if #parents > 0 then local tmp = {} while nodename ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 3 then table.insert(tree.children, nodename) end nodetype, nodename = reader:next_node() end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end function add_name_maps(tree) tree.children_map = {} for _, node in pairs(tree.children) do if type(node) == "table" then if not tree.children_map[node.name] then tree.children_map[node.name] = {} end table.insert(tree.children_map[node.name], node) add_name_maps(node) end end end
gpl-2.0
azekillDIABLO/Voxellar
mods/NODES/xtend/xfurniture/system/get_nodes.lua
1
1427
local table_contains = function(table, element) for i,v in pairs(table) do if v == element then return true end end return false end local to_be_ignored = function(name) for _,regex in pairs(_xtend.v.xfurniture.blacklist) do if name:match(regex) ~= nil then return true end end return false end local get_nodes = function() local nodes = {} for name,def in pairs(minetest.registered_nodes) do if def.drawtype == 'normal' and to_be_ignored(name) == false then nodes[name] = def end end for name in _xtend.g('xfurniture_additional_nodes'):gmatch('%S+') do if minetest.registered_nodes[name] ~= nil then nodes[name] = minetest.registered_nodes[name] end end return nodes end _xtend.v.xfurniture.nodes = get_nodes() -- Get nodes per category -- -- @return table A table containing all xFurniture objects (nodes) ordered by -- their category (ID without prefix and material information). _xtend.f.xfurniture.get_nodes_per_category = function () local res = {} for id,def in pairs(minetest.registered_nodes) do if def.groups['_xfurniture_category'] then local category = 'category_'..def.groups['_xfurniture_category'] if not res[category] then res[category] = {} end res[category][id] = def end end return res end
lgpl-2.1
ffxiphoenix/darkstar
scripts/zones/Rabao/npcs/Porter_Moogle.lua
41
1509
----------------------------------- -- Area: Rabao -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 247 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Rabao/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 136, STORE_EVENT_ID = 137, RETRIEVE_EVENT_ID = 138, ALREADY_STORED_ID = 139, MAGIAN_TRIAL_ID = 140 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
RockySeven3161/POWERNEW
plugins/id.lua
12
5756
--[[ Print user identification/informations by replying their post or by providing their username or print_name. !id <text> is the least reliable because it will scan trough all of members and print all member with <text> in their print_name. chat_info can be displayed on group, send it into PM, or save as file then send it into group or PM. --]] do local function scan_name(extra, success, result) local founds = {} for k,member in pairs(result.members) do if extra.name then gp_member = extra.name fields = {'first_name', 'last_name', 'print_name'} elseif extra.user then gp_member = string.gsub(extra.user, '@', '') fields = {'username'} end for k,field in pairs(fields) do if member[field] and type(member[field]) == 'string' then if member[field]:match(gp_member) then founds[tostring(member.id)] = member end end end end if next(founds) == nil then -- Empty table send_msg(extra.receiver, (extra.name or extra.user)..' not found on this chat.', ok_cb, false) else local text = '' for k,user in pairs(founds) do text = text..'Name: '..(user.first_name or '')..' '..(user.last_name or '')..'\n' ..'First name: '..(user.first_name or '')..'\n' ..'Last name: '..(user.last_name or '')..'\n' ..'User name: @'..(user.username or '')..'\n' ..'ID: '..(user.id or '')..'\n\n' end send_msg(extra.receiver, text, ok_cb, false) end end local function action_by_reply(extra, success, result) local text = 'Name: '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'First name: '..(result.from.first_name or '')..'\n' ..'Last name: '..(result.from.last_name or '')..'\n' ..'User name: @'..(result.from.username or '')..'\n' ..'ID: '..result.from.id send_msg(extra.receiver, text, ok_cb, true) end local function returnids(extra, success, result) local chat_id = extra.msg.to.id local text = '['..result.id..'] '..result.title..'.\n' ..result.members_num..' members.\n\n' i = 0 for k,v in pairs(result.members) do i = i+1 if v.username then user_name = ' @'..v.username else user_name = '' end text = text..i..'. ['..v.id..'] '..user_name..' '..(v.first_name or '')..(v.last_name or '')..'\n' end if extra.matches == 'pm' then send_large_msg('user#id'..extra.msg.from.id, text) elseif extra.matches == 'txt' or extra.matches == 'pmtxt' then local textfile = '/tmp/chat_info_'..chat_id..'_'..os.date("%y%m%d.%H%M%S")..'.txt' local file = io.open(textfile, 'w') file:write(text) file:flush() file:close() if extra.matches == 'txt' then send_document('chat#id'..chat_id, textfile, rmtmp_cb, {file_path=textfile}) elseif extra.matches == 'pmtxt' then send_document('user#id'..extra.msg.from.id, textfile, rmtmp_cb, {file_path=textfile}) end elseif not extra.matches then send_large_msg('chat#id'..chat_id, text) end end local function run(msg, matches) local receiver = get_receiver(msg) if is_chat_msg(msg) then if msg.text == '!id' then if msg.reply_id then if is_mod(msg) then msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver}) end else local text = 'Name: '..(msg.from.first_name or '')..' '..(msg.from.last_name or '')..'\n' ..'First name: '..(msg.from.first_name or '')..'\n' ..'Last name: '..(msg.from.last_name or '')..'\n' ..'User name: @'..(msg.from.username or '')..'\n' ..'ID: ' .. msg.from.id local text = text..'\n\nYou are in group ' ..msg.to.title..' (ID: '..msg.to.id..')' return text end elseif is_mod(msg) and matches[1] == 'chat' then if matches[2] == 'pm' or matches[2] == 'txt' or matches[2] == 'pmtxt' then chat_info(receiver, returnids, {msg=msg, matches=matches[2]}) else chat_info(receiver, returnids, {msg=msg}) end elseif is_mod(msg) and string.match(matches[1], '^@.+$') then chat_info(receiver, scan_name, {receiver=receiver, user=matches[1]}) elseif is_mod(msg) and string.gsub(matches[1], ' ', '_') then user = string.gsub(matches[1], ' ', '_') chat_info(receiver, scan_name, {receiver=receiver, name=matches[1]}) end else return 'You are not in a group.' end end return { description = 'Know your id or the id of a chat members.', usage = { user = { '!id: Return your ID and the chat id if you are in one.' }, moderator = { '!id : Return ID of replied user if used by reply.', '!id chat : Return the IDs of the current chat members.', '!id chat txt : Return the IDs of the current chat members and send it as text file.', '!id chat pm : Return the IDs of the current chat members and send it to PM.', '!id chat pmtxt : Return the IDs of the current chat members, save it as text file and then send it to PM.', '!id <id> : Return the IDs of the <id>.', '!id @<user_name> : Return the member @<user_name> ID from the current chat.', '!id <text> : Search for users with <text> on first_name, last_name, or print_name on current chat.' }, }, patterns = { "^!id$", "^!id (chat) (.*)$", "^!id (.*)$" }, run = run } end
gpl-2.0
Quenty/NevermoreEngine
src/deathreport/src/Server/Stats/PlayerKillTrackerAssigner.lua
1
2240
--[=[ @class PlayerKillTrackerAssigner ]=] local require = require(script.Parent.loader).load(script) local Players = game:GetService("Players") local BaseObject = require("BaseObject") local Maid = require("Maid") local PlayerKillTrackerUtils = require("PlayerKillTrackerUtils") local DeathReportBindersServer = require("DeathReportBindersServer") local PlayerKillTrackerAssigner = setmetatable({}, BaseObject) PlayerKillTrackerAssigner.ClassName = "PlayerKillTrackerAssigner" PlayerKillTrackerAssigner.__index = PlayerKillTrackerAssigner function PlayerKillTrackerAssigner.new(serviceBag) local self = setmetatable(BaseObject.new(), PlayerKillTrackerAssigner) self._serviceBag = assert(serviceBag, "No serviceBag") self._deathReportBindersServer = self._serviceBag:GetService(DeathReportBindersServer) self._killTrackers = {} self._maid:GiveTask(Players.PlayerAdded:Connect(function(player) self:_handlePlayerAdded(player) end)) self._maid:GiveTask(Players.PlayerRemoving:Connect(function(player) self:_handlePlayerRemoving(player) end)) for _, player in pairs(Players:GetPlayers()) do self:_handlePlayerAdded(player) end return self end function PlayerKillTrackerAssigner:GetPlayerKills(player) local tracker = self:GetPlayerKillTracker(player) if tracker then return tracker:GetKills() else return nil end end function PlayerKillTrackerAssigner:GetPlayerKillTracker(player) local trackerInstance = self._killTrackers[player] if trackerInstance then return self._deathReportBindersServer.PlayerKillTracker:Get(trackerInstance) else return nil end end function PlayerKillTrackerAssigner:_handlePlayerRemoving(player) self._maid[player] = nil end function PlayerKillTrackerAssigner:_handlePlayerAdded(player) local maid = Maid.new() local killTracker = PlayerKillTrackerUtils.create(self._deathReportBindersServer.PlayerKillTracker, player) maid:GiveTask(killTracker) self._killTrackers[player] = killTracker maid:GiveTask(function() self._killTrackers[player] = nil end) local deathTracker = PlayerKillTrackerUtils.create(self._deathReportBindersServer.PlayerDeathTracker, player) maid:GiveTask(deathTracker) self._maid[player] = maid end return PlayerKillTrackerAssigner
mit
guker/nn
SpatialFullConvolution.lua
42
1589
local SpatialFullConvolution, parent = torch.class('nn.SpatialFullConvolution','nn.Module') function SpatialFullConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.weight = torch.Tensor(nInputPlane, nOutputPlane, kH, kW) self.gradWeight = torch.Tensor(nInputPlane, nOutputPlane, kH, kW) self.bias = torch.Tensor(self.nOutputPlane) self.gradBias = torch.Tensor(self.nOutputPlane) self:reset() end function SpatialFullConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else local nInputPlane = self.nInputPlane local kH = self.kH local kW = self.kW stdv = 1/math.sqrt(kW*kH*nInputPlane) end self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) end function SpatialFullConvolution:updateOutput(input) return input.nn.SpatialFullConvolution_updateOutput(self, input) end function SpatialFullConvolution:updateGradInput(input, gradOutput) if self.gradInput then return input.nn.SpatialFullConvolution_updateGradInput(self, input, gradOutput) end end function SpatialFullConvolution:accGradParameters(input, gradOutput, scale) return input.nn.SpatialFullConvolution_accGradParameters(self, input, gradOutput, scale) end
bsd-3-clause
ffxiphoenix/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/Treasure_Coffer.lua
17
4063
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Treasure Coffer -- @zone 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1046,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1046,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local mJob = player:getMainJob(); local zone = player:getZoneID(); local AFHandsActivated = player:getVar("BorghertzAlreadyActiveWithJob"); local listAF = getAFbyZone(zone); if ((AFHandsActivated == 8 or AFHandsActivated == 5 or AFHandsActivated == 1 or AFHandsActivated == 7) and player:hasKeyItem(OLD_GAUNTLETS) == false) then questItemNeeded = 1; else for nb = 1,table.getn(listAF),3 do if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then questItemNeeded = 2; break end end end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- 0 or 1 -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(OLD_GAUNTLETS); player:messageSpecial(KEYITEM_OBTAINED,OLD_GAUNTLETS); -- Old Gauntlets (KI) elseif (questItemNeeded == 2) then for nb = 1,table.getn(listAF),3 do if (mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1046); 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
ffxiphoenix/darkstar
scripts/globals/pets.lua
37
36137
----------------------------------- -- -- PETS ID -- ----------------------------------- ----------------------------------- -- PETTYPE ----------------------------------- PETTYPE_AVATAR = 0; PETTYPE_WYVERN = 1; PETTYPE_JUGPET = 2; PETTYPE_CHARMED_MOB = 3; PETTYPE_AUTOMATON = 4; PETTYPE_ADVENTURING_FELLOW= 5; PETTYPE_CHOCOBO = 6; ----------------------------------- -- PETNAME ----------------------------------- PETNAME_AZURE = 1; PETNAME_CERULEAN = 2; PETNAME_RYGOR = 3; PETNAME_FIREWING = 4; PETNAME_DELPHYNE = 5; PETNAME_EMBER = 6; PETNAME_ROVER = 7; PETNAME_MAX = 8; PETNAME_BUSTER = 9; PETNAME_DUKE = 10; PETNAME_OSCAR = 11; PETNAME_MAGGIE = 12; PETNAME_JESSIE = 13; PETNAME_LADY = 14; PETNAME_HIEN = 15; PETNAME_RAIDEN = 16; PETNAME_LUMIERE = 17; PETNAME_EISENZAHN = 18; PETNAME_PFEIL = 19; PETNAME_WUFFI = 20; PETNAME_GEORGE = 21; PETNAME_DONRYU = 22; PETNAME_QIQIRU = 23; PETNAME_KARAV_MARAV = 24; PETNAME_OBORO = 25; PETNAME_DARUG_BORUG = 26; PETNAME_MIKAN = 27; PETNAME_VHIKI = 28; PETNAME_SASAVI = 29; PETNAME_TATANG = 30; PETNAME_NANAJA = 31; PETNAME_KHOCHA = 32; PETNAME_DINO = 33; PETNAME_CHOMPER = 34; PETNAME_HUFFY = 35; PETNAME_POUNCER = 36; PETNAME_FIDO = 37; PETNAME_LUCY = 38; PETNAME_JAKE = 39; PETNAME_ROCKY = 40; PETNAME_REX = 41; PETNAME_RUSTY = 42; PETNAME_HIMMELSKRALLE = 43; PETNAME_GIZMO = 44; PETNAME_SPIKE = 45; PETNAME_SYLVESTER = 46; PETNAME_MILO = 47; PETNAME_TOM = 48; PETNAME_TOBY = 49; PETNAME_FELIX = 50; PETNAME_KOMET = 51; PETNAME_BO = 52; PETNAME_MOLLY = 53; PETNAME_UNRYU = 54; PETNAME_DAISY = 55; PETNAME_BARON = 56; PETNAME_GINGER = 57; PETNAME_MUFFIN = 58; PETNAME_LUMINEUX = 59; PETNAME_QUATREVENTS = 60; PETNAME_TORYU = 61; PETNAME_TATABA = 62; PETNAME_ETOILAZUREE = 63; PETNAME_GRISNUAGE = 64; PETNAME_BELORAGE = 65; PETNAME_CENTONNERRE = 66; PETNAME_NOUVELLUNE = 67; PETNAME_MISSY = 68; PETNAME_AMEDEO = 69; PETNAME_TRANCHEVENT = 70; PETNAME_SOUFFLEFEU = 71; PETNAME_ETOILE = 72; PETNAME_TONNERRE = 73; PETNAME_NUAGE = 74; PETNAME_FOUDRE = 75; PETNAME_HYUH = 76; PETNAME_ORAGE = 77; PETNAME_LUNE = 78; PETNAME_ASTRE = 79; PETNAME_WAFFENZAHN = 80; PETNAME_SOLEIL = 81; PETNAME_COURAGEUX = 82; PETNAME_KOFFLA_PAFFLA = 83; PETNAME_VENTEUSE = 84; PETNAME_LUNAIRE = 85; PETNAME_TORA = 86; PETNAME_CELESTE = 87; PETNAME_GALJA_MOGALJA = 88; PETNAME_GABOH = 89; PETNAME_VHYUN = 90; PETNAME_ORAGEUSE = 91; PETNAME_STELLAIRE = 92; PETNAME_SOLAIRE = 93; PETNAME_WIRBELWIND = 94; PETNAME_BLUTKRALLE = 95; PETNAME_BOGEN = 96; PETNAME_JUNKER = 97; PETNAME_FLINK = 98; PETNAME_KNIRPS = 99; PETNAME_BODO = 100; PETNAME_SORYU = 101; PETNAME_WAWARO = 102; PETNAME_TOTONA = 103; PETNAME_LEVIAN_MOVIAN = 104; PETNAME_KAGERO = 105; PETNAME_JOSEPH = 106; PETNAME_PAPARAL = 107; PETNAME_COCO = 108; PETNAME_RINGO = 109; PETNAME_NONOMI = 110; PETNAME_TETER = 111; PETNAME_GIGIMA = 112; PETNAME_GOGODAVI = 113; PETNAME_RURUMO = 114; PETNAME_TUPAH = 115; PETNAME_JYUBIH = 116; PETNAME_MAJHA = 117; PETNAME_LURON = 118; PETNAME_DRILLE = 119; PETNAME_TOURNEFOUX = 120; PETNAME_CHAFOUIN = 121; PETNAME_PLAISANTIN = 122; PETNAME_LOUSTIC = 123; PETNAME_HISTRION = 124; PETNAME_BOBECHE = 125; PETNAME_BOUGRION = 126; PETNAME_ROULETEAU = 127; PETNAME_ALLOUETTE = 128; PETNAME_SERENADE = 129; PETNAME_FICELETTE = 130; PETNAME_TOCADIE = 131; PETNAME_CAPRICE = 132; PETNAME_FOUCADE = 133; PETNAME_CAPILLOTTE = 134; PETNAME_QUENOTTE = 135; PETNAME_PACOTILLE = 136; PETNAME_COMEDIE = 137; PETNAME_KAGEKIYO = 138; PETNAME_TORAOH = 139; PETNAME_GENTA = 140; PETNAME_KINTOKI = 141; PETNAME_KOUMEI = 142; PETNAME_PAMAMA = 143; PETNAME_LOBO = 144; PETNAME_TSUKUSHI = 145; PETNAME_ONIWAKA = 146; PETNAME_KENBISHI = 147; PETNAME_HANNYA = 148; PETNAME_MASHIRA = 149; PETNAME_NADESHIKO = 150; PETNAME_E100 = 151; PETNAME_KOUME = 152; PETNAME_X_32 = 153; PETNAME_POPPO = 154; PETNAME_ASUKA = 155; PETNAME_SAKURA = 156; PETNAME_TAO = 157; PETNAME_MAO = 158; PETNAME_GADGET = 159; PETNAME_MARION = 160; PETNAME_WIDGET = 161; PETNAME_QUIRK = 162; PETNAME_SPROCKET = 163; PETNAME_COGETTE = 164; PETNAME_LECTER = 165; PETNAME_COPPELIA = 166; PETNAME_SPARKY = 167; PETNAME_CLANK = 168; PETNAME_CALCOBRENA = 169; PETNAME_CRACKLE = 170; PETNAME_RICOCHET = 171; PETNAME_JOSETTE = 172; PETNAME_FRITZ = 173; PETNAME_SKIPPY = 174; PETNAME_PINO = 175; PETNAME_MANDARIN = 176; PETNAME_JACKSTRAW = 177; PETNAME_GUIGNOL = 178; PETNAME_MOPPET = 179; PETNAME_NUTCRACKER = 180; PETNAME_ERWIN = 181; PETNAME_OTTO = 182; PETNAME_GUSTAV = 183; PETNAME_MUFFIN = 184; PETNAME_XAVER = 185; PETNAME_TONI = 186; PETNAME_INA = 187; PETNAME_GERDA = 188; PETNAME_PETRA = 189; PETNAME_VERENA = 190; PETNAME_ROSI = 191; PETNAME_SCHATZI = 192; PETNAME_WARASHI = 193; PETNAME_KLINGEL = 194; PETNAME_CLOCHETTE = 195; PETNAME_CAMPANELLO = 196; PETNAME_KAISERIN = 197; PETNAME_PRINCIPESSA = 198; PETNAME_BUTLER = 199; PETNAME_GRAF = 200; PETNAME_CARO = 201; PETNAME_CARA = 202; PETNAME_MADEMOISELLE = 203; PETNAME_HERZOG = 204; PETNAME_TRAMP = 205; PETNAME_V_1000 = 206; PETNAME_HIKOZAEMON = 207; PETNAME_NINE = 208; PETNAME_ACHT = 209; PETNAME_QUATTRO = 210; PETNAME_ZERO = 211; PETNAME_DREIZEHN = 212; PETNAME_SEIZE = 213; PETNAME_FUKUSUKE = 214; PETNAME_MATAEMON = 215; PETNAME_KANSUKE = 216; PETNAME_POLICHINELLE = 217; PETNAME_TOBISUKE = 218; PETNAME_SASUKE = 219; PETNAME_SHIJIMI = 220; PETNAME_CHOBI = 221; PETNAME_AURELIE = 222; PETNAME_MAGALIE = 223; PETNAME_AURORE = 224; PETNAME_CAROLINE = 225; PETNAME_ANDREA = 226; PETNAME_MACHINETTE = 227; PETNAME_CLARINE = 228; PETNAME_ARMELLE = 229; PETNAME_REINETTE = 230; PETNAME_DORLOTE = 231; PETNAME_TURLUPIN = 232; PETNAME_KLAXON = 233; PETNAME_BAMBINO = 234; PETNAME_POTIRON = 235; PETNAME_FUSTIGE = 236; PETNAME_AMIDON = 237; PETNAME_MACHIN = 238; PETNAME_BIDULON = 239; PETNAME_TANDEM = 240; PETNAME_PRESTIDIGE = 241; PETNAME_PURUTE_PORUTE = 242; PETNAME_BITO_RABITO = 243; PETNAME_COCOA = 244; PETNAME_TOTOMO = 245; PETNAME_CENTURION = 246; PETNAME_A7V = 247; PETNAME_SCIPIO = 248; PETNAME_SENTINEL = 249; PETNAME_PIONEER = 250; PETNAME_SENESCHAL = 251; PETNAME_GINJIN = 252; PETNAME_AMAGATSU = 253; PETNAME_DOLLY = 254; PETNAME_FANTOCCINI = 255; PETNAME_JOE = 256; PETNAME_KIKIZARU = 257; PETNAME_WHIPPET = 258; PETNAME_PUNCHINELLO = 259; PETNAME_CHARLIE = 260; PETNAME_MIDGE = 261; PETNAME_PETROUCHKA = 262; PETNAME_SCHNEIDER = 263; PETNAME_USHABTI = 264; PETNAME_NOEL = 265; PETNAME_YAJIROBE = 266; PETNAME_HINA = 267; PETNAME_NORA = 268; PETNAME_SHOKI = 269; PETNAME_KOBINA = 270; PETNAME_KOKESHI = 271; PETNAME_MAME = 272; PETNAME_BISHOP = 273; PETNAME_MARVIN = 274; PETNAME_DORA = 275; PETNAME_DATA = 276; PETNAME_ROBIN = 277; PETNAME_ROBBY = 278; PETNAME_PORLO_MOPERLO = 279; PETNAME_PAROKO_PURONKO= 280; PETNAME_PIPIMA = 281; PETNAME_GAGAJA = 282; PETNAME_MOBIL = 283; PETNAME_DONZEL = 284; PETNAME_ARCHER = 285; PETNAME_SHOOTER = 286; PETNAME_STEPHEN = 287; PETNAME_MK_IV = 288; PETNAME_CONJURER = 289; PETNAME_FOOTMAN = 290; PETNAME_TOKOTOKO = 291; PETNAME_SANCHO = 292; PETNAME_SARUMARO = 293; PETNAME_PICKET = 294; PETNAME_MUSHROOM = 295; PETNAME_G = 296; PETNAME_I = 297; PETNAME_Q = 298; PETNAME_V = 299; PETNAME_X = 300; PETNAME_Z = 301; PETNAME_II = 302; PETNAME_IV = 303; PETNAME_IX = 304; PETNAME_OR = 305; PETNAME_VI = 306; PETNAME_XI = 307; PETNAME_ACE = 308; PETNAME_AIR = 309; PETNAME_AKI = 310; PETNAME_AYU = 311; PETNAME_BAT = 312; PETNAME_BEC = 313; PETNAME_BEL = 314; PETNAME_BIG = 315; PETNAME_BON = 316; PETNAME_BOY = 317; PETNAME_CAP = 318; PETNAME_COQ = 319; PETNAME_CRY = 320; PETNAME_DOM = 321; PETNAME_DUC = 322; PETNAME_DUN = 323; PETNAME_END = 324; PETNAME_ETE = 325; PETNAME_EYE = 326; PETNAME_FAT = 327; PETNAME_FEE = 328; PETNAME_FER = 329; PETNAME_FEU = 330; PETNAME_FOG = 331; PETNAME_FOX = 332; PETNAME_HOT = 333; PETNAME_ICE = 334; PETNAME_ICE = 335; PETNAME_ICY = 336; PETNAME_III = 337; PETNAME_JET = 338; PETNAME_JOY = 339; PETNAME_LEG = 340; PETNAME_MAX = 341; PETNAME_NEO = 342; PETNAME_ONE = 343; PETNAME_PUR = 344; PETNAME_RAY = 345; PETNAME_RED = 346; PETNAME_ROI = 347; PETNAME_SEA = 348; PETNAME_SKY = 349; PETNAME_SUI = 350; PETNAME_SUN = 351; PETNAME_TEN = 352; PETNAME_VIF = 353; PETNAME_VII = 354; PETNAME_XII = 355; PETNAME_AILE = 356; PETNAME_ANGE = 357; PETNAME_ARDI = 358; PETNAME_BEAK = 359; PETNAME_BEAU = 360; PETNAME_BEST = 361; PETNAME_BLEU = 362; PETNAME_BLUE = 363; PETNAME_BONE = 364; PETNAME_CART = 365; PETNAME_CHIC = 366; PETNAME_CIEL = 367; PETNAME_CLAW = 368; PETNAME_COOL = 369; PETNAME_DAME = 370; PETNAME_DARK = 371; PETNAME_DORE = 372; PETNAME_DRAY = 373; PETNAME_DUKE = 374; PETNAME_EASY = 375; PETNAME_EDEL = 376; PETNAME_FACE = 377; PETNAME_FAST = 378; PETNAME_FIER = 379; PETNAME_FINE = 380; PETNAME_FIRE = 381; PETNAME_FOOT = 382; PETNAME_FURY = 383; PETNAME_FUYU = 384; PETNAME_GALE = 385; PETNAME_GIRL = 386; PETNAME_GOER = 387; PETNAME_GOLD = 388; PETNAME_GOOD = 389; PETNAME_GRAF = 390; PETNAME_GRAY = 391; PETNAME_GUST = 392; PETNAME_GUTE = 393; PETNAME_HAOH = 394; PETNAME_HARU = 395; PETNAME_HELD = 396; PETNAME_HERO = 397; PETNAME_HOPE = 398; PETNAME_IDOL = 399; PETNAME_IRIS = 400; PETNAME_IRON = 401; PETNAME_JACK = 402; PETNAME_JADE = 403; PETNAME_JOLI = 404; PETNAME_JUNG = 405; PETNAME_KIKU = 406; PETNAME_KING = 407; PETNAME_KOPF = 408; PETNAME_LADY = 409; PETNAME_LAST = 410; PETNAME_LILI = 411; PETNAME_LILY = 412; PETNAME_LINE = 413; PETNAME_LONG = 414; PETNAME_LORD = 415; PETNAME_LUFT = 416; PETNAME_LUNA = 417; PETNAME_LUNE = 418; PETNAME_MAMA = 419; PETNAME_MARS = 420; PETNAME_MIEL = 421; PETNAME_MISS = 422; PETNAME_MOMO = 423; PETNAME_MOND = 424; PETNAME_MOON = 425; PETNAME_NANA = 426; PETNAME_NICE = 427; PETNAME_NOIR = 428; PETNAME_NONO = 429; PETNAME_NOVA = 430; PETNAME_NUIT = 431; PETNAME_OCRE = 432; PETNAME_OLLE = 433; PETNAME_PAPA = 434; PETNAME_PERS = 435; PETNAME_PHAR = 436; PETNAME_PONY = 437; PETNAME_PURE = 438; PETNAME_RAIN = 439; PETNAME_RICE = 440; PETNAME_RICH = 441; PETNAME_ROAD = 442; PETNAME_ROSE = 443; PETNAME_ROTE = 444; PETNAME_ROUX = 445; PETNAME_RUBY = 446; PETNAME_SAGE = 447; PETNAME_SNOW = 448; PETNAME_STAR = 449; PETNAME_TAIL = 450; PETNAME_TROT = 451; PETNAME_VEGA = 452; PETNAME_VENT = 453; PETNAME_VERT = 454; PETNAME_VIII = 455; PETNAME_VIVE = 456; PETNAME_WAVE = 457; PETNAME_WEST = 458; PETNAME_WILD = 459; PETNAME_WIND = 460; PETNAME_WING = 461; PETNAME_XIII = 462; PETNAME_ZERO = 463; PETNAME_ACIER = 464; PETNAME_AGATE = 465; PETNAME_AGILE = 466; PETNAME_AGNES = 467; PETNAME_AILEE = 468; PETNAME_ALPHA = 469; PETNAME_AMBER = 470; PETNAME_AMBRE = 471; PETNAME_ANGEL = 472; PETNAME_ARDIE = 473; PETNAME_ARKIE = 474; PETNAME_ARROW = 475; PETNAME_AVIAN = 476; PETNAME_AZURE = 477; PETNAME_BARON = 478; PETNAME_BELLE = 479; PETNAME_BERYL = 480; PETNAME_BLACK = 481; PETNAME_BLADE = 482; PETNAME_BLAUE = 483; PETNAME_BLAZE = 484; PETNAME_BLEUE = 485; PETNAME_BLITZ = 486; PETNAME_BLOND = 487; PETNAME_BLOOD = 488; PETNAME_BONNE = 489; PETNAME_BRAVE = 490; PETNAME_BRIAN = 491; PETNAME_BRISE = 492; PETNAME_BURST = 493; PETNAME_CALME = 494; PETNAME_CHAOS = 495; PETNAME_CLAIR = 496; PETNAME_CLOUD = 497; PETNAME_COMET = 498; PETNAME_COMTE = 499; PETNAME_COURT = 500; PETNAME_CRAFT = 501; PETNAME_CRETE = 502; PETNAME_CROWN = 503; PETNAME_DANCE = 504; PETNAME_DANDY = 505; PETNAME_DEVIL = 506; PETNAME_DIANA = 507; PETNAME_DOREE = 508; PETNAME_DREAM = 509; PETNAME_EAGER = 510; PETNAME_EAGLE = 511; PETNAME_EBONY = 512; PETNAME_EISEN = 513; PETNAME_EMBER = 514; PETNAME_ENGEL = 515; PETNAME_FAIRY = 516; PETNAME_FATTY = 517; PETNAME_FEDER = 518; PETNAME_FEUER = 519; PETNAME_FIERE = 520; PETNAME_FIERY = 521; PETNAME_FINAL = 522; PETNAME_FLARE = 523; PETNAME_FLEET = 524; PETNAME_FLEUR = 525; PETNAME_FLIER = 526; PETNAME_FLOOD = 527; PETNAME_FLORA = 528; PETNAME_FLYER = 529; PETNAME_FRAIS = 530; PETNAME_FROST = 531; PETNAME_FUCHS = 532; PETNAME_GALOP = 533; PETNAME_GEIST = 534; PETNAME_GELBE = 535; PETNAME_GHOST = 536; PETNAME_GLORY = 537; PETNAME_GRAND = 538; PETNAME_GREAT = 539; PETNAME_GREEN = 540; PETNAME_GUTER = 541; PETNAME_GUTES = 542; PETNAME_HEART = 543; PETNAME_HELLE = 544; PETNAME_HIDEN = 545; PETNAME_HITEN = 546; PETNAME_HIVER = 547; PETNAME_HOBBY = 548; PETNAME_HYPER = 549; PETNAME_IVORY = 550; PETNAME_JAUNE = 551; PETNAME_JEUNE = 552; PETNAME_JINPU = 553; PETNAME_JOLIE = 554; PETNAME_JOLLY = 555; PETNAME_KLUGE = 556; PETNAME_KNIFE = 557; PETNAME_KOMET = 558; PETNAME_KUGEL = 559; PETNAME_LAHME = 560; PETNAME_LESTE = 561; PETNAME_LIGHT = 562; PETNAME_LILAS = 563; PETNAME_LUCKY = 564; PETNAME_LUNAR = 565; PETNAME_LUTIN = 566; PETNAME_MAGIC = 567; PETNAME_MERRY = 568; PETNAME_METAL = 569; PETNAME_NATSU = 570; PETNAME_NEDDY = 571; PETNAME_NIGHT = 572; PETNAME_NINJA = 573; PETNAME_NOBLE = 574; PETNAME_NOIRE = 575; PETNAME_NUAGE = 576; PETNAME_OCREE = 577; PETNAME_OLIVE = 578; PETNAME_OLLER = 579; PETNAME_OLLES = 580; PETNAME_OMEGA = 581; PETNAME_OPALE = 582; PETNAME_ORAGE = 583; PETNAME_PATTE = 584; PETNAME_PEACE = 585; PETNAME_PENNE = 586; PETNAME_PETIT = 587; PETNAME_PFEIL = 588; PETNAME_PLUIE = 589; PETNAME_PLUME = 590; PETNAME_PLUTO = 591; PETNAME_POINT = 592; PETNAME_POMME = 593; PETNAME_POWER = 594; PETNAME_QUAKE = 595; PETNAME_QUEEN = 596; PETNAME_QUEUE = 597; PETNAME_REINE = 598; PETNAME_REPPU = 599; PETNAME_RICHE = 600; PETNAME_RIEUR = 601; PETNAME_ROTER = 602; PETNAME_ROTES = 603; PETNAME_ROUGE = 604; PETNAME_ROYAL = 605; PETNAME_RUBIN = 606; PETNAME_RUBIS = 607; PETNAME_SAURE = 608; PETNAME_SERRE = 609; PETNAME_SMALT = 610; PETNAME_SNOWY = 611; PETNAME_SOLAR = 612; PETNAME_SPARK = 613; PETNAME_SPEED = 614; PETNAME_STEED = 615; PETNAME_STERN = 616; PETNAME_STONE = 617; PETNAME_STORM = 618; PETNAME_STURM = 619; PETNAME_STUTE = 620; PETNAME_SUPER = 621; PETNAME_SWEEP = 622; PETNAME_SWEET = 623; PETNAME_SWIFT = 624; PETNAME_TALON = 625; PETNAME_TEIOH = 626; PETNAME_TITAN = 627; PETNAME_TURBO = 628; PETNAME_ULTRA = 629; PETNAME_URARA = 630; PETNAME_VENUS = 631; PETNAME_VERTE = 632; PETNAME_VERVE = 633; PETNAME_VIVID = 634; PETNAME_VOGEL = 635; PETNAME_YOUNG = 636; PETNAME_ZIPPY = 637; PETNAME_AIRAIN = 638; PETNAME_AMBREE = 639; PETNAME_AMIRAL = 640; PETNAME_ARASHI = 641; PETNAME_ARCHER = 642; PETNAME_ARDENT = 643; PETNAME_ARGENT = 644; PETNAME_AUDACE = 645; PETNAME_AUTUMN = 646; PETNAME_BATTLE = 647; PETNAME_BEAUTE = 648; PETNAME_BEAUTY = 649; PETNAME_BEETLE = 650; PETNAME_BLAUER = 651; PETNAME_BLAUES = 652; PETNAME_BLEUET = 653; PETNAME_BLONDE = 654; PETNAME_BONBON = 655; PETNAME_BREEZE = 656; PETNAME_BRONZE = 657; PETNAME_BRUMBY = 658; PETNAME_BUCKER = 659; PETNAME_CAESAR = 660; PETNAME_CARMIN = 661; PETNAME_CERISE = 662; PETNAME_CERULE = 663; PETNAME_CHANCE = 664; PETNAME_CINDER = 665; PETNAME_CITRON = 666; PETNAME_CLAIRE = 667; PETNAME_COBALT = 668; PETNAME_CORAIL = 669; PETNAME_COURTE = 670; PETNAME_CUIVRE = 671; PETNAME_DANCER = 672; PETNAME_DARING = 673; PETNAME_DESERT = 674; PETNAME_DOBBIN = 675; PETNAME_DUNKLE = 676; PETNAME_ELANCE = 677; PETNAME_EMBLEM = 678; PETNAME_ENZIAN = 679; PETNAME_ESPRIT = 680; PETNAME_ETOILE = 681; PETNAME_FILANT = 682; PETNAME_FLAMME = 683; PETNAME_FLECHE = 684; PETNAME_FLIGHT = 685; PETNAME_FLINKE = 686; PETNAME_FLOWER = 687; PETNAME_FLURRY = 688; PETNAME_FLYING = 689; PETNAME_FOREST = 690; PETNAME_FREEZE = 691; PETNAME_FREUND = 692; PETNAME_FRIEND = 693; PETNAME_FROSTY = 694; PETNAME_FROZEN = 695; PETNAME_FUBUKI = 696; PETNAME_GALAXY = 697; PETNAME_GANGER = 698; PETNAME_GELBER = 699; PETNAME_GELBES = 700; PETNAME_GINGER = 701; PETNAME_GLOIRE = 702; PETNAME_GLORIE = 703; PETNAME_GOEMON = 704; PETNAME_GRANDE = 705; PETNAME_GRENAT = 706; PETNAME_GROOVE = 707; PETNAME_GROSSE = 708; PETNAME_GRUENE = 709; PETNAME_GUSTAV = 710; PETNAME_HAYATE = 711; PETNAME_HELDIN = 712; PETNAME_HELLER = 713; PETNAME_HELLES = 714; PETNAME_HENGST = 715; PETNAME_HERMES = 716; PETNAME_HERZOG = 717; PETNAME_HIMMEL = 718; PETNAME_HUMBLE = 719; PETNAME_IDATEN = 720; PETNAME_IMPACT = 721; PETNAME_INDIGO = 722; PETNAME_JAGGER = 723; PETNAME_JASMIN = 724; PETNAME_JOYEUX = 725; PETNAME_JUNGLE = 726; PETNAME_KAISER = 727; PETNAME_KEFFEL = 728; PETNAME_KLEINE = 729; PETNAME_KLUGER = 730; PETNAME_KLUGES = 731; PETNAME_KOLOSS = 732; PETNAME_LAHMER = 733; PETNAME_LAHMES = 734; PETNAME_LANCER = 735; PETNAME_LANDER = 736; PETNAME_LAUREL = 737; PETNAME_LEAPER = 738; PETNAME_LEGEND = 739; PETNAME_LIMBER = 740; PETNAME_LONGUE = 741; PETNAME_MELODY = 742; PETNAME_METEOR = 743; PETNAME_MIRAGE = 744; PETNAME_MISTER = 745; PETNAME_MOTION = 746; PETNAME_MUGUET = 747; PETNAME_NATURE = 748; PETNAME_NEBULA = 749; PETNAME_NETHER = 750; PETNAME_NIMBLE = 751; PETNAME_OLYMPE = 752; PETNAME_ORCHID = 753; PETNAME_OUTLAW = 754; PETNAME_PASSER = 755; PETNAME_PASTEL = 756; PETNAME_PELTER = 757; PETNAME_PENSEE = 758; PETNAME_PETITE = 759; PETNAME_PIMENT = 760; PETNAME_POETIC = 761; PETNAME_POULET = 762; PETNAME_PRESTE = 763; PETNAME_PRETTY = 764; PETNAME_PRINCE = 765; PETNAME_PURETE = 766; PETNAME_QUARTZ = 767; PETNAME_QUASAR = 768; PETNAME_RAFALE = 769; PETNAME_RAGING = 770; PETNAME_RAIDEN = 771; PETNAME_RAMAGE = 772; PETNAME_RAPIDE = 773; PETNAME_REICHE = 774; PETNAME_REMIGE = 775; PETNAME_RIEUSE = 776; PETNAME_RISING = 777; PETNAME_ROBUST = 778; PETNAME_ROYALE = 779; PETNAME_RUDOLF = 780; PETNAME_RUNNER = 781; PETNAME_SADDLE = 782; PETNAME_SAFRAN = 783; PETNAME_SAKURA = 784; PETNAME_SAPHIR = 785; PETNAME_SATURN = 786; PETNAME_SCHUSS = 787; PETNAME_SEKITO = 788; PETNAME_SELENE = 789; PETNAME_SENDEN = 790; PETNAME_SEREIN = 791; PETNAME_SHADOW = 792; PETNAME_SHIDEN = 793; PETNAME_SHINPU = 794; PETNAME_SIEGER = 795; PETNAME_SILBER = 796; PETNAME_SILENT = 797; PETNAME_SILVER = 798; PETNAME_SILVER = 799; PETNAME_SOLEIL = 800; PETNAME_SOMBRE = 801; PETNAME_SORREL = 802; PETNAME_SPHENE = 803; PETNAME_SPIRIT = 804; PETNAME_SPRING = 805; PETNAME_STREAM = 806; PETNAME_STRIKE = 807; PETNAME_SUMMER = 808; PETNAME_TEKIRO = 809; PETNAME_TERROR = 810; PETNAME_TICKET = 811; PETNAME_TIMIDE = 812; PETNAME_TOPAZE = 813; PETNAME_TULIPE = 814; PETNAME_TYCOON = 815; PETNAME_ULTIME = 816; PETNAME_URANUS = 817; PETNAME_VELOCE = 818; PETNAME_VELVET = 819; PETNAME_VICTOR = 820; PETNAME_VIOLET = 821; PETNAME_WALKER = 822; PETNAME_WEISSE = 823; PETNAME_WINGED = 824; PETNAME_WINNER = 825; PETNAME_WINNER = 826; PETNAME_WINTER = 827; PETNAME_WONDER = 828; PETNAME_XANTHE = 829; PETNAME_YELLOW = 830; PETNAME_ZEPHYR = 831; PETNAME_ARDENTE = 832; PETNAME_AUTOMNE = 833; PETNAME_AVENGER = 834; PETNAME_BARONNE = 835; PETNAME_BATTANT = 836; PETNAME_BLAZING = 837; PETNAME_BLITZER = 838; PETNAME_CAMELIA = 839; PETNAME_CANDIDE = 840; PETNAME_CARAMEL = 841; PETNAME_CELESTE = 842; PETNAME_CERULEE = 843; PETNAME_CHARBON = 844; PETNAME_CHARGER = 845; PETNAME_CHARIOT = 846; PETNAME_CLIPPER = 847; PETNAME_COUREUR = 848; PETNAME_CRIMSON = 849; PETNAME_CRISTAL = 850; PETNAME_CRYSTAL = 851; PETNAME_CUIVREE = 852; PETNAME_CYCLONE = 853; PETNAME_DANCING = 854; PETNAME_DANSEUR = 855; PETNAME_DIAMANT = 856; PETNAME_DIAMOND = 857; PETNAME_DRAFTER = 858; PETNAME_DUNKLER = 859; PETNAME_DUNKLES = 860; PETNAME_EASTERN = 861; PETNAME_EINHORN = 862; PETNAME_ELANCEE = 863; PETNAME_ELEGANT = 864; PETNAME_EMPEROR = 865; PETNAME_EMPRESS = 866; PETNAME_EXPRESS = 867; PETNAME_FARCEUR = 868; PETNAME_FEATHER = 869; PETNAME_FIGHTER = 870; PETNAME_FILANTE = 871; PETNAME_FLINKER = 872; PETNAME_FLINKES = 873; PETNAME_FORTUNE = 874; PETNAME_FRAICHE = 875; PETNAME_GAGNANT = 876; PETNAME_GALAXIE = 877; PETNAME_GALLANT = 878; PETNAME_GENESIS = 879; PETNAME_GEOELTE = 880; PETNAME_GROSSER = 881; PETNAME_GROSSES = 882; PETNAME_GRUENER = 883; PETNAME_GRUENES = 884; PETNAME_HARMONY = 885; PETNAME_HEROINE = 886; PETNAME_IKEZUKI = 887; PETNAME_IMPULSE = 888; PETNAME_JAVELIN = 889; PETNAME_JOYEUSE = 890; PETNAME_JUMPING = 891; PETNAME_JUPITER = 892; PETNAME_JUSTICE = 893; PETNAME_KLEINER = 894; PETNAME_KLEINES = 895; PETNAME_LAVANDE = 896; PETNAME_LEAPING = 897; PETNAME_LEGENDE = 898; PETNAME_LIBERTY = 899; PETNAME_LICORNE = 900; PETNAME_MAJESTY = 901; PETNAME_MARQUIS = 902; PETNAME_MAXIMAL = 903; PETNAME_MELODIE = 904; PETNAME_MERCURY = 905; PETNAME_MILLION = 906; PETNAME_MIRACLE = 907; PETNAME_MUSASHI = 908; PETNAME_MUSTANG = 909; PETNAME_NACARAT = 910; PETNAME_NATURAL = 911; PETNAME_NEMESIS = 912; PETNAME_NEPTUNE = 913; PETNAME_OEILLET = 914; PETNAME_OPTIMAL = 915; PETNAME_ORAGEUX = 916; PETNAME_OURAGAN = 917; PETNAME_PAPRIKA = 918; PETNAME_PARFAIT = 919; PETNAME_PARTNER = 920; PETNAME_PATIENT = 921; PETNAME_PATURON = 922; PETNAME_PEGASUS = 923; PETNAME_PENSIVE = 924; PETNAME_PERFECT = 925; PETNAME_PEUREUX = 926; PETNAME_PHOENIX = 927; PETNAME_PLUMAGE = 928; PETNAME_POURPRE = 929; PETNAME_POUSSIN = 930; PETNAME_PRANCER = 931; PETNAME_PREMIUM = 932; PETNAME_QUANTUM = 933; PETNAME_RADIANT = 934; PETNAME_RAINBOW = 935; PETNAME_RATTLER = 936; PETNAME_REICHER = 937; PETNAME_REICHES = 938; PETNAME_ROUGHIE = 939; PETNAME_SAMURAI = 940; PETNAME_SAUTANT = 941; PETNAME_SCARLET = 942; PETNAME_SCHWEIF = 943; PETNAME_SEREINE = 944; PETNAME_SERGENT = 945; PETNAME_SHINDEN = 946; PETNAME_SHINING = 947; PETNAME_SHOOTER = 948; PETNAME_SMOKING = 949; PETNAME_SOUFFLE = 950; PETNAME_SPECIAL = 951; PETNAME_STYLISH = 952; PETNAME_SUMPTER = 953; PETNAME_TEMPEST = 954; PETNAME_TEMPETE = 955; PETNAME_THUNDER = 956; PETNAME_TORNADO = 957; PETNAME_TORPEDO = 958; PETNAME_TRISTAN = 959; PETNAME_TROOPER = 960; PETNAME_TROTTER = 961; PETNAME_TYPHOON = 962; PETNAME_UNICORN = 963; PETNAME_VENGEUR = 964; PETNAME_VERMEIL = 965; PETNAME_VICTORY = 966; PETNAME_WARRIOR = 967; PETNAME_WEISSER = 968; PETNAME_WEISSES = 969; PETNAME_WESTERN = 970; PETNAME_WHISPER = 971; PETNAME_WINNING = 972; PETNAME_ZETSUEI = 973; PETNAME_ZILLION = 974; PETNAME_BARONESS = 975; PETNAME_BATTANTE = 976; PETNAME_BLIZZARD = 977; PETNAME_CANNELLE = 978; PETNAME_CAPUCINE = 979; PETNAME_CERULEAN = 980; PETNAME_CHANCEUX = 981; PETNAME_CHARISMA = 982; PETNAME_CHARMANT = 983; PETNAME_CHOCOLAT = 984; PETNAME_CLAYBANK = 985; PETNAME_COMTESSE = 986; PETNAME_COUREUSE = 987; PETNAME_DANSEUSE = 988; PETNAME_DUCHESSE = 989; PETNAME_ECARLATE = 990; PETNAME_ELEGANTE = 991; PETNAME_EMERAUDE = 992; PETNAME_FARCEUSE = 993; PETNAME_FARFADET = 994; PETNAME_FRINGANT = 995; PETNAME_GAGNANTE = 996; PETNAME_GALLOPER = 997; PETNAME_GALOPANT = 998; PETNAME_GEOELTER = 999; PETNAME_GEOELTES = 1000; PETNAME_GESCHOSS = 1001; PETNAME_GORGEOUS = 1002; PETNAME_HANAKAZE = 1003; PETNAME_HIGHLAND = 1004; PETNAME_HYPERION = 1005; PETNAME_ILLUSION = 1006; PETNAME_IMMORTAL = 1007; PETNAME_IMPERIAL = 1008; PETNAME_INCARNAT = 1009; PETNAME_INFINITY = 1010; PETNAME_INNOCENT = 1011; PETNAME_JACINTHE = 1012; PETNAME_KAISERIN = 1013; PETNAME_KRISTALL = 1014; PETNAME_MAHARAJA = 1015; PETNAME_MAHARANI = 1016; PETNAME_MARQUISE = 1017; PETNAME_MATAEMON = 1018; PETNAME_MEILLEUR = 1019; PETNAME_MERCEDES = 1020; PETNAME_MYOSOTIS = 1021; PETNAME_NEBULOUS = 1022; PETNAME_NEGATIVE = 1023; PETNAME_NENUPHAR = 1024; PETNAME_NORTHERN = 1025; PETNAME_NORTHERN = 1026; PETNAME_OBSIDIAN = 1027; PETNAME_ORAGEUSE = 1028; PETNAME_ORCHIDEE = 1029; PETNAME_PARFAITE = 1030; PETNAME_PATIENTE = 1031; PETNAME_PEUREUSE = 1032; PETNAME_POSITIVE = 1033; PETNAME_PRINCELY = 1034; PETNAME_PRINCESS = 1035; PETNAME_PRODIGUE = 1036; PETNAME_PUISSANT = 1037; PETNAME_RESTLESS = 1038; PETNAME_RHAPSODY = 1039; PETNAME_ROADSTER = 1040; PETNAME_RUTILANT = 1041; PETNAME_SAUTANTE = 1042; PETNAME_SCHWARZE = 1043; PETNAME_SHOOTING = 1044; PETNAME_SILBERNE = 1045; PETNAME_SOUTHERN = 1046; PETNAME_SPECIALE = 1047; PETNAME_STALLION = 1048; PETNAME_STARDUST = 1049; PETNAME_SURUSUMI = 1050; PETNAME_TONNERRE = 1051; PETNAME_TROTTEUR = 1052; PETNAME_ULTIMATE = 1053; PETNAME_UNIVERSE = 1054; PETNAME_VAILLANT = 1055; PETNAME_VENGEUSE = 1056; PETNAME_XANTHOUS = 1057; PETNAME_ZEPPELIN = 1058; PETNAME_AMBITIOUS = 1059; PETNAME_AUDACIEUX = 1060; PETNAME_BALLISTIC = 1061; PETNAME_BEAUTIFUL = 1062; PETNAME_BRILLIANT = 1063; PETNAME_CAMPANULE = 1064; PETNAME_CAPITAINE = 1065; PETNAME_CHANCEUSE = 1066; PETNAME_CHARMANTE = 1067; PETNAME_CLEMATITE = 1068; PETNAME_CLOCHETTE = 1069; PETNAME_CORIANDRE = 1070; PETNAME_CRACKLING = 1071; PETNAME_DESTROYER = 1072; PETNAME_EXCELLENT = 1073; PETNAME_FANTASTIC = 1074; PETNAME_FEATHERED = 1075; PETNAME_FRINGANTE = 1076; PETNAME_GALOPANTE = 1077; PETNAME_GINGEMBRE = 1078; PETNAME_HURRICANE = 1079; PETNAME_ICHIMONJI = 1080; PETNAME_IMPETUEUX = 1081; PETNAME_INCARNATE = 1082; PETNAME_LIGHTNING = 1083; PETNAME_MATSUKAZE = 1084; PETNAME_MEILLEURE = 1085; PETNAME_MENESTREL = 1086; PETNAME_MERCILESS = 1087; PETNAME_PENDRAGON = 1088; PETNAME_PRINCESSE = 1089; PETNAME_PRINTEMPS = 1090; PETNAME_PUISSANTE = 1091; PETNAME_QUADRILLE = 1092; PETNAME_ROSINANTE = 1093; PETNAME_RUTILANTE = 1094; PETNAME_SCHWARZER = 1095; PETNAME_SCHWARZES = 1096; PETNAME_SILBERNER = 1097; PETNAME_SILBERNES = 1098; PETNAME_SPARKLING = 1099; PETNAME_SPEEDSTER = 1100; PETNAME_TOURNESOL = 1101; PETNAME_TRANSIENT = 1102; PETNAME_TROTTEUSE = 1103; PETNAME_TURBULENT = 1104; PETNAME_TWINKLING = 1105; PETNAME_VAILLANTE = 1106; PETNAME_VALENTINE = 1107; PETNAME_VELOCIOUS = 1108; PETNAME_VERMEILLE = 1109; PETNAME_WONDERFUL = 1110; PETNAME_AMATSUKAZE = 1111; PETNAME_AUDACIEUSE = 1112; PETNAME_BENEVOLENT = 1113; PETNAME_BLISTERING = 1114; PETNAME_BRILLIANCE = 1115; PETNAME_BUCEPHALUS = 1116; PETNAME_CHALLENGER = 1117; PETNAME_EXCELLENTE = 1118; PETNAME_IMPETUEUSE = 1119; PETNAME_INVINCIBLE = 1120; PETNAME_MALEVOLENT = 1121; PETNAME_MILLENNIUM = 1122; PETNAME_TRANQUILLE = 1123; PETNAME_TURBULENTE = 1124; PETNAME_DESTRUCTION = 1125; PETNAME_FIRECRACKER = 1126; ----------------------------------- -- Summoner ----------------------------------- PET_FIRE_SPIRIT = 0; PET_ICE_SPIRIT = 1; PET_AIR_SPIRIT = 2; PET_EARTH_SPIRIT = 3; PET_THUNDER_SPIRIT = 4; PET_WATER_SPIRIT = 5; PET_LIGHT_SPIRIT = 6; PET_DARK_SPIRIT = 7; PET_CARBUNCLE = 8; PET_FENRIR = 9; PET_IFRIT = 10; PET_TITAN = 11; PET_LEVIATHAN = 12; PET_GARUDA = 13; PET_SHIVA = 14; PET_RAMUH = 15; PET_DIABOLOS = 16; PET_ALEXANDER = 17; PET_ODIN = 18; PET_ATOMOS = 19; PET_CAIT_SITH = 20; PET_AUTOMATON = 69; PET_WYVERN = 48; ----------------------------------- -- Beastmaster ----------------------------------- PET_SHEEP_FAMILIAR = 21; PET_HARE_FAMILIAR = 22; PET_CRAB_FAMILIAR = 23; PET_COURIER_CARRIE = 24; PET_HOMUNCULUS = 25; PET_FLYTRAP_FAMILIAR = 26; PET_TIGER_FAMILIAR = 27; PET_FLOWERPOT_BILL = 28; PET_EFT_FAMILIAR = 29; PET_LIZARD_FAMILIAR = 30; PET_MAYFLY_FAMILIAR = 31; PET_FUNGUAR_FAMILIAR = 32; PET_BEETLE_FAMILIAR = 33; PET_ANTLION_FAMILIAR = 34; PET_MITE_FAMILIAR = 35; PET_LULLABY_MELODIA = 36; PET_KEENEARED_STEFFI = 37; PET_FLOWERPOT_BEN = 38; PET_SABER_SIRAVARDE = 39; PET_COLDBLOOD_COMO = 40; PET_SHELLBUSTER_OROB = 41; PET_VORACIOUS_AUDREY = 42; PET_AMBUSHER_ALLIE = 43; PET_LIFEDRINKER_LARS = 44; PET_PANZER_GALAHAD = 45; PET_CHOPSUEY_CHUCKY = 46; PET_AMIGO_SABOTENDER = 47;
gpl-3.0
azekillDIABLO/Voxellar
mods/NODES/stairs/init.lua
1
14778
-- Minetest 0.4 mod: stairs -- See README.txt for licensing and other information. -- Global namespace for functions stairs = {} -- Register aliases for new pine node names minetest.register_alias("stairs:stair_pinewood", "stairs:stair_pine_wood") minetest.register_alias("stairs:slab_pinewood", "stairs:slab_pine_wood") -- Get setting for replace ABM local replace = minetest.settings:get_bool("enable_stairs_replace_abm") local function rotate_and_place(itemstack, placer, pointed_thing) local p0 = pointed_thing.under local p1 = pointed_thing.above local param2 = 0 local placer_pos = placer:getpos() if placer_pos then param2 = minetest.dir_to_facedir(vector.subtract(p1, placer_pos)) end local finepos = minetest.pointed_thing_to_face_pos(placer, pointed_thing) local fpos = finepos.y % 1 if p0.y - 1 == p1.y or (fpos > 0 and fpos < 0.5) or (fpos < -0.5 and fpos > -0.999999999) then param2 = param2 + 20 if param2 == 21 then param2 = 23 elseif param2 == 23 then param2 = 21 end end return minetest.item_place(itemstack, placer, pointed_thing, param2) end -- Register stairs. -- Node will be called stairs:stair_<subname> function stairs.register_stair(subname, recipeitem, groups, images, description, sounds) groups.stair = 1 minetest.register_node(":stairs:stair_" .. subname, { description = description, drawtype = "mesh", mesh = "stairs_stair.obj", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = false, groups = groups, sounds = sounds, selection_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, }, collision_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, {-0.5, 0, 0, 0.5, 0.5, 0.5}, }, }, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end return rotate_and_place(itemstack, placer, pointed_thing) end, }) -- for replace ABM if replace then minetest.register_node(":stairs:stair_" .. subname .. "upside_down", { replace_name = "stairs:stair_" .. subname, groups = {slabs_replace = 1}, }) end if recipeitem then -- Recipe matches appearence in inventory minetest.register_craft({ output = 'stairs:stair_' .. subname .. ' 8', recipe = { {"", "", recipeitem}, {"", recipeitem, recipeitem}, {recipeitem, recipeitem, recipeitem}, }, }) -- Use stairs to craft full blocks again (1:1) minetest.register_craft({ output = recipeitem .. ' 3', recipe = { {'stairs:stair_' .. subname, 'stairs:stair_' .. subname}, {'stairs:stair_' .. subname, 'stairs:stair_' .. subname}, }, }) -- Fuel local baseburntime = minetest.get_craft_result({ method = "fuel", width = 1, items = {recipeitem} }).time if baseburntime > 0 then minetest.register_craft({ type = "fuel", recipe = 'stairs:stair_' .. subname, burntime = math.floor(baseburntime * 0.75), }) end end end -- Slab facedir to placement 6d matching table local slab_trans_dir = {[0] = 8, 0, 2, 1, 3, 4} -- Register slabs. -- Node will be called stairs:slab_<subname> function stairs.register_slab(subname, recipeitem, groups, images, description, sounds) groups.slab = 1 minetest.register_node(":stairs:slab_" .. subname, { description = description, drawtype = "nodebox", tiles = images, paramtype = "light", paramtype2 = "facedir", is_ground_content = false, groups = groups, sounds = sounds, node_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) local under = minetest.get_node(pointed_thing.under) local wield_item = itemstack:get_name() local creative_enabled = (creative and creative.is_enabled_for and creative.is_enabled_for(placer:get_player_name())) if under and under.name:find("stairs:slab_") then -- place slab using under node orientation local dir = minetest.dir_to_facedir(vector.subtract( pointed_thing.above, pointed_thing.under), true) local p2 = under.param2 -- combine two slabs if possible if slab_trans_dir[math.floor(p2 / 4)] == dir and wield_item == under.name then if not recipeitem then return itemstack end local player_name = placer:get_player_name() if minetest.is_protected(pointed_thing.under, player_name) and not minetest.check_player_privs(placer, "protection_bypass") then minetest.record_protection_violation(pointed_thing.under, player_name) return end minetest.set_node(pointed_thing.under, {name = recipeitem, param2 = p2}) if not creative_enabled then itemstack:take_item() end return itemstack end -- Placing a slab on an upside down slab should make it right-side up. if p2 >= 20 and dir == 8 then p2 = p2 - 20 -- same for the opposite case: slab below normal slab elseif p2 <= 3 and dir == 4 then p2 = p2 + 20 end -- else attempt to place node with proper param2 minetest.item_place_node(ItemStack(wield_item), placer, pointed_thing, p2) if not creative_enabled then itemstack:take_item() end return itemstack else return rotate_and_place(itemstack, placer, pointed_thing) end end, }) -- for replace ABM if replace then minetest.register_node(":stairs:slab_" .. subname .. "upside_down", { replace_name = "stairs:slab_".. subname, groups = {slabs_replace = 1}, }) end if recipeitem then minetest.register_craft({ output = 'stairs:slab_' .. subname .. ' 6', recipe = { {recipeitem, recipeitem, recipeitem}, }, }) -- Use 2 slabs to craft a full block again (1:1) minetest.register_craft({ output = recipeitem, recipe = { {'stairs:slab_' .. subname}, {'stairs:slab_' .. subname}, }, }) -- Fuel local baseburntime = minetest.get_craft_result({ method = "fuel", width = 1, items = {recipeitem} }).time if baseburntime > 0 then minetest.register_craft({ type = "fuel", recipe = 'stairs:slab_' .. subname, burntime = math.floor(baseburntime * 0.5), }) end end end -- Optionally replace old "upside_down" nodes with new param2 versions. -- Disabled by default. if replace then minetest.register_abm({ label = "Slab replace", nodenames = {"group:slabs_replace"}, interval = 16, chance = 1, action = function(pos, node) node.name = minetest.registered_nodes[node.name].replace_name node.param2 = node.param2 + 20 if node.param2 == 21 then node.param2 = 23 elseif node.param2 == 23 then node.param2 = 21 end minetest.set_node(pos, node) end, }) end -- Stair/slab registration function. -- Nodes will be called stairs:{stair,slab}_<subname> function stairs.register_stair_and_slab(subname, recipeitem, groups, images, desc_stair, desc_slab, sounds) stairs.register_stair(subname, recipeitem, groups, images, desc_stair, sounds) stairs.register_slab(subname, recipeitem, groups, images, desc_slab, sounds) end -- Register default stairs and slabs stairs.register_stair_and_slab( "wood", "default:wood", {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, {"default_wood.png"}, "Wooden Stair", "Wooden Slab", default.node_sound_wood_defaults() ) stairs.register_stair_and_slab( "junglewood", "default:junglewood", {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, {"default_junglewood.png"}, "Jungle Wood Stair", "Jungle Wood Slab", default.node_sound_wood_defaults() ) stairs.register_stair_and_slab( "pine_wood", "default:pine_wood", {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3}, {"default_pine_wood.png"}, "Pine Wood Stair", "Pine Wood Slab", default.node_sound_wood_defaults() ) stairs.register_stair_and_slab( "acacia_wood", "default:acacia_wood", {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, {"default_acacia_wood.png"}, "Acacia Wood Stair", "Acacia Wood Slab", default.node_sound_wood_defaults() ) stairs.register_stair_and_slab( "aspen_wood", "default:aspen_wood", {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3}, {"default_aspen_wood.png"}, "Aspen Wood Stair", "Aspen Wood Slab", default.node_sound_wood_defaults() ) stairs.register_stair_and_slab( "stone", "default:stone", {cracky = 3}, {"default_stone.png"}, "Stone Stair", "Stone Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "cobble", "default:cobble", {cracky = 3}, {"default_cobble.png"}, "Cobblestone Stair", "Cobblestone Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "mossycobble", "default:mossycobble", {cracky = 3}, {"default_mossycobble.png"}, "Mossy Cobblestone Stair", "Mossy Cobblestone Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "stonebrick", "default:stonebrick", {cracky = 2}, {"default_stone_brick.png"}, "Stone Brick Stair", "Stone Brick Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "stone_block", "default:stone_block", {cracky = 2}, {"default_stone_block.png"}, "Stone Block Stair", "Stone Block Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "desert_stone", "default:desert_stone", {cracky = 3}, {"default_desert_stone.png"}, "Desert Stone Stair", "Desert Stone Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "desert_cobble", "default:desert_cobble", {cracky = 3}, {"default_desert_cobble.png"}, "Desert Cobblestone Stair", "Desert Cobblestone Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "desert_stonebrick", "default:desert_stonebrick", {cracky = 2}, {"default_desert_stone_brick.png"}, "Desert Stone Brick Stair", "Desert Stone Brick Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "desert_stone_block", "default:desert_stone_block", {cracky = 2}, {"default_desert_stone_block.png"}, "Desert Stone Block Stair", "Desert Stone Block Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "sandstone", "default:sandstone", {crumbly = 1, cracky = 3}, {"default_sandstone.png"}, "Sandstone Stair", "Sandstone Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "sandstonebrick", "default:sandstonebrick", {cracky = 2}, {"default_sandstone_brick.png"}, "Sandstone Brick Stair", "Sandstone Brick Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "sandstone_block", "default:sandstone_block", {cracky = 2}, {"default_sandstone_block.png"}, "Sandstone Block Stair", "Sandstone Block Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "desert_sandstone", "default:desert_sandstone", {crumbly = 1, cracky = 3}, {"default_desert_sandstone.png"}, "Desert Sandstone Stair", "Desert Sandstone Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "desert_sandstone_brick", "default:desert_sandstone_brick", {cracky = 2}, {"default_desert_sandstone_brick.png"}, "Desert Sandstone Brick Stair", "Desert Sandstone Brick Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "desert_sandstone_block", "default:desert_sandstone_block", {cracky = 2}, {"default_desert_sandstone_block.png"}, "Desert Sandstone Block Stair", "Desert Sandstone Block Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "silver_sandstone", "default:silver_sandstone", {crumbly = 1, cracky = 3}, {"default_silver_sandstone.png"}, "Silver Sandstone Stair", "Silver Sandstone Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "silver_sandstone_brick", "default:silver_sandstone_brick", {cracky = 2}, {"default_silver_sandstone_brick.png"}, "Silver Sandstone Brick Stair", "Silver Sandstone Brick Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "silver_sandstone_block", "default:silver_sandstone_block", {cracky = 2}, {"default_silver_sandstone_block.png"}, "Silver Sandstone Block Stair", "Silver Sandstone Block Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "obsidian", "default:obsidian", {cracky = 1, level = 2}, {"default_obsidian.png"}, "Obsidian Stair", "Obsidian Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "obsidianbrick", "default:obsidianbrick", {cracky = 1, level = 2}, {"default_obsidian_brick.png"}, "Obsidian Brick Stair", "Obsidian Brick Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "obsidian_block", "default:obsidian_block", {cracky = 1, level = 2}, {"default_obsidian_block.png"}, "Obsidian Block Stair", "Obsidian Block Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "brick", "default:brick", {cracky = 3}, {"default_brick.png"}, "Brick Stair", "Brick Slab", default.node_sound_stone_defaults() ) stairs.register_stair_and_slab( "straw", "farming:straw", {snappy = 3, flammable = 4}, {"farming_straw.png"}, "Straw Stair", "Straw Slab", default.node_sound_leaves_defaults() ) stairs.register_stair_and_slab( "steelblock", "default:steelblock", {cracky = 1, level = 2}, {"default_steel_block.png"}, "Steel Block Stair", "Steel Block Slab", default.node_sound_metal_defaults() ) stairs.register_stair_and_slab( "copperblock", "default:copperblock", {cracky = 1, level = 2}, {"default_copper_block.png"}, "Copper Block Stair", "Copper Block Slab", default.node_sound_metal_defaults() ) stairs.register_stair_and_slab( "bronzeblock", "default:bronzeblock", {cracky = 1, level = 2}, {"default_bronze_block.png"}, "Bronze Block Stair", "Bronze Block Slab", default.node_sound_metal_defaults() ) stairs.register_stair_and_slab( "goldblock", "default:goldblock", {cracky = 1}, {"default_gold_block.png"}, "Gold Block Stair", "Gold Block Slab", default.node_sound_metal_defaults() ) stairs.register_stair_and_slab( "ice", "default:ice", {cracky = 3, puts_out_fire = 1, cools_lava = 1}, {"default_ice.png"}, "Ice Stair", "Ice Slab", default.node_sound_glass_defaults() ) stairs.register_stair_and_slab( "snowblock", "default:snowblock", {crumbly = 3, puts_out_fire = 1, cools_lava = 1, snowy = 1}, {"default_snow.png"}, "Snow Block Stair", "Snow Block Slab", default.node_sound_dirt_defaults({ footstep = {name = "default_snow_footstep", gain = 0.15}, dug = {name = "default_snow_footstep", gain = 0.2}, dig = {name = "default_snow_footstep", gain = 0.2} }) )
lgpl-2.1
ffxiphoenix/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Kabihyam.lua
34
1033
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Kabihyam -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00F5); 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
ffxiphoenix/darkstar
scripts/globals/items/bastore_sardine.lua
18
1337
----------------------------------------- -- ID: 5792 -- Item: Bastore Sardine -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 1 -- Mind -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end 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,5792); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_MND, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_MND, -3); end;
gpl-3.0
bgarrels/vlc-2.1
share/lua/playlist/pluzz.lua
105
3740
--[[ $Id$ Copyright © 2011 VideoLAN Authors: Ludovic Fauvet <etix at l0cal dot com> 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "pluzz.fr/%w+" ) or string.match( vlc.path, "info.francetelevisions.fr/.+") or string.match( vlc.path, "france4.fr/%w+") end -- Helpers function key_match( line, key ) return string.match( line, "name=\"" .. key .. "\"" ) end function get_value( line ) local _,_,r = string.find( line, "content=\"(.*)\"" ) return r end -- Parse function. function parse() p = {} if string.match ( vlc.path, "www.pluzz.fr/%w+" ) then while true do line = vlc.readline() if not line then break end if string.match( line, "id=\"current_video\"" ) then _,_,redirect = string.find (line, "href=\"(.-)\"" ) print ("redirecting to: " .. redirect ) return { { path = redirect } } end end end if string.match ( vlc.path, "www.france4.fr/%w+" ) then while true do line = vlc.readline() if not line then break end -- maybe we should get id from tags having video/cappuccino type instead if string.match( line, "id=\"lavideo\"" ) then _,_,redirect = string.find (line, "href=\"(.-)\"" ) print ("redirecting to: " .. redirect ) return { { path = redirect } } end end end if string.match ( vlc.path, "info.francetelevisions.fr/.+" ) then title = "" arturl = "http://info.francetelevisions.fr/video-info/player_sl/Images/PNG/gene_ftv.png" while true do line = vlc.readline() if not line then break end -- Try to find the video's path if key_match( line, "urls--url--video" ) then video = get_value( line ) end -- Try to find the video's title if key_match( line, "vignette--titre--court" ) then title = get_value( line ) title = vlc.strings.resolve_xml_special_chars( title ) print ("playing: " .. title ) end -- Try to find the video's thumbnail if key_match( line, "vignette" ) then arturl = get_value( line ) if not string.match( line, "http://" ) then arturl = "http://info.francetelevisions.fr/" .. arturl end end end if video then -- base url is hardcoded inside a js source file -- see http://www.pluzz.fr/layoutftv/arches/common/javascripts/jquery.player-min.js base_url = "mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/" table.insert( p, { path = base_url .. video; name = title; arturl = arturl; } ) end end return p end
gpl-2.0
ayub-mahabadi/anti-spam-bot
plugins/clash.lua
3
3062
--[[ # # @GPMod # @dragon_born # ]] local apikey = 'Enter Your Clash API here' local function run(msg, matches) if matches[1]:lower() == 'clan' or matches[1]:lower() == 'clash' or matches[1]:lower() == 'clantag' or matches[1]:lower() == 'tag' then local clantag = matches[2] if string.match(matches[2], '^#.+$') then clantag = string.gsub(matches[2], '#', '') end clantag = string.upper(clantag) local curl = 'curl -X GET --header "Accept: application/json" --header "authorization: Bearer '..apikey..'" "https://api.clashofclans.com/v1/clans/%23'..clantag..'"' cmd = io.popen(curl) local result = cmd:read('*all') local jdat = json:decode(result) if jdat.reason then if jdat.reason == 'accessDenied' then return 'برای ثبت API Key خود به سایت زیر بروید\ndeveloper.clashofclans.com' end return '#Error\n'..jdat.reason end local text = 'Clan Tag: '.. jdat.tag text = text..'\nClan Name: '.. jdat.name text = text..'\nDescription: '.. jdat.description text = text..'\nType: '.. jdat.type text = text..'\nWar Frequency: '.. jdat.warFrequency text = text..'\nClan Level: '.. jdat.clanLevel text = text..'\nWar Wins: '.. jdat.warWins text = text..'\nClan Points: '.. jdat.clanPoints text = text..'\nRequired Trophies: '.. jdat.requiredTrophies text = text..'\nMembers: '.. jdat.members text = text..'\n\n@GPMod Team' cmd:close() return text end if matches[1]:lower() == 'members' or matches[1]:lower() == 'clashmembers' or matches[1]:lower() == 'clanmembers' then local members = matches[2] if string.match(matches[2], '^#.+$') then members = string.gsub(matches[2], '#', '') end members = string.upper(members) local curl = 'curl -X GET --header "Accept: application/json" --header "authorization: Bearer '..apikey..'" "https://api.clashofclans.com/v1/clans/%23'..members..'/members"' cmd = io.popen(curl) local result = cmd:read('*all') local jdat = json:decode(result) if jdat.reason then if jdat.reason == 'accessDenied' then return 'برای ثبت API Key خود به سایت زیر بروید\ndeveloper.clashofclans.com' end return '#Error\n'..jdat.reason end local leader = "" local coleader = "" local items = jdat.items leader = 'Clan Moderators: \n' for i = 1, #items do if items[i].role == "leader" then leader = leader.."\nLeader: "..items[i].name.."\nLevel: "..items[i].expLevel end if items[i].role == "coLeader" then coleader = coleader.."\nCo-Leader: "..items[i].name.."\nLevel: "..items[i].expLevel end end text = leader.."\n"..coleader.."\n\nClan Members:" for i = 1, #items do text = text..'\n'..i..'- '..items[i].name..'\nlevel: '..items[i].expLevel.."\n" end text = text.."\n\n@GPMod" cmd:close() return text end end return { patterns = { "^[/!](clash) (.*)$", "^[/!](clan) (.*)$", "^[/!](clantag) (.*)$", "^[/!](tag) (.*)$", "^[/!](clashmembers) (.*)$", "^[/!](clanmembers) (.*)$", "^[/!](members) (.*)$", }, run = run }
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Geltpix.lua
36
1165
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Geltpix -- @zone 80 -- @pos 154 -2 103 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, 7043); -- Don't hurt poor Geltpix! Geltpix's just a merchant from Boodlix's Emporium in Jeuno. Kingdom vendors don't like gil, but Boodlix knows true value of new money. 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